Sfoglia il codice sorgente

Playlists: the daytime, dayofweek and never modes work like in Wallpaper Engine (PlaylistSchedule), items can carry a preset (wpresets lookup), logon steps one item per login session (state file under XDG_STATE_HOME), transition random picks one of our transitions per switch. Audio: --audio-input, --audio-input-volume, --audio-input-threshold, --list-audio-inputs and the matching control file keys; the outgoing wallpaper is silenced while the next one is being built during a switch. Rendering: material constants of model parts with an animation or script now run (CMesh::Part), a script that returns a string for a vector property (Vec + number) is read like WE's Vec constructors, scripts on particle instanceoverride keys run and a particle file's second (spritetrail) renderer is drawn, a solid layer with a user image covers the layer instead of stretching, GLSL max/min accept mixed scalar and vector arguments, uniform declarations with extra spaces or tabs keep their type, invalid combo JSON in a shader is skipped without an error like WE does. Build: opt-in LWE_LTO and LWE_LINK_TRIM. Code quality: PVS-Studio and clang-tidy findings worked through (logged empty catches, nodiscard results used, float comparisons, narrowing casts, default member initialisers in ApplicationContext), the whole scene library renders pixel identical to before the cleanup; 424 unit tests, clang-format 22 clean. Linux VM harness: fake ffmpeg release for the video check, SteamOS launch of the rule test programs, per-disk lock in the icons matrix, Manjaro update popups closed.

UwU 2 settimane fa
parent
commit
e66381c772
100 ha cambiato i file con 2820 aggiunte e 1077 eliminazioni
  1. 24 0
      CMakeLists.txt
  2. 8 2
      README.md
  3. 248 35
      src/WallpaperEngine/Application/ApplicationContext.cpp
  4. 98 36
      src/WallpaperEngine/Application/ApplicationContext.h
  5. 439 0
      src/WallpaperEngine/Application/PlaylistSchedule.cpp
  6. 65 0
      src/WallpaperEngine/Application/PlaylistSchedule.h
  7. 323 39
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  8. 29 8
      src/WallpaperEngine/Application/WallpaperApplication.h
  9. 11 10
      src/WallpaperEngine/Assets/AssetLocator.h
  10. 1 1
      src/WallpaperEngine/Audio/AudioContext.h
  11. 16 0
      src/WallpaperEngine/Audio/AudioInput.h
  12. 19 21
      src/WallpaperEngine/Audio/AudioStream.cpp
  13. 2 0
      src/WallpaperEngine/Audio/AudioStream.h
  14. 1 1
      src/WallpaperEngine/Audio/Drivers/AudioDriver.h
  15. 234 18
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp
  16. 31 0
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h
  17. 9 6
      src/WallpaperEngine/Audio/SpectrumAnalyzer.cpp
  18. 5 0
      src/WallpaperEngine/Audio/SpectrumAnalyzer.h
  19. 11 7
      src/WallpaperEngine/Data/Builders/ColorBuilder.cpp
  20. 1 1
      src/WallpaperEngine/Data/Builders/UserSettingBuilder.h
  21. 6 2
      src/WallpaperEngine/Data/Builders/VectorBuilder.h
  22. 1 1
      src/WallpaperEngine/Data/JSON.h
  23. 6 7
      src/WallpaperEngine/Data/Model/DynamicValue.cpp
  24. 1 0
      src/WallpaperEngine/Data/Model/DynamicValue.h
  25. 3 3
      src/WallpaperEngine/Data/Model/Object.h
  26. 3 3
      src/WallpaperEngine/Data/Parsers/DynamicValueParser.cpp
  27. 1 1
      src/WallpaperEngine/Data/Parsers/EffectParser.cpp
  28. 3 1
      src/WallpaperEngine/Data/Parsers/MaterialParser.cpp
  29. 9 9
      src/WallpaperEngine/Data/Parsers/ObjectParser.cpp
  30. 3 1
      src/WallpaperEngine/Data/Parsers/TextureParser.cpp
  31. 98 0
      src/WallpaperEngine/Data/Utils/DecimalNumber.h
  32. 1 1
      src/WallpaperEngine/Data/Utils/ScopeGuard.h
  33. 9 11
      src/WallpaperEngine/Debugging/CallStack.cpp
  34. 9 8
      src/WallpaperEngine/Debugging/CallStack.h
  35. 95 0
      src/WallpaperEngine/Desktop/DlopenX11.h
  36. 2 2
      src/WallpaperEngine/Desktop/HostWayland.cpp
  37. 24 24
      src/WallpaperEngine/Desktop/IconTheme.cpp
  38. 3 0
      src/WallpaperEngine/Desktop/IconTheme.h
  39. 0 2
      src/WallpaperEngine/Desktop/KWinScript.cpp
  40. 16 43
      src/WallpaperEngine/Desktop/PowerMonitor.cpp
  41. 13 41
      src/WallpaperEngine/Desktop/SessionMonitor.cpp
  42. 4 17
      src/WallpaperEngine/Desktop/UserShortcut.cpp
  43. 1 1
      src/WallpaperEngine/Desktop/UserShortcut.h
  44. 28 25
      src/WallpaperEngine/FileSystem/Adapters/Directory.cpp
  45. 1 1
      src/WallpaperEngine/FileSystem/Adapters/MediaCover.h
  46. 3 1
      src/WallpaperEngine/FileSystem/Adapters/Types.h
  47. 2 2
      src/WallpaperEngine/FileSystem/Container.h
  48. 19 0
      src/WallpaperEngine/FileSystem/StateDirectory.h
  49. 2 2
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp
  50. 1 1
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.h
  51. 42 44
      src/WallpaperEngine/Led/OpenRgbProtocol.h
  52. 3 5
      src/WallpaperEngine/Maths.cpp
  53. 1 1
      src/WallpaperEngine/Media/CoverDownloader.cpp
  54. 24 35
      src/WallpaperEngine/Media/DBusMediaSource.cpp
  55. 2 2
      src/WallpaperEngine/Media/MediaSource.cpp
  56. 3 3
      src/WallpaperEngine/Render/AlbumTexture.cpp
  57. 1 1
      src/WallpaperEngine/Render/AlbumTexture.h
  58. 40 45
      src/WallpaperEngine/Render/CFBO.cpp
  59. 4 4
      src/WallpaperEngine/Render/CFBO.h
  60. 1 1
      src/WallpaperEngine/Render/CObject.cpp
  61. 1 1
      src/WallpaperEngine/Render/CObject.h
  62. 12 6
      src/WallpaperEngine/Render/CTexture.cpp
  63. 9 7
      src/WallpaperEngine/Render/CWallpaper.cpp
  64. 8 4
      src/WallpaperEngine/Render/CWallpaper.h
  65. 0 2
      src/WallpaperEngine/Render/Camera.cpp
  66. 1 1
      src/WallpaperEngine/Render/Camera.h
  67. 14 10
      src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp
  68. 25 88
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp
  69. 3 3
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.h
  70. 4 11
      src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.cpp
  71. 1 1
      src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.h
  72. 1 6
      src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.cpp
  73. 2 2
      src/WallpaperEngine/Render/Drivers/Output/Output.cpp
  74. 1 1
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  75. 2 2
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h
  76. 16 46
      src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
  77. 32 1
      src/WallpaperEngine/Render/Drivers/VideoDriver.cpp
  78. 9 0
      src/WallpaperEngine/Render/Drivers/VideoDriver.h
  79. 5 5
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
  80. 2 2
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h
  81. 27 0
      src/WallpaperEngine/Render/Drivers/X11RandR.h
  82. 22 9
      src/WallpaperEngine/Render/Drivers/X11WindowType.h
  83. 1 2
      src/WallpaperEngine/Render/Fonts/SystemFonts.cpp
  84. 5 21
      src/WallpaperEngine/Render/FrameMaterial.cpp
  85. 26 0
      src/WallpaperEngine/Render/Helpers/ShaderCompile.h
  86. 3 19
      src/WallpaperEngine/Render/LedFrameGrabber.cpp
  87. 97 99
      src/WallpaperEngine/Render/ModelData.h
  88. 133 47
      src/WallpaperEngine/Render/Objects/CImage.cpp
  89. 19 14
      src/WallpaperEngine/Render/Objects/CImage.h
  90. 25 6
      src/WallpaperEngine/Render/Objects/CMesh.cpp
  91. 1 0
      src/WallpaperEngine/Render/Objects/CMesh.h
  92. 180 80
      src/WallpaperEngine/Render/Objects/CParticle.cpp
  93. 21 4
      src/WallpaperEngine/Render/Objects/CParticle.h
  94. 1 1
      src/WallpaperEngine/Render/Objects/CRenderable.h
  95. 14 0
      src/WallpaperEngine/Render/Objects/CSound.cpp
  96. 3 0
      src/WallpaperEngine/Render/Objects/CSound.h
  97. 14 4
      src/WallpaperEngine/Render/Objects/CText.cpp
  98. 1 0
      src/WallpaperEngine/Render/Objects/CText.h
  99. 11 26
      src/WallpaperEngine/Render/Objects/Effects/CPass.cpp
  100. 5 10
      src/WallpaperEngine/Render/Objects/Effects/CPass.h

+ 24 - 0
CMakeLists.txt

@@ -22,6 +22,23 @@ endif()
 
 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-narrowing")
 
+option(LWE_LTO "Link time optimization for the engine and its bundled libraries (long link, needs a lot of memory)" OFF)
+option(LWE_LINK_TRIM "Put functions and data in their own sections and let the linker drop what is unused" OFF)
+if(LWE_LTO)
+    include(CheckIPOSupported)
+    check_ipo_supported(RESULT lwe_ipo_ok OUTPUT lwe_ipo_log LANGUAGES C CXX)
+    if(NOT lwe_ipo_ok)
+        message(FATAL_ERROR "LWE_LTO is not supported by this toolchain: ${lwe_ipo_log}")
+    endif()
+    set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ON)
+endif()
+if(LWE_LINK_TRIM)
+    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ffunction-sections -fdata-sections")
+    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffunction-sections -fdata-sections")
+    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--gc-sections")
+    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--gc-sections")
+endif()
+
 set(LWE_SANITIZE "" CACHE STRING "Build with sanitizers: address, address;undefined or thread (tools/runtime_analysis.py)")
 if(LWE_SANITIZE)
     string(REPLACE ";" "," lwe_sanitize_list "${LWE_SANITIZE}")
@@ -444,6 +461,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Application/ApplicationContext.h
     src/WallpaperEngine/Application/WallpaperApplication.cpp
     src/WallpaperEngine/Application/WallpaperApplication.h
+    src/WallpaperEngine/Application/PlaylistSchedule.cpp
+    src/WallpaperEngine/Application/PlaylistSchedule.h
 
     src/WallpaperEngine/Assets/AssetLoadException.cpp
     src/WallpaperEngine/Assets/AssetLoadException.h
@@ -451,6 +470,7 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Assets/AssetLocator.h
 
     src/WallpaperEngine/FileSystem/Container.h
+    src/WallpaperEngine/FileSystem/StateDirectory.h
     src/WallpaperEngine/FileSystem/Container.cpp
     src/WallpaperEngine/FileSystem/Adapters/Types.h
     src/WallpaperEngine/FileSystem/Adapters/Directory.cpp
@@ -489,6 +509,7 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp
     src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.h
     src/WallpaperEngine/Audio/AudioContext.cpp
+    src/WallpaperEngine/Audio/AudioInput.h
     src/WallpaperEngine/Audio/AudioContext.h
     src/WallpaperEngine/Audio/AudioStream.cpp
     src/WallpaperEngine/Audio/AudioStream.h
@@ -855,11 +876,14 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/ScriptCallbackGuard.cpp
         src/WallpaperEngine/Testing/Cases/WeJsonTypes.cpp
         src/WallpaperEngine/Testing/Cases/ScriptLimits.cpp
+        src/WallpaperEngine/Testing/Cases/ShaderCompat.cpp
+        src/WallpaperEngine/Testing/Cases/ShaderCache.cpp
         src/WallpaperEngine/Testing/Cases/ShaderUniforms.cpp
         src/WallpaperEngine/Testing/Cases/ScriptWatchdog.cpp
         src/WallpaperEngine/Testing/Cases/WebFrameSlots.cpp
         src/WallpaperEngine/Testing/Cases/AlbumArtworkUpload.cpp
         src/WallpaperEngine/Testing/Cases/SplitLayout.cpp
+        src/WallpaperEngine/Testing/Cases/PlaylistSchedule.cpp
         src/WallpaperEngine/Testing/Cases/AutomuteDetector.cpp
         src/WallpaperEngine/Testing/Cases/IconTheme.cpp
         src/WallpaperEngine/Testing/Cases/ApplicationArguments.cpp

+ 8 - 2
README.md

@@ -53,7 +53,7 @@ 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.
+- 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. Besides `timer`, playlists in `daytime` mode (each item has an end time of day), `dayofweek` mode (items share the days of the week, starting with the locale's first day) and `logon` mode (the next item once per login session) are followed, and a playlist setting `transition` to `random` picks one of the transitions below for each switch.
 - 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 156 with its property, audio and file API.
 
@@ -212,6 +212,8 @@ The KDE Plasma integration (plasma-shell desktop surfaces, cursor tracking throu
 cmake -DCMAKE_BUILD_TYPE='Release' -DDISABLE_KDE_FEATURES=ON ..
 ```
 
+Two optional switches shrink the binaries: `-DLWE_LINK_TRIM=ON` (per-function sections and `--gc-sections`) and `-DLWE_LTO=ON` (link time optimization, needs a lot of memory while linking). Together they cut the engine library and the web helper by about 13-15 %. They did not change load time or frame cost in a comparison on four scenes (within 1-2 %), so they are off by default; `-march` is left to the packagers' `CXXFLAGS`.
+
 On KDE Plasma the engine loads KWin scripts of its own for the cursor position and for the windows that pause it (maximized, fullscreen, and focused with `--pause-on-focus`), per screen like Wallpaper Engine; nothing needs installing.
 
 On a Wayland compositor that offers no layer shell and isn't GNOME (Gala on elementary OS) the engine falls back to XWayland: it draws into a desktop type background window of its own, like `--screen-root` does on an X11 desktop. Wallpapers, scripts and the pointer work as usual, X11 windows pause it, and on Gala native Wayland windows too, through its `org.pantheon.gala.DesktopIntegration` D-Bus interface (it gives sizes but no fullscreen or maximized flag, so a window at least as large as a screen counts as fullscreen and maximized ones don't pause). The wallpaper window takes the clicks that would reach the desktop.
@@ -220,7 +222,7 @@ On sway, Hyprland, niri, labwc and other compositors with the wlr foreign toplev
 
 ## Assets
 
-You need Wallpaper Engine installed through Steam - this is where the backgrounds and shared assets come from. The binary looks for it automatically under:
+You need Wallpaper Engine installed through Steam - this is where the backgrounds and shared assets come from. Use the normal version: neither the beta branch nor the Windows 7 support version (Steam -> Wallpaper Engine -> Properties -> Betas, it has to say "None") works, they ship older assets that lack files newer wallpapers need (for example the MSDF font materials, so texts with outline or shadow break). The binary looks for it automatically under:
 
 ```
 ~/.steam/steam/steamapps/common
@@ -326,6 +328,10 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--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 |
 | `--ambient-volume <val>` | Separate volume for non-video backgrounds; video keeps using `--volume` |
+| `--audio-input <source>` | Capture source the audio visualizers listen to instead of the default output. Control file: `audio-input=` |
+| `--audio-input-volume <0-100>` | How much the audio input is amplified, 50 leaves it as it is. Control file: `audio-input-volume=` |
+| `--audio-input-threshold <n>` | Audio below this level counts as silence, 0 turns it off. Control file: `audio-input-threshold=` |
+| `--list-audio-inputs` | List the sources `--audio-input` takes and exit |
 | `--hrtf <auto\|on\|off>` | Headphones (HRTF) rendering of scene sounds like Wallpaper Engine: `auto` uses it while the default output is headphones or a headset |
 | `--sound-volume <id/name>=<val>` | Per-object volume (0-1), repeatable, `*` for unmatched objects |
 | `--audio-sensitivity <id/name>=<mult>` | Scale an object's audio-reactive swing; `0` disables it, `1` is default; repeatable, `*` for unmatched objects |

+ 248 - 35
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -1,7 +1,9 @@
 #include "ApplicationContext.h"
 
+#include "PlaylistSchedule.h"
 #include "Steam/FileSystem/FileSystem.h"
 #include "WallpaperEngine/Data/JSON.h"
+#include "WallpaperEngine/Data/Utils/DecimalNumber.h"
 #include "WallpaperEngine/Data/Utils/FiniteFloat.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/CFBO.h"
@@ -10,11 +12,13 @@
 
 #include <algorithm>
 #include <charconv>
+#include <cmath>
 #include <cstdlib>
 #include <cstring>
 #include <fstream>
 #include <functional>
 #include <iostream>
+#include <limits>
 #include <optional>
 #include <ranges>
 #include <sstream>
@@ -49,14 +53,14 @@ bool isHelperProcess (int argc, char** argv, bool webHost) {
 }
 using WallpaperEngine::Data::JSON::JSON;
 
-std::filesystem::path ApplicationContext::resolvePlaylistItemPath (const std::string& raw) const {
+std::filesystem::path ApplicationContext::resolvePlaylistItemPath (const std::string& raw) {
     if (raw.empty ()) {
 	return {};
     }
 
     std::string cleaned = raw;
 
-    constexpr std::string_view windowsPrefix = "\\\\?\\";
+    constexpr std::string_view windowsPrefix = R"(\\?\)";
 
     if (cleaned.starts_with (windowsPrefix)) {
 	cleaned = cleaned.substr (windowsPrefix.length ());
@@ -81,7 +85,7 @@ std::filesystem::path ApplicationContext::resolvePlaylistItemPath (const std::st
     return path;
 }
 
-std::filesystem::path ApplicationContext::configFilePath () const {
+std::filesystem::path ApplicationContext::configFilePath () {
     try {
 	return Steam::FileSystem::appDirectory (APP_DIRECTORY, "") / "config.json";
     } catch (std::runtime_error&) {
@@ -90,7 +94,7 @@ std::filesystem::path ApplicationContext::configFilePath () const {
     }
 }
 
-std::optional<JSON> ApplicationContext::parseConfigJson (const std::filesystem::path& path) const {
+std::optional<JSON> ApplicationContext::parseConfigJson (const std::filesystem::path& path) {
     if (path.empty ()) {
 	return std::nullopt;
     }
@@ -114,9 +118,8 @@ std::optional<ApplicationContext::PlaylistDefinition>
 ApplicationContext::buildPlaylistDefinition (const JSON& playlistJson, const std::string& fallbackName) const {
     PlaylistDefinition definition;
     definition.name = playlistJson.optional<std::string> ("name", fallbackName);
-    definition.settings = this->parsePlaylistSettings (playlistJson);
-    definition.items
-	= this->collectPlaylistItems (playlistJson, definition.name.empty () ? fallbackName : definition.name);
+    definition.settings = ApplicationContext::parsePlaylistSettings (playlistJson);
+    this->collectPlaylistItems (playlistJson, definition.name.empty () ? fallbackName : definition.name, definition);
 
     if (definition.items.empty ()) {
 	return std::nullopt;
@@ -134,7 +137,7 @@ ApplicationContext::buildPlaylistDefinition (const JSON& playlistJson, const std
     return definition;
 }
 
-ApplicationContext::PlaylistSettings ApplicationContext::parsePlaylistSettings (const JSON& playlistJson) const {
+ApplicationContext::PlaylistSettings ApplicationContext::parsePlaylistSettings (const JSON& playlistJson) {
     PlaylistSettings result;
     const auto settingsJson = playlistJson.optional ("settings");
     result.delayMinutes = settingsJson ? settingsJson->optional<uint32_t> ("delay", 60) : 60;
@@ -147,49 +150,148 @@ ApplicationContext::PlaylistSettings ApplicationContext::parsePlaylistSettings (
 	result.beginFirst = settingsJson->optional<bool> ("beginfirst", false);
 	result.playIntro = result.beginFirst && settingsJson->optional<bool> ("playintro", false);
     }
+
+    // WE's transition ids and its pool of them (sub_140075790) are its own shaders, "random" picks one of ours
+    if (settingsJson && settingsJson->optional<std::string> ("transition", "") == "random") {
+	result.randomTransition = true;
+	result.transitionMs = std::clamp (
+	    settingsJson->optional<int> ("transitiontime", 500), Render::TRANSITION_MIN_MS, Render::TRANSITION_MAX_MS
+	);
+    }
     return result;
 }
 
-std::vector<std::filesystem::path>
-ApplicationContext::collectPlaylistItems (const JSON& playlistJson, const std::string& name) const {
-    std::vector<std::filesystem::path> items;
+std::vector<float> ApplicationContext::PlaylistDefinition::scheduleEnds () const {
+    std::vector<float> requested;
+
+    requested.reserve (this->slots.size ());
+
+    for (const auto& slot : this->slots) {
+	requested.push_back (slot.end);
+    }
+
+    const auto all = this->settings.isDayOfWeek () ? dayOfWeekEnds (this->slots.size ()) : daytimeEnds (requested);
+    std::vector<float> ends;
+
+    ends.reserve (this->items.size ());
+
+    for (std::size_t slot = 0; slot < this->slots.size (); slot++) {
+	if (this->slots[slot].usable) {
+	    ends.push_back (all[slot]);
+	}
+    }
+
+    return ends;
+}
+
+std::size_t ApplicationContext::PlaylistDefinition::initialIndex () const {
+    if (this->settings.isLogon () && this->items.size () > 1) {
+	return logonIndex (logonStateFile (), this->name, this->items.size (), currentSessionToken (), false);
+    }
+
+    if (!this->settings.isScheduled () || this->items.size () < 2) {
+	return 0;
+    }
+
+    return std::min (scheduledIndexNow (this->scheduleEnds (), this->settings.isDayOfWeek ()), this->items.size () - 1);
+}
+
+void ApplicationContext::PlaylistDefinition::commitStart () const {
+    if (this->settings.isLogon () && this->items.size () > 1) {
+	[[maybe_unused]] const auto index
+	    = logonIndex (logonStateFile (), this->name, this->items.size (), currentSessionToken ());
+    }
+}
+
+void ApplicationContext::collectPlaylistItems (
+    const JSON& playlistJson, const std::string& name, PlaylistDefinition& definition
+) const {
     const auto jsonItems = playlistJson.optional ("items");
 
     if (!jsonItems.has_value () || !jsonItems->is_array ()) {
 	sLog.error ("Skipping playlist ", name, ": missing items");
-	return items;
+	return;
     }
 
     for (const auto& rawItem : *jsonItems) {
-	if (!rawItem.is_string ()) {
+	// an item is a path or, in daytime playlists, {"file", "daytimeend", "preset"} (sub_140075A90)
+	const auto file = rawItem.is_object () ? rawItem.find ("file") : rawItem.end ();
+	const bool entry = rawItem.is_string () || (file != rawItem.end () && file->is_string ());
+
+	if (!entry) {
 	    continue;
 	}
 
-	auto resolvedPath = this->resolvePlaylistItemPath (rawItem.get<std::string> ());
+	auto resolvedPath = ApplicationContext::resolvePlaylistItemPath (
+	    rawItem.is_string () ? rawItem.get<std::string> () : file->get<std::string> ()
+	);
+
+	const auto end = rawItem.is_object () ? rawItem.find ("daytimeend") : rawItem.end ();
+	const float requestedEnd = end != rawItem.end () && end->is_number () ? end->get<float> () : 0.0f;
 
 	if (resolvedPath.empty ()) {
+	    definition.slots.push_back ({ requestedEnd, false });
 	    continue;
 	}
 
 	if (!std::filesystem::exists (resolvedPath)) {
 	    sLog.error ("Skipping playlist item not found: ", resolvedPath.string ());
+	    definition.slots.push_back ({ requestedEnd, false });
 	    continue;
 	}
 
-	items.push_back (resolvedPath);
+	const auto preset = rawItem.is_object () ? rawItem.find ("preset") : rawItem.end ();
+
+	PlaylistDefinition::ItemPreset details;
+
+	if (preset != rawItem.end () && preset->is_string ()) {
+	    details.file = file != rawItem.end () ? file->get<std::string> () : "";
+	    details.name = preset->get<std::string> ();
+	}
+
+	definition.slots.push_back ({ requestedEnd, true });
+	definition.addItem (std::move (resolvedPath), std::move (details));
     }
 
-    if (items.empty ()) {
+    if (definition.items.empty ()) {
 	sLog.error ("Skipping playlist ", name, ": no usable items found");
     }
-
-    return items;
 }
 
 void ApplicationContext::registerPlaylist (PlaylistDefinition&& definition) {
     this->m_configPlaylists.insert_or_assign (definition.name, std::move (definition));
 }
 
+namespace {
+const JSON* findSavedPreset (const std::optional<JSON>& wpresets, const std::string& file, const std::string& name) {
+    if (!wpresets.has_value () || !wpresets->is_object ()) {
+	return nullptr;
+    }
+
+    const auto forFile = wpresets->find (file);
+
+    if (forFile == wpresets->end () || !forFile->is_object ()) {
+	return nullptr;
+    }
+
+    const auto list = forFile->find ("presets");
+
+    if (list == forFile->end () || !list->is_array ()) {
+	return nullptr;
+    }
+
+    for (const auto& saved : *list) {
+	const auto savedName = saved.is_object () ? saved.find ("name") : saved.end ();
+
+	if (savedName != saved.end () && savedName->is_string () && savedName->get<std::string> () == name) {
+	    return &saved;
+	}
+    }
+
+    return nullptr;
+}
+}
+
 void ApplicationContext::loadPlaylistsFromConfig () {
     if (this->m_loadedConfigPlaylists) {
 	return;
@@ -197,8 +299,8 @@ void ApplicationContext::loadPlaylistsFromConfig () {
 
     this->m_loadedConfigPlaylists = true;
 
-    const auto configPath = this->configFilePath ();
-    const auto root = this->parseConfigJson (configPath);
+    const auto configPath = ApplicationContext::configFilePath ();
+    const auto root = ApplicationContext::parseConfigJson (configPath);
     if (!root.has_value ()) {
 	return;
     }
@@ -209,15 +311,36 @@ void ApplicationContext::loadPlaylistsFromConfig () {
 	sLog.exception ("Cannot find steamuser section in config.json");
     }
 
-    auto addPlaylist = [this] (const JSON& playlistJson, const std::string& fallbackName) {
+    // general.wpresets.<file>.presets is a list of {"name": ..., <property>: <value>} (sub_140063F00)
+    const auto general = steamUser->optional ("general");
+    const auto savedPresets = general ? general->optional ("wpresets") : std::nullopt;
+
+    auto addPlaylist = [this, &savedPresets] (const JSON& playlistJson, const std::string& fallbackName) {
 	auto definition = this->buildPlaylistDefinition (playlistJson, fallbackName);
 	if (!definition) {
 	    return;
 	}
+
+	for (auto& preset : definition->presets) {
+	    if (preset.name.empty ()) {
+		continue;
+	    }
+
+	    if (const auto* saved = findSavedPreset (savedPresets, preset.file, preset.name)) {
+		preset.values = *saved;
+	    }
+
+	    if (!preset.values.has_value ()) {
+		sLog.error (
+		    "Playlist ", definition->name, ": preset '", preset.name, "' of ", preset.file, " not found"
+		);
+	    }
+	}
+
 	this->registerPlaylist (std::move (*definition));
     };
 
-    if (const auto general = steamUser->optional ("general")) {
+    if (general) {
 	if (const auto playlists = general->optional ("playlists")) {
 	    for (const auto& playlist : *playlists) {
 		try {
@@ -316,7 +439,7 @@ std::vector<std::string> ApplicationContext::describeRequestedScreens () const {
     std::vector<std::string> lines;
 
     for (const auto& screen : this->settings.general.screenBackgrounds | std::views::keys) {
-	if (screen.find ('#') == std::string::npos) {
+	if (screen.find ('#') == std::string::npos && !screen.starts_with ("span:")) {
 	    lines.push_back (screen);
 	}
     }
@@ -383,6 +506,42 @@ std::optional<float> ApplicationContext::resolveAudioSensitivity (int id, const
     return wildcard;
 }
 
+namespace {
+// both audio input options read a plain decimal number: an optional sign, no blanks, no hex, "inf" or "nan"; one too
+// big (or too small) for the type is still a number and clamps like any other
+std::optional<double> parseDecimal (const std::string& value) {
+    const char* position = value.c_str ();
+    double number = 0.0;
+
+    if (!WallpaperEngine::Data::Utils::readDecimalNumber (position, number) || *position != '\0') {
+	return std::nullopt;
+    }
+
+    return number;
+}
+}
+
+std::optional<int> ApplicationContext::parseAudioInputVolume (const std::string& value) {
+    const auto number = parseDecimal (value);
+
+    // a whole number only
+    if (!number.has_value () || value.find_first_of (".eE") != std::string::npos) {
+	return std::nullopt;
+    }
+
+    return static_cast<int> (std::clamp (*number, 0.0, 100.0));
+}
+
+std::optional<float> ApplicationContext::parseAudioInputThreshold (const std::string& value) {
+    const auto number = parseDecimal (value);
+
+    if (!number.has_value ()) {
+	return std::nullopt;
+    }
+
+    return static_cast<float> (std::clamp (*number, 0.0, static_cast<double> (std::numeric_limits<float>::max ())));
+}
+
 std::optional<ApplicationContext::HRTF_MODE> ApplicationContext::parseHrtfMode (const std::string& value) {
     if (value == "auto") {
 	return HRTF_AUTO;
@@ -509,10 +668,10 @@ void ApplicationContext::loadSettingsFromArgv () {
 		sLog.exception ("Window geometry must be in the format: XxYxWxH");
 	    }
 
-	    this->settings.render.window.geometry.x = strtol (str, nullptr, 10);
-	    this->settings.render.window.geometry.y = strtol (delim1 + 1, nullptr, 10);
-	    this->settings.render.window.geometry.z = strtol (delim2 + 1, nullptr, 10);
-	    this->settings.render.window.geometry.w = strtol (delim3 + 1, nullptr, 10);
+	    this->settings.render.window.geometry.x = static_cast<int> (strtol (str, nullptr, 10));
+	    this->settings.render.window.geometry.y = static_cast<int> (strtol (delim1 + 1, nullptr, 10));
+	    this->settings.render.window.geometry.z = static_cast<int> (strtol (delim2 + 1, nullptr, 10));
+	    this->settings.render.window.geometry.w = static_cast<int> (strtol (delim3 + 1, nullptr, 10));
 	})
 	.append ();
     backgroundMode.add_argument ("-r", "--screen-root")
@@ -584,8 +743,8 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    group.scaling = this->settings.render.window.scalingMode;
 	    group.clamp = this->settings.render.window.clamp;
 	    group.alignment = this->settings.render.window.alignment;
+	    lastScreen = "span:" + group.screens.front ();
 	    this->settings.general.spanGroups.push_back (std::move (group));
-	    lastScreen = "span:" + value;
 	    this->settings.general.screenBackgrounds[lastScreen] = "";
 	})
 	.append ();
@@ -671,21 +830,28 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    "screen, otherwise it is used in window mode."
 	)
 	.action ([this, &lastScreen] (const std::string& value) -> void {
-	    const auto& playlist = this->getPlaylistFromConfig (value);
+	    auto playlist = this->getPlaylistFromConfig (value);
+	    const auto first = playlist.items.empty () ? 0 : playlist.initialIndex ();
+
+	    playlist.startIndex = first;
 
 	    if (lastScreen.empty ()) {
 		this->settings.general.defaultPlaylist = playlist;
 		if (this->settings.general.defaultBackground.empty () && !playlist.items.empty ()) {
-		    this->settings.general.defaultBackground = playlist.items.front ();
+		    this->settings.general.defaultBackground = playlist.items[first];
 		}
 	    } else {
 		this->settings.general.screenPlaylists[lastScreen] = playlist;
 		if (!playlist.items.empty ()) {
-		    this->settings.general.screenBackgrounds[lastScreen] = playlist.items.front ();
+		    this->settings.general.screenBackgrounds[lastScreen] = playlist.items[first];
+
+		    if (lastScreen.starts_with ("span:") && !this->settings.general.spanGroups.empty ()) {
+			this->settings.general.spanGroups.back ().background = playlist.items[first];
+		    }
 		}
 
 		if (this->settings.general.defaultBackground.empty () && !playlist.items.empty ()) {
-		    this->settings.general.defaultBackground = playlist.items.front ();
+		    this->settings.general.defaultBackground = playlist.items[first];
 		}
 	    }
 	})
@@ -1068,12 +1234,10 @@ void ApplicationContext::loadSettingsFromArgv () {
 	.action ([this] (const std::string& value) -> void {
 	    this->settings.render.wayland.layerAuto = value == "auto";
 
-	    if (value == "auto") {
+	    if (value == "auto" || value == "bottom") {
 		this->settings.render.wayland.layer = WAYLAND_LAYER_BOTTOM;
 	    } else if (value == "background") {
 		this->settings.render.wayland.layer = WAYLAND_LAYER_BACKGROUND;
-	    } else if (value == "bottom") {
-		this->settings.render.wayland.layer = WAYLAND_LAYER_BOTTOM;
 	    } else if (value == "top") {
 		this->settings.render.wayland.layer = WAYLAND_LAYER_TOP;
 	    } else if (value == "overlay") {
@@ -1229,6 +1393,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    }
 
 	    this->settings.render.transition = value;
+	    this->settings.render.transitionChosen = true;
 	});
 
     performanceGroup.add_argument ("--transition-duration")
@@ -1248,6 +1413,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.render.transitionMs = std::clamp (
 		ms, WallpaperEngine::Render::TRANSITION_MIN_MS, WallpaperEngine::Render::TRANSITION_MAX_MS
 	    );
+	    this->settings.render.transitionMsChosen = true;
 	});
 
     performanceGroup.add_argument ("--no-fullscreen-pause")
@@ -1373,6 +1539,49 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.audio.hrtf = *mode;
 	});
 
+    audioGroup.add_argument ("--audio-input")
+	.help (
+	    "What the audio visualizers listen to, like Wallpaper Engine's audio input device: a source (microphone, "
+	    "line in, a monitor) by its name or description, or a sink by its name for its monitor, see "
+	    "--list-audio-inputs. Default: the default output. Control file: audio-input=<source>"
+	)
+	.action ([this] (const std::string& value) -> void { this->settings.audio.input.device = value; });
+
+    audioGroup.add_argument ("--audio-input-volume")
+	.help (
+	    "How much the audio input is amplified for the visualizers, 0 to 100, 50 leaves it as it is (Wallpaper "
+	    "Engine's audioinputvolume). Control file: audio-input-volume=<n>"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    const auto volume = parseAudioInputVolume (value);
+
+	    if (!volume.has_value ()) {
+		sLog.exception ("Invalid --audio-input-volume value: ", value);
+	    }
+
+	    this->settings.audio.input.volume = *volume;
+	});
+
+    audioGroup.add_argument ("--audio-input-threshold")
+	.help (
+	    "Audio below this level counts as silence for the visualizers, 0 turns it off (Wallpaper Engine's "
+	    "audioinputthreshold, the sample level is the value times 0.001). Control file: audio-input-threshold=<n>"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    const auto threshold = parseAudioInputThreshold (value);
+
+	    if (!threshold.has_value ()) {
+		sLog.exception ("Invalid --audio-input-threshold value: ", value);
+	    }
+
+	    this->settings.audio.input.threshold = *threshold;
+	});
+
+    audioGroup.add_argument ("--list-audio-inputs")
+	.help ("List the sources --audio-input takes and exit")
+	.flag ()
+	.store_into (this->settings.general.onlyListAudioInputs);
+
     auto& ledGroup = program.add_group ("LED options");
 
     ledGroup.add_argument ("--leds")
@@ -1865,6 +2074,10 @@ void ApplicationContext::loadSettingsFromArgv () {
     try {
 	program.parse_known_args (this->m_argc, this->m_argv);
 
+	if (this->settings.general.onlyListAudioInputs) {
+	    return;
+	}
+
 	if (this->settings.general.defaultBackground.empty ()) {
 	    throw std::runtime_error ("At least one background ID must be specified");
 	}

+ 98 - 36
src/WallpaperEngine/Application/ApplicationContext.h

@@ -11,6 +11,7 @@
 #include <glm/vec4.hpp>
 
 #include "ApplicationState.h"
+#include "WallpaperEngine/Audio/AudioInput.h"
 #include "WallpaperEngine/Data/JSON.h"
 
 #include "../Render/TextureProvider.h"
@@ -55,6 +56,10 @@ public:
     };
 
     [[nodiscard]] static std::optional<HRTF_MODE> parseHrtfMode (const std::string& value);
+    /** 0 to 100 (clamped), nullopt for anything that is not a whole number */
+    [[nodiscard]] static std::optional<int> parseAudioInputVolume (const std::string& value);
+    /** 0 or more, nullopt for anything that is not a finite number */
+    [[nodiscard]] static std::optional<float> parseAudioInputThreshold (const std::string& value);
 
     struct PlaylistSettings {
 	uint32_t delayMinutes = 60;
@@ -64,14 +69,60 @@ public:
 	bool videoSequence = false;
 	bool beginFirst = false;
 	bool playIntro = false;
+	bool randomTransition = false;
+	int transitionMs = 0;
 
 	[[nodiscard]] bool hasIntro () const { return this->mode == "timer" && this->beginFirst && this->playIntro; }
+	[[nodiscard]] bool isDaytime () const { return this->mode == "daytime"; }
+	[[nodiscard]] bool isDayOfWeek () const { return this->mode == "dayofweek"; }
+	[[nodiscard]] bool isLogon () const { return this->mode == "logon"; }
+	[[nodiscard]] bool isScheduled () const { return this->isDaytime () || this->isDayOfWeek (); }
     };
 
     struct PlaylistDefinition {
 	std::string name;
 	std::vector<std::filesystem::path> items;
+	/**
+	 * per item, in step with items: the "preset" it names with what config.json stores under that name
+	 */
+	struct ItemPreset {
+	    std::string file;
+	    std::string name;
+	    std::optional<WallpaperEngine::Data::JSON::JSON> values;
+	};
+	std::vector<ItemPreset> presets;
+	/**
+	 * one per item the playlist lists, usable or not: the schedule is laid out over all of them so an item that is
+	 * not installed leaves its time to the next one instead of moving everything after it
+	 */
+	struct ScheduleSlot {
+	    float end = 0.0f;
+	    bool usable = false;
+	};
+	std::vector<ScheduleSlot> slots;
 	PlaylistSettings settings;
+
+	/** the only way an item gets in, so items and presets stay the same length */
+	void addItem (std::filesystem::path path, ItemPreset preset) {
+	    this->items.push_back (std::move (path));
+	    this->presets.push_back (std::move (preset));
+	}
+
+	[[nodiscard]] std::vector<float> scheduleEnds () const;
+	[[nodiscard]] const WallpaperEngine::Data::JSON::JSON* presetValues (std::size_t index) const {
+	    return index < this->presets.size () && this->presets[index].values.has_value ()
+		? &*this->presets[index].values
+		: nullptr;
+	}
+	/** the item chosen when the playlist was selected, so every reader agrees on what was started with */
+	std::optional<std::size_t> startIndex;
+
+	[[nodiscard]] std::size_t initialIndex () const;
+	/** records the item a "logon" playlist started with, repeating it within a session is harmless */
+	void commitStart () const;
+	[[nodiscard]] std::size_t startItem () const {
+	    return this->startIndex.has_value () ? *this->startIndex : this->initialIndex ();
+	}
     };
 
     struct SpanGroup {
@@ -108,6 +159,7 @@ public:
 	    bool onlyListProperties = false;
 	    bool onlyListObjects = false;
 	    bool onlyListAudioObjects = false;
+	    bool onlyListAudioInputs = false;
 	    bool onlyListEffects = false;
 	    bool onlyListFonts = false;
 	    bool dumpStructure = false;
@@ -155,54 +207,58 @@ public:
 	} general;
 
 	struct {
-	    WINDOW_MODE mode;
-	    int maximumFPS;
-	    float playbackSpeed;
+	    WINDOW_MODE mode = {};
+	    int maximumFPS = 0;
+	    float playbackSpeed = 0.0f;
 	    WallpaperEngine::VideoPlayback::VideoSegments videoSegments;
 	    std::string hwdec;
 	    std::string webFrames;
 	    std::string frameLimiter;
 	    std::string transition;
-	    int transitionMs;
-	    bool freezeAnimations;
-	    bool pauseOnFullscreen;
+	    int transitionMs = 0;
+	    /** --transition / --transition-duration or their control file keys were given, a playlist's "random" yields
+	     */
+	    bool transitionChosen = false;
+	    bool transitionMsChosen = false;
+	    bool freezeAnimations = false;
+	    bool pauseOnFullscreen = false;
 	    // only fullscreen toplevels that are also activated count (scrollable tiling compositors)
-	    bool pauseOnFullscreenOnlyWhenActive;
-	    bool pauseOnFocus;
+	    bool pauseOnFullscreenOnlyWhenActive = false;
+	    bool pauseOnFocus = false;
 	    /** wlroots: maximized toplevels pause their outputs too (KDE and GNOME always do, like WE) */
-	    bool pauseOnMaximized;
+	    bool pauseOnMaximized = false;
 	    std::vector<std::string> fullscreenPauseIgnoreAppIds;
 	    std::optional<int> batteryFPS;
-	    int idlePauseMinutes;
-	    bool pauseOnLock;
-	    bool hdr;
+	    int idlePauseMinutes = 0;
+	    bool pauseOnLock = false;
+	    bool hdr = false;
 	    struct {
-		bool baseOnly;
-		bool noSolidFinal;
-		bool passLog;
-		bool brightnessLog;
-		bool noPuppetAnimation;
+		bool baseOnly = false;
+		bool noSolidFinal = false;
+		bool passLog = false;
+		bool brightnessLog = false;
+		bool noPuppetAnimation = false;
 		std::optional<int> objectFilter;
 		std::vector<int> skipObjects;
 		std::vector<int> skipEffects;
 	    } debug;
 
 	    struct {
-		glm::ivec4 geometry;
-		TextureFlags clamp;
-		WallpaperEngine::Render::WallpaperState::TextureUVsScaling scalingMode;
-		float zoom;
-		glm::vec2 offset;
-		WallpaperEngine::Render::WallpaperState::Alignment alignment;
-		glm::vec4 cornerColor;
-		WallpaperEngine::Data::Model::ImageAdjustments imageAdjustments;
-		bool asBackground;
-		bool regular;
+		glm::ivec4 geometry = {};
+		TextureFlags clamp = {};
+		WallpaperEngine::Render::WallpaperState::TextureUVsScaling scalingMode = {};
+		float zoom = 0.0f;
+		glm::vec2 offset = {};
+		WallpaperEngine::Render::WallpaperState::Alignment alignment = {};
+		glm::vec4 cornerColor = {};
+		WallpaperEngine::Data::Model::ImageAdjustments imageAdjustments = {};
+		bool asBackground = false;
+		bool regular = false;
 	    } window;
 
 	    struct {
-		WAYLAND_LAYER layer;
-		bool layerAuto;
+		WAYLAND_LAYER layer = {};
+		bool layerAuto = false;
 	    } wayland;
 	} render;
 
@@ -215,6 +271,8 @@ public:
 	    std::optional<std::string> audioScreen;
 	    std::optional<int> ambientVolume;
 	    HRTF_MODE hrtf;
+	    /** WE's audioinputdevice, audioinputvolume and audioinputthreshold */
+	    WallpaperEngine::Audio::AudioInput input;
 	} audio;
 
 	struct {
@@ -245,6 +303,7 @@ public:
             .onlyListProperties = false,
             .onlyListObjects = false,
             .onlyListAudioObjects = false,
+            .onlyListAudioInputs = false,
             .onlyListEffects = false,
             .onlyListFonts = false,
             .dumpStructure = false,
@@ -335,6 +394,7 @@ public:
             .audioScreen = std::nullopt,
             .ambientVolume = std::nullopt,
             .hrtf = HRTF_AUTO,
+            .input = {},
         },
         .leds = {
             .enabled = false,
@@ -371,13 +431,15 @@ private:
     static std::filesystem::path translateBackground (const std::string& bgIdOrPath);
 
     void loadPlaylistsFromConfig ();
-    std::filesystem::path resolvePlaylistItemPath (const std::string& raw) const;
-    std::filesystem::path configFilePath () const;
-    std::optional<WallpaperEngine::Data::JSON::JSON> parseConfigJson (const std::filesystem::path& path) const;
-    PlaylistSettings parsePlaylistSettings (const WallpaperEngine::Data::JSON::JSON& playlistJson) const;
-    std::vector<std::filesystem::path>
-    collectPlaylistItems (const WallpaperEngine::Data::JSON::JSON& playlistJson, const std::string& name) const;
-    std::optional<PlaylistDefinition> buildPlaylistDefinition (
+    [[nodiscard]] static std::filesystem::path resolvePlaylistItemPath (const std::string& raw);
+    [[nodiscard]] static std::filesystem::path configFilePath ();
+    [[nodiscard]] static std::optional<WallpaperEngine::Data::JSON::JSON>
+    parseConfigJson (const std::filesystem::path& path);
+    [[nodiscard]] static PlaylistSettings parsePlaylistSettings (const WallpaperEngine::Data::JSON::JSON& playlistJson);
+    void collectPlaylistItems (
+	const WallpaperEngine::Data::JSON::JSON& playlistJson, const std::string& name, PlaylistDefinition& definition
+    ) const;
+    [[nodiscard]] std::optional<PlaylistDefinition> buildPlaylistDefinition (
 	const WallpaperEngine::Data::JSON::JSON& playlistJson, const std::string& fallbackName
     ) const;
     void registerPlaylist (PlaylistDefinition&& definition);

+ 439 - 0
src/WallpaperEngine/Application/PlaylistSchedule.cpp

@@ -0,0 +1,439 @@
+#include "PlaylistSchedule.h"
+
+#include <algorithm>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <ctime>
+#include <fstream>
+#include <mutex>
+#include <nlohmann/json.hpp>
+#include <random>
+#include <sstream>
+
+#include "WallpaperEngine/FileSystem/StateDirectory.h"
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <clocale>
+#include <fcntl.h>
+#include <langinfo.h>
+#include <sys/file.h>
+#include <sys/stat.h>
+
+#ifndef STATX_MNT_ID_UNIQUE
+#define STATX_MNT_ID_UNIQUE 0x00004000U
+#endif
+#include <unistd.h>
+
+namespace WallpaperEngine::Application {
+std::vector<float> daytimeEnds (const std::vector<float>& requested) {
+    std::vector<float> ends = requested;
+
+    if (ends.empty ()) {
+	return ends;
+    }
+
+    std::size_t runStart = 0;
+    float previous = 0.0f;
+
+    for (std::size_t index = 0; index < ends.size (); index++) {
+	float end = 1.0f;
+
+	if (index + 1 != ends.size ()) {
+	    end = ends[index];
+
+	    if (end <= 0.0f) {
+		continue;
+	    }
+	}
+
+	const float step = (end - previous) / static_cast<float> (index - runStart + 1);
+
+	for (std::size_t item = runStart; item <= index; item++) {
+	    ends[item] = static_cast<float> (item - runStart + 1) * step + previous;
+	}
+
+	ends[index] = end;
+
+	runStart = index + 1;
+	previous = end;
+    }
+
+    if (!std::is_sorted (ends.begin (), ends.end ())) {
+	sLog.error ("Daytime playlist item ends do not rise through the day, some items will never be shown");
+    }
+
+    return ends;
+}
+
+std::vector<float> dayOfWeekEnds (const std::size_t count) {
+    std::vector<float> ends (count);
+    const int slots = static_cast<int> (std::clamp<std::size_t> (count, 1, 7));
+    unsigned int total = 0;
+
+    for (std::size_t item = 0; item < count; item++) {
+	int remaining = 7;
+	int share = 7;
+
+	for (int slot = 0; slot < slots; slot++) {
+	    share = slot < slots - 1 ? remaining / (slots - slot) : remaining;
+
+	    if (slot == static_cast<int> (item)) {
+		break;
+	    }
+
+	    remaining -= share;
+	}
+
+	total += static_cast<unsigned int> (share);
+	ends[item] = static_cast<float> (total);
+    }
+
+    return ends;
+}
+
+std::size_t scheduledIndex (const std::vector<float>& ends, const float position) {
+    for (std::size_t index = 0; index < ends.size (); index++) {
+	if (ends[index] > position) {
+	    return index;
+	}
+    }
+
+    return ends.empty () ? 0 : ends.size () - 1;
+}
+
+float daytimePosition (const int hour, const int minute) { return static_cast<float> (minute + 60 * hour) / 1440.0f; }
+
+float dayOfWeekPosition (const int weekday, const int firstWeekday) {
+    return static_cast<float> (((weekday - firstWeekday) % 7 + 7) % 7);
+}
+
+int localeFirstWeekday () {
+// the two items are enum members of glibc, not macros
+#ifdef __GLIBC__
+    const locale_t locale = newlocale (LC_TIME_MASK, "", nullptr);
+
+    if (locale == nullptr) {
+	return 0;
+    }
+
+    const int first = static_cast<unsigned char> (nl_langinfo_l (_NL_TIME_FIRST_WEEKDAY, locale)[0]);
+    // a word item: glibc only defines the low 32 bits of the returned pointer
+    const auto origin
+	= static_cast<std::uint32_t> (reinterpret_cast<std::uintptr_t> (nl_langinfo_l (_NL_TIME_WEEK_1STDAY, locale)));
+
+    freelocale (locale);
+
+    // 19971130 was a Sunday and 19971201 a Monday, the week starts first_weekday - 1 days after that
+    const int firstOrigin = origin == 19971201 ? 1 : 0;
+
+    return first >= 1 && first <= 7 ? (firstOrigin + first - 1) % 7 : 0;
+#else
+    return 0;
+#endif
+}
+
+std::size_t scheduledIndexNow (const std::vector<float>& ends, const bool dayOfWeek) {
+    const std::time_t now = std::time (nullptr);
+    std::tm local {};
+
+    tzset ();
+    localtime_r (&now, &local);
+
+    static const int firstWeekday = localeFirstWeekday ();
+
+    return scheduledIndex (
+	ends,
+	dayOfWeek ? dayOfWeekPosition (local.tm_wday, firstWeekday) : daytimePosition (local.tm_hour, local.tm_min)
+    );
+}
+
+std::size_t logonIndex (
+    const std::filesystem::path& stateFile, const std::string& playlist, const std::size_t count,
+    const std::string& session, const bool commit
+) {
+    if (count == 0) {
+	return 0;
+    }
+
+    std::error_code ignored;
+
+    // a peek reads the renamed-into-place file and leaves the disk and the lock alone
+    if (commit) {
+	std::filesystem::create_directories (stateFile.parent_path (), ignored);
+    }
+
+    // two engines starting together must not both read the old index and overwrite each other's playlist
+    auto lockPath = stateFile;
+    lockPath += ".lock";
+    struct Lock {
+	int fd;
+
+	~Lock () {
+	    if (fd >= 0) {
+		close (fd);
+	    }
+	}
+    } lock { commit ? open (lockPath.c_str (), O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600) : -1 };
+
+    if (lock.fd >= 0) {
+	flock (lock.fd, LOCK_EX);
+    }
+
+    nlohmann::json state = nlohmann::json::object ();
+
+    try {
+	std::ifstream in (stateFile);
+
+	if (in.is_open ()) {
+	    state = nlohmann::json::parse (in, nullptr, false);
+	}
+    } catch (...) {
+	sLog.debug ("Cannot read playlist state ", stateFile.string ());
+    }
+
+    if (!state.is_object ()) {
+	state = nlohmann::json::object ();
+    }
+
+    const auto entry = state.find (playlist);
+    std::size_t index = 0;
+
+    if (entry != state.end () && entry->is_object ()) {
+	const auto saved = entry->find ("index");
+	const auto savedSession = entry->find ("session");
+
+	if (saved != entry->end () && saved->is_number_integer () && saved->get<long long> () >= 0) {
+	    index = static_cast<std::size_t> (saved->get<long long> ()) % count;
+
+	    if (savedSession != entry->end () && savedSession->is_string ()
+		&& savedSession->get<std::string> () == session) {
+		return index;
+	    }
+
+	    index = (index + 1) % count;
+	}
+    }
+
+    if (!commit) {
+	return index;
+    }
+
+    state[playlist] = { { "index", index }, { "session", session } };
+
+    // renamed over the target so a reader never sees half of it, a state file that cannot be written only costs the
+    // memory of the last item
+    auto partial = stateFile;
+    partial += ".partial" + std::to_string (getpid ());
+
+    try {
+	// a name another user could have guessed in a shared directory must not be followed or reused
+	std::filesystem::remove (partial, ignored);
+
+	const int fd = open (partial.c_str (), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
+
+	if (fd >= 0) {
+	    const std::string text = state.dump (1, ' ', false, nlohmann::json::error_handler_t::replace) + '\n';
+	    std::size_t written = 0;
+
+	    while (written < text.size ()) {
+		const auto step = write (fd, text.data () + written, text.size () - written);
+
+		if (step <= 0) {
+		    break;
+		}
+
+		written += static_cast<std::size_t> (step);
+	    }
+
+	    close (fd);
+
+	    if (written == text.size ()) {
+		std::filesystem::rename (partial, stateFile, ignored);
+	    }
+	}
+    } catch (...) {
+	sLog.debug ("Cannot write playlist state ", stateFile.string ());
+    }
+
+    std::filesystem::remove (partial, ignored);
+
+    return index;
+}
+
+std::string runtimeMountId (const std::string& dir) {
+    std::error_code error;
+    const auto resolved = std::filesystem::canonical (dir, error).string ();
+
+    if (error) {
+	return {};
+    }
+
+    std::ifstream info ("/proc/self/mountinfo");
+    std::string line;
+    std::string best;
+    std::size_t bestLength = 0;
+
+    while (std::getline (info, line)) {
+	std::istringstream fields (line);
+	std::string id, parent, device, root, escaped;
+
+	fields >> id >> parent >> device >> root >> escaped;
+
+	std::string point;
+
+	for (std::size_t at = 0; at < escaped.size (); at++) {
+	    if (escaped[at] == '\\' && at + 3 < escaped.size ()) {
+		point += static_cast<char> (std::strtol (escaped.substr (at + 1, 3).c_str (), nullptr, 8));
+		at += 3;
+	    } else {
+		point += escaped[at];
+	    }
+	}
+
+	const bool inside = point == "/" || resolved == point || resolved.starts_with (point + "/");
+
+	// later lines are mounted on top of earlier ones
+	if (inside && point.size () >= bestLength) {
+	    best = id;
+	    bestLength = point.size ();
+	}
+    }
+
+    return best;
+}
+
+std::string loginMarker (const std::filesystem::path& dir) {
+    const auto marker = dir / "lwe-login";
+    const auto read = [&marker] () {
+	std::string id;
+	std::ifstream in (marker);
+
+	std::getline (in, id);
+
+	return id;
+    };
+
+    if (auto id = read (); !id.empty ()) {
+	return id;
+    }
+
+    std::random_device entropy;
+    const std::uint64_t random[2] = {
+	(static_cast<std::uint64_t> (entropy ()) << 32) | entropy (),
+	(static_cast<std::uint64_t> (entropy ()) << 32) | entropy (),
+    };
+
+    char text[40];
+
+    snprintf (
+	text, sizeof (text), "%016llx%016llx\n", static_cast<unsigned long long> (random[0]),
+	static_cast<unsigned long long> (random[1])
+    );
+
+    // linked into place whole: two engines starting together settle on the first one's id and nobody reads half of it
+    auto partial = marker;
+    partial += "." + std::to_string (getpid ());
+    std::error_code ignored;
+    std::filesystem::remove (partial, ignored);
+
+    const int fd = open (partial.c_str (), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
+
+    if (fd >= 0) {
+	const auto length = std::strlen (text);
+	const bool written = write (fd, text, length) == static_cast<ssize_t> (length);
+
+	close (fd);
+
+	if (written) {
+	    const int linked = link (partial.c_str (), marker.c_str ());
+
+	    static_cast<void> (linked);
+	}
+    }
+
+    std::filesystem::remove (partial, ignored);
+
+    return read ();
+}
+
+std::string currentSessionToken () {
+    std::string token;
+    std::ifstream boot ("/proc/sys/kernel/random/boot_id");
+
+    std::getline (boot, token);
+
+    // inside a Flatpak /run/user/<uid> sits on the sandbox's own tmpfs, a new mount for every run, but the app's folder
+    // in it is the host's and lives until the last logout
+    if (const char* appId = std::getenv ("FLATPAK_ID"); appId != nullptr && access ("/.flatpak-info", F_OK) == 0) {
+	const char* shared = std::getenv ("XDG_RUNTIME_DIR");
+	const std::filesystem::path appDir
+	    = std::filesystem::path (
+		  shared != nullptr && shared[0] == '/' ? shared : "/run/user/" + std::to_string (getuid ())
+	      )
+	    / "app" / appId;
+	std::error_code error;
+
+	if (std::filesystem::is_directory (appDir, error)) {
+	    if (const auto id = loginMarker (appDir); !id.empty ()) {
+		return token + ":f" + id;
+	    }
+	}
+    }
+
+    // the runtime dir is a tmpfs of its own from the first login of a user to the last logout, whatever started the
+    // engine, unlike XDG_SESSION_ID which a terminal has and an autostart entry or a user service often lacks. Its
+    // inode is always 1, the mount is what tells two logins apart (unique ids are never reused while the system runs)
+    const char* runtime = std::getenv ("XDG_RUNTIME_DIR");
+    const std::string runtimeDir
+	= runtime != nullptr && runtime[0] == '/' ? std::string (runtime) : "/run/user/" + std::to_string (getuid ());
+
+    // glibc 2.35's struct statx has no stx_mnt_id: the kernel's layout has the mask first and the id at 0x90
+    alignas (8) unsigned char info[256] = {};
+    std::uint32_t mask = 0;
+    std::uint64_t mountId = 0;
+
+    if (statx (AT_FDCWD, runtimeDir.c_str (), 0, STATX_MNT_ID_UNIQUE, reinterpret_cast<struct statx*> (info)) == 0) {
+	std::memcpy (&mask, info, sizeof (mask));
+	std::memcpy (&mountId, info + 0x90, sizeof (mountId));
+    }
+
+    if ((mask & STATX_MNT_ID_UNIQUE) != 0) {
+	token += ":" + std::to_string (mountId);
+    } else if (const auto mount = runtimeMountId (runtimeDir); !mount.empty ()) {
+	// kernels before 6.8: the classic mount id is handed out cyclically, so it is not reused soon after a logout
+	token += ":m" + mount;
+    } else if (const char* session = std::getenv ("XDG_SESSION_ID"); session != nullptr) {
+	token += ":";
+	token += session;
+    }
+
+    return token;
+}
+
+std::filesystem::path logonStateFile () {
+    if (const auto root = FileSystem::stateRoot (); !root.empty ()) {
+	return root / "playlists.json";
+    }
+
+    static std::once_flag reported;
+
+    std::call_once (reported, [] {
+	sLog.error (
+	    "No state directory (XDG_STATE_HOME and HOME unset): the logon playlist position is kept in a temporary "
+	    "folder and starts over at every login"
+	);
+    });
+
+    if (const char* runtime = std::getenv ("XDG_RUNTIME_DIR"); runtime != nullptr && runtime[0] == '/') {
+	return std::filesystem::path (runtime) / "linux-wallpaperengine-playlists.json";
+    }
+
+    std::error_code error;
+    const auto temp = std::filesystem::temp_directory_path (error);
+
+    return (error ? std::filesystem::path ("/tmp") : temp)
+	/ ("linux-wallpaperengine-playlists-" + std::to_string (getuid ()) + ".json");
+}
+}

+ 65 - 0
src/WallpaperEngine/Application/PlaylistSchedule.h

@@ -0,0 +1,65 @@
+#pragma once
+
+#include <cstddef>
+#include <filesystem>
+#include <string>
+#include <vector>
+
+namespace WallpaperEngine::Application {
+/**
+ * Where WE's daytime and dayofweek playlists (wallpaper64.exe 2.8.42, sub_140075A90 and sub_140067A00) switch.
+ * Every item has an end, the first item whose end is past the clock is the one shown, the last item when none is.
+ */
+
+/**
+ * Daytime ends as fractions of the day. requested holds each item's "daytimeend" (0 or less when it has none): items
+ * without one share the time up to the next one that has one evenly, the last item always ends at 1
+ */
+[[nodiscard]] std::vector<float> daytimeEnds (const std::vector<float>& requested);
+
+/** Day of week ends in days since the first day of the week: 7 days shared out among at most 7 items */
+[[nodiscard]] std::vector<float> dayOfWeekEnds (std::size_t count);
+
+[[nodiscard]] std::size_t scheduledIndex (const std::vector<float>& ends, float position);
+
+/** minutes into the local day as WE counts them, divided by 1440 */
+[[nodiscard]] float daytimePosition (int hour, int minute);
+
+/** weekday: 0 is Sunday like tm_wday, firstWeekday likewise, the result counts days from the first one */
+[[nodiscard]] float dayOfWeekPosition (int weekday, int firstWeekday);
+
+/** the first day of the week of the current locale, 0 is Sunday (WE asks Windows' LOCALE_IFIRSTDAYOFWEEK) */
+[[nodiscard]] int localeFirstWeekday ();
+
+/** item to show for the local clock now, the playlist's mode is "daytime" or "dayofweek" */
+[[nodiscard]] std::size_t scheduledIndexNow (const std::vector<float>& ends, bool dayOfWeek);
+
+/**
+ * "logon" playlists show the next item once per session (WE keeps the index in its config). The state file maps a
+ * playlist name to the index it showed and the session that was started in: the same session asking again gets the
+ * same item, a new one the item after it. A missing or unreadable file starts at the first item. Without commit the
+ * state file is only read, asking again with commit records the item (and gives the same answer)
+ */
+[[nodiscard]] std::size_t logonIndex (
+    const std::filesystem::path& stateFile, const std::string& playlist, std::size_t count, const std::string& session,
+    bool commit = true
+);
+
+/** id of the mount holding dir from /proc/self/mountinfo, empty when it cannot be told */
+[[nodiscard]] std::string runtimeMountId (const std::string& dir);
+
+/**
+ * the id stored in dir/lwe-login, made on first use: a file in the user's runtime folder is gone with the last logout.
+ * Empty when dir cannot hold it
+ */
+[[nodiscard]] std::string loginMarker (const std::filesystem::path& dir);
+
+/**
+ * boot id and the mount of the user's runtime dir: a new boot or a login after the last logout is a new session. A
+ * Flatpak has a mount of its own for the runtime dir on every run, there the marker in the app's shared folder tells
+ * the logins apart
+ */
+[[nodiscard]] std::string currentSessionToken ();
+
+[[nodiscard]] std::filesystem::path logonStateFile ();
+}

+ 323 - 39
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -1,7 +1,9 @@
 #include "WallpaperApplication.h"
+#include "WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h"
 #include "WallpaperEngine/Debugging/Profiling.h"
 
 #include "ControlFileOwner.h"
+#include "PlaylistSchedule.h"
 #include "WallpaperEngine/Render/Transition.h"
 
 #include <cstdlib>
@@ -65,6 +67,7 @@ using WallpaperEngine::Data::Utils::parseFiniteFloat;
 
 #define FULLSCREEN_CHECK_WAIT_TIME 250000
 #define INPUT_SUSPEND_AFTER std::chrono::seconds (3)
+#define SCHEDULE_RETRY_AFTER std::chrono::seconds (60)
 
 float g_Time;
 float g_TimeLast;
@@ -186,10 +189,12 @@ void WallpaperApplication::loadBackgrounds () {
 
 	if (this->m_context.settings.general.defaultPlaylist.has_value ()
 	    && !this->m_context.settings.general.defaultPlaylist->items.empty ()) {
-	    path = this->m_context.settings.general.defaultPlaylist->items.front ();
+	    const auto& playlist = this->m_context.settings.general.defaultPlaylist.value ();
+
+	    path = playlist.items[playlist.startItem ()];
 	}
 
-	this->m_backgrounds["default"] = this->loadBackground (path);
+	this->m_backgrounds["default"] = this->loadBackground (path, this->playlistItemPreset ("default", path));
 	return;
     }
 
@@ -200,7 +205,7 @@ void WallpaperApplication::loadBackgrounds () {
 	if (path.empty ()) {
 	    this->m_backgrounds[screen] = this->loadBackground (this->m_context.settings.general.defaultBackground);
 	} else {
-	    this->m_backgrounds[screen] = this->loadBackground (path);
+	    this->m_backgrounds[screen] = this->loadBackground (path, this->playlistItemPreset (screen, path));
 	}
     }
 
@@ -215,7 +220,7 @@ void WallpaperApplication::loadBackgrounds () {
 	}
 
 	const std::string groupKey = "span:" + spanGroup.screens.front ();
-	this->m_backgrounds[groupKey] = this->loadBackground (bgPath);
+	this->m_backgrounds[groupKey] = this->loadBackground (bgPath, this->playlistItemPreset (groupKey, bgPath));
     }
 }
 
@@ -318,9 +323,10 @@ ImageAdjustments parseImageAdjustments (const WallpaperEngine::Data::JSON::JSON&
 }
 
 void WallpaperApplication::applyPreset (
-    Project& project, const WallpaperEngine::Data::JSON::JSON& preset, const std::filesystem::path& presetDir
+    Project& project, const WallpaperEngine::Data::JSON::JSON& preset, const std::filesystem::path& presetDir,
+    const bool confineFiles
 ) {
-    project.imageAdjustments = parseImageAdjustments (preset);
+    project.imageAdjustments = parseImageAdjustments (preset).over (project.imageAdjustments);
 
     for (const auto& entry : preset.items ()) {
 	const auto property = project.properties.find (entry.key ());
@@ -351,7 +357,7 @@ void WallpaperApplication::applyPreset (
 
 	    // a preset is someone else's content, its files are in its own folder: "/" or "../.." must not open the
 	    // user's disk to a web page
-	    if (pathError || inside.empty () || *inside.begin () == "..") {
+	    if (confineFiles && (pathError || inside.empty () || *inside.begin () == "..")) {
 		sLog.error ("Preset value for ", entry.key (), " is outside the preset's folder, ignored: ", text);
 		continue;
 	    }
@@ -379,7 +385,51 @@ void WallpaperApplication::applyPreset (
     }
 }
 
-ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) try {
+const WallpaperEngine::Data::JSON::JSON*
+WallpaperApplication::playlistItemPreset (const std::string& screen, const std::filesystem::path& path) const {
+    const ApplicationContext::PlaylistDefinition* playlist = nullptr;
+
+    if (screen == "default") {
+	if (this->m_context.settings.general.defaultPlaylist.has_value ()) {
+	    playlist = &*this->m_context.settings.general.defaultPlaylist;
+	}
+    } else if (
+	const auto found = this->m_context.settings.general.screenPlaylists.find (screen);
+	found != this->m_context.settings.general.screenPlaylists.end ()
+    ) {
+	playlist = &found->second;
+    }
+
+    if (playlist == nullptr) {
+	return nullptr;
+    }
+
+    std::optional<std::size_t> shown = playlist->startIndex;
+
+    if (const auto active = this->m_activePlaylists.find (screen); active != this->m_activePlaylists.end ()) {
+	if (active->second.scheduledItem.has_value ()) {
+	    shown = active->second.scheduledItem;
+	} else if (active->second.orderIndex < active->second.order.size ()) {
+	    shown = active->second.order[active->second.orderIndex];
+	}
+    }
+
+    // a wallpaper can be listed twice with different presets, so the item on screen wins over the first match
+    if (shown.has_value () && *shown < playlist->items.size () && playlist->items[*shown] == path) {
+	return playlist->presetValues (*shown);
+    }
+
+    const auto item = std::find (playlist->items.begin (), playlist->items.end (), path);
+
+    if (item == playlist->items.end ()) {
+	return nullptr;
+    }
+
+    return playlist->presetValues (static_cast<std::size_t> (item - playlist->items.begin ()));
+}
+
+ProjectUniquePtr
+WallpaperApplication::loadBackground (const std::string& bg, const WallpaperEngine::Data::JSON::JSON* userPreset) try {
     LWE_ZONE_TEXT ("load background", bg);
     auto [container, json, preset, directory] = this->openProjectSource (bg);
 
@@ -411,16 +461,23 @@ ProjectUniquePtr WallpaperApplication::loadBackground (const std::string& bg) tr
     // WE opens scene.pkg when there is one
     project->sceneFile = std::filesystem::exists (folder / "scene.pkg") ? folder / "scene.pkg" : folder / sceneFileName;
 
-    if (preset.has_value ()) {
-	std::filesystem::path presetDir = bg;
+    std::filesystem::path presetDir = bg;
 
-	if (!presetDir.has_filename ()) {
-	    presetDir = presetDir.parent_path ();
-	}
+    if (!presetDir.has_filename ()) {
+	presetDir = presetDir.parent_path ();
+    }
 
+    if (preset.has_value ()) {
 	applyPreset (*project, *preset, presetDir);
     }
 
+    if (userPreset != nullptr) {
+	auto values = *userPreset;
+
+	values.erase ("name");
+	applyPreset (*project, values, presetDir, false);
+    }
+
     return project;
 } catch (const std::exception& e) {
     throw std::runtime_error ("Cannot load wallpaper '" + bg + "': " + e.what ());
@@ -461,10 +518,36 @@ void WallpaperApplication::initializePlaylists () {
 
 	ActivePlaylist state;
 
+	// the item started with, not the first one with the same path: a wallpaper can be listed twice
+	std::optional<std::size_t> shownStart;
+
+	if (currentPath.has_value () && playlist.startIndex.has_value ()
+	    && *playlist.startIndex < playlist.items.size ()
+	    && playlist.items[*playlist.startIndex] == currentPath.value ()) {
+	    shownStart = playlist.startIndex;
+	}
+
+	playlist.commitStart ();
 	state.definition = playlist;
 	state.order = this->buildPlaylistOrder (playlist);
 	state.introPlaying = playlist.settings.hasIntro () && playlist.items.size () > 1;
 
+	if (playlist.settings.isScheduled () && playlist.items.size () > 1) {
+	    state.scheduleEnds = playlist.scheduleEnds ();
+	    // the item that is on screen, not the clock now: loading can take long enough to cross a boundary
+	    const auto shown = currentPath.has_value ()
+		? std::find (playlist.items.begin (), playlist.items.end (), currentPath.value ())
+		: playlist.items.end ();
+
+	    state.scheduledItem = shownStart.has_value () ? shownStart
+		: shown != playlist.items.end ()
+		? std::optional<std::size_t> { static_cast<std::size_t> (shown - playlist.items.begin ()) }
+		: std::optional<std::size_t> { playlist.startItem () };
+	    sLog.out (
+		"Playlist ", playlist.name, ": ", playlist.settings.mode, " starts with item ", *state.scheduledItem
+	    );
+	}
+
 	if (state.order.empty ()) {
 	    return;
 	}
@@ -473,7 +556,8 @@ void WallpaperApplication::initializePlaylists () {
 	    state.orderIndex = 0;
 
 	    for (std::size_t i = 0; i < state.order.size (); i++) {
-		if (playlist.items[state.order[i]] == currentPath.value ()) {
+		if (shownStart.has_value () ? state.order[i] == *shownStart
+					    : playlist.items[state.order[i]] == currentPath.value ()) {
 		    state.orderIndex = i;
 		    break;
 		}
@@ -493,7 +577,7 @@ void WallpaperApplication::initializePlaylists () {
 	const auto& playlist = this->m_context.settings.general.defaultPlaylist.value ();
 	const auto currentPath = playlist.items.empty ()
 	    ? std::optional<std::filesystem::path> { this->m_context.settings.general.defaultBackground }
-	    : std::optional<std::filesystem::path> { playlist.items.front () };
+	    : std::optional<std::filesystem::path> { playlist.items[playlist.startItem ()] };
 	registerPlaylist ("default", playlist, currentPath);
     }
 
@@ -588,7 +672,7 @@ void WallpaperApplication::advancePlaylist (
 
     std::size_t candidateOrderIndex = playlist.orderIndex;
 
-    if (!this->selectNextCandidate (playlist, candidateOrderIndex)) {
+    if (!WallpaperEngine::Application::WallpaperApplication::selectNextCandidate (playlist, candidateOrderIndex)) {
 	sLog.error ("All playlist items failed for ", screen, ", keeping current wallpaper");
 	const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
 	playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
@@ -602,7 +686,7 @@ void WallpaperApplication::advancePlaylist (
     if (!this->preflightWallpaper (candidatePath.string ())) {
 	playlist.failedIndices.insert (candidateIndex);
 
-	if (!this->selectNextCandidate (playlist, candidateOrderIndex)) {
+	if (!WallpaperEngine::Application::WallpaperApplication::selectNextCandidate (playlist, candidateOrderIndex)) {
 	    sLog.error ("All playlist items failed for ", screen, ", keeping current wallpaper");
 	    const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
 	    playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
@@ -612,7 +696,16 @@ void WallpaperApplication::advancePlaylist (
     }
 
     playlist.orderIndex = candidateOrderIndex;
-    const auto& nextPath = playlist.definition.items[playlist.order[playlist.orderIndex]];
+    this->loadPlaylistItem (screen, playlist, playlist.order[playlist.orderIndex]);
+
+    const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
+    playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
+}
+
+bool WallpaperApplication::loadPlaylistItem (
+    const std::string& screen, ActivePlaylist& playlist, const std::size_t itemIndex
+) {
+    const auto& nextPath = playlist.definition.items[itemIndex];
 
     bool loaded = false;
 
@@ -622,9 +715,12 @@ void WallpaperApplication::advancePlaylist (
 	    throw std::runtime_error ("No viewport available");
 	}
 
-	auto project = this->loadBackground (nextPath.string ());
+	const auto* userPreset = playlist.definition.presetValues (itemIndex);
+	auto project = this->loadBackground (nextPath.string (), userPreset);
 
 	this->setupPropertiesForProject (*project);
+	this->setupAudioSensitivityForProject (*project);
+	this->setupSoundVolumeForProject (*project);
 	this->ensureAudioCapture (*project);
 
 	// the outgoing project must outlive setWallpaper(), the old wallpaper keeps a reference into it
@@ -634,6 +730,25 @@ void WallpaperApplication::advancePlaylist (
 	try {
 	    if (this->m_renderContext) {
 		this->installWallpaper (screen, *this->m_backgrounds[screen], nextPath, true, true);
+
+		const auto& render = this->m_context.settings.render;
+
+		if (playlist.definition.settings.randomTransition && !render.transitionChosen) {
+		    const auto& transition
+			= Render::RANDOM_TRANSITIONS[this->m_playlistRng () % Render::RANDOM_TRANSITIONS.size ()];
+		    const int milliseconds
+			= render.transitionMsChosen ? render.transitionMs : playlist.definition.settings.transitionMs;
+
+		    // a span group holds its frames under each member output, not under its own key
+		    if (const auto* spanGroup = this->findSpanGroup (screen)) {
+			for (const auto& member : spanGroup->screens) {
+			    this->m_renderContext->overrideTransition (member, transition, milliseconds);
+			}
+		    } else {
+			this->m_renderContext->overrideTransition (screen, transition, milliseconds);
+		    }
+		}
+
 		this->applyAudioPolicy ();
 	    }
 	} catch (...) {
@@ -648,6 +763,11 @@ void WallpaperApplication::advancePlaylist (
 	}
 
 	this->m_context.settings.general.screenBackgrounds[screen] = nextPath;
+
+	if (auto* spanGroup = this->findSpanGroup (screen)) {
+	    spanGroup->background = nextPath;
+	}
+
 	loaded = true;
     } catch (const std::exception& e) {
 	sLog.error ("Failed to advance playlist on ", screen, ": ", e.what ());
@@ -656,13 +776,56 @@ void WallpaperApplication::advancePlaylist (
     }
 
     if (!loaded) {
-	playlist.failedIndices.insert (playlist.order[playlist.orderIndex]);
+	playlist.failedIndices.insert (itemIndex);
 
 	sLog.error ("Failed to load wallpaper for ", screen, ", skipping it until the playlist comes round again");
     }
 
-    const uint32_t delayMinutes = std::max<uint32_t> (1, playlist.definition.settings.delayMinutes);
-    playlist.nextSwitch = now + std::chrono::minutes (delayMinutes);
+    return loaded;
+}
+
+void WallpaperApplication::updateScheduledPlaylist (
+    const std::string& screen, ActivePlaylist& playlist, const std::chrono::steady_clock::time_point& now
+) {
+    if (now < playlist.nextScheduleCheck) {
+	return;
+    }
+
+    playlist.nextScheduleCheck = now + std::chrono::seconds (5);
+
+    const auto target = std::min (
+	scheduledIndexNow (playlist.scheduleEnds, playlist.definition.settings.isDayOfWeek ()),
+	playlist.definition.items.size () - 1
+    );
+
+    if (playlist.scheduleFailed.has_value () && playlist.scheduleFailed != target) {
+	playlist.scheduleFailed.reset ();
+    }
+
+    if (playlist.scheduledItem == target) {
+	return;
+    }
+
+    if (playlist.scheduleFailed == target) {
+	if (now < playlist.scheduleRetry) {
+	    return;
+	}
+
+	playlist.scheduleFailed.reset ();
+    }
+
+    sLog.out (
+	"Playlist ", playlist.definition.name, ": ", playlist.definition.settings.mode, " switches to item ", target
+    );
+
+    if (this->loadPlaylistItem (screen, playlist, target)) {
+	playlist.scheduledItem = target;
+	playlist.scheduleFailed.reset ();
+	playlist.failedIndices.clear ();
+    } else {
+	playlist.scheduleFailed = target;
+	playlist.scheduleRetry = now + SCHEDULE_RETRY_AFTER;
+    }
 }
 
 void WallpaperApplication::updatePlaylists () {
@@ -675,6 +838,14 @@ void WallpaperApplication::updatePlaylists () {
     for (auto& [screen, playlist] : this->m_activePlaylists) {
 	playlist.lastUpdate = now;
 
+	if (playlist.definition.settings.isScheduled ()) {
+	    if (!playlist.scheduleEnds.empty ()) {
+		this->updateScheduledPlaylist (screen, playlist, now);
+	    }
+
+	    continue;
+	}
+
 	if (playlist.definition.settings.mode != "timer") {
 	    continue;
 	}
@@ -750,6 +921,9 @@ struct HotswapRequest {
     std::optional<std::string> videoSegments;
     std::optional<std::string> hwdec;
     std::optional<std::string> hrtf;
+    std::optional<std::string> audioInput;
+    std::optional<std::string> audioInputVolume;
+    std::optional<std::string> audioInputThreshold;
     std::optional<std::string> transition;
     std::optional<std::string> transitionDuration;
     std::optional<std::string> videoSeek;
@@ -913,6 +1087,12 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	    request.hwdec = value;
 	} else if (key == "hrtf") {
 	    request.hrtf = value;
+	} else if (key == "audio-input") {
+	    request.audioInput = value;
+	} else if (key == "audio-input-volume") {
+	    request.audioInputVolume = value;
+	} else if (key == "audio-input-threshold") {
+	    request.audioInputThreshold = value;
 	} else if (key == "transition") {
 	    request.transition = value;
 	} else if (key == "transition-duration") {
@@ -1005,8 +1185,9 @@ void WallpaperApplication::checkHotswapRequest () {
 	&& !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.hwdec.has_value () && !request.hrtf.has_value () && !request.audioInput.has_value ()
+	&& !request.audioInputVolume.has_value () && !request.audioInputThreshold.has_value ()
+	&& !request.transition.has_value () && !request.transitionDuration.has_value ()) {
 	sLog.error ("Hotswap requested but control file was empty");
 	return;
     }
@@ -1021,6 +1202,7 @@ void WallpaperApplication::checkHotswapRequest () {
     if (request.transition.has_value ()) {
 	if (WallpaperEngine::Render::parseTransition (*request.transition).has_value ()) {
 	    this->m_context.settings.render.transition = *request.transition;
+	    this->m_context.settings.render.transitionChosen = true;
 	} else {
 	    sLog.error ("Hotswap: ignoring invalid transition value: ", *request.transition);
 	}
@@ -1032,6 +1214,7 @@ void WallpaperApplication::checkHotswapRequest () {
 		std::stoi (*request.transitionDuration), WallpaperEngine::Render::TRANSITION_MIN_MS,
 		WallpaperEngine::Render::TRANSITION_MAX_MS
 	    );
+	    this->m_context.settings.render.transitionMsChosen = true;
 	} catch (const std::exception&) {
 	    sLog.error ("Hotswap: ignoring invalid transition-duration value: ", *request.transitionDuration);
 	}
@@ -1178,6 +1361,11 @@ void WallpaperApplication::checkHotswapRequest () {
 	}
     }
 
+    if (request.audioInput.has_value () || request.audioInputVolume.has_value ()
+	|| request.audioInputThreshold.has_value ()) {
+	this->applyAudioInputHotswap (request.audioInput, request.audioInputVolume, request.audioInputThreshold);
+    }
+
     if (request.audioScreen.has_value ()) {
 	this->applyAudioScreenHotswap (*request.audioScreen);
     }
@@ -1326,7 +1514,9 @@ void WallpaperApplication::checkHotswapRequest () {
 	const bool animate = request.path.has_value () && targetPath != currentPath;
 
 	try {
-	    auto project = this->loadBackground (targetPath);
+	    auto project = this->loadBackground (
+		targetPath, targetPath == currentPath ? this->playlistItemPreset (screen, targetPath) : nullptr
+	    );
 
 	    this->setupPropertiesForProject (*project);
 	    this->setupAudioSensitivityForProject (*project);
@@ -2046,6 +2236,56 @@ void WallpaperApplication::applyAudioScreenHotswap (const std::string& value) {
     sLog.out ("Hotswap: applied audio screen '", value, "' live");
 }
 
+WallpaperEngine::Audio::AudioInput WallpaperApplication::audioInput () const {
+    return this->m_context.settings.audio.input;
+}
+
+void WallpaperApplication::applyAudioInputHotswap (
+    const std::optional<std::string>& device, const std::optional<std::string>& volume,
+    const std::optional<std::string>& threshold
+) {
+    auto& audio = this->m_context.settings.audio;
+    bool changed = false;
+
+    if (device.has_value ()) {
+	const std::string next = device->empty () ? "default" : *device;
+
+	changed = changed || next != audio.input.device;
+	audio.input.device = next;
+    }
+
+    if (volume.has_value ()) {
+	if (const auto parsed = ApplicationContext::parseAudioInputVolume (*volume); parsed.has_value ()) {
+	    audio.input.volume = *parsed;
+	    changed = true;
+	} else {
+	    sLog.error ("Hotswap: ignoring invalid audio input volume value: ", *volume);
+	}
+    }
+
+    if (threshold.has_value ()) {
+	if (const auto parsed = ApplicationContext::parseAudioInputThreshold (*threshold); parsed.has_value ()) {
+	    audio.input.threshold = *parsed;
+	    changed = true;
+	} else {
+	    sLog.error ("Hotswap: ignoring invalid audio input threshold value: ", *threshold);
+	}
+    }
+
+    if (!changed) {
+	return;
+    }
+
+    // a wallpaper without audio processing has no capture yet, ensureAudioCapture starts it with these settings
+    if (auto* recorder = dynamic_cast<WallpaperEngine::Audio::Drivers::Recorders::PulseAudioPlaybackRecorder*> (
+	    this->m_audioRecorder.get ()
+	)) {
+	recorder->setInput (this->audioInput ());
+    }
+
+    sLog.out ("Hotswap: applied audio input live");
+}
+
 void WallpaperApplication::applyAmbientVolumeHotswap (const std::string& value) {
     int volume;
 
@@ -2117,7 +2357,7 @@ void WallpaperApplication::setupProperties () {
     }
 }
 
-void WallpaperApplication::listObjectsForProject (const std::string& background, const Project& project) const {
+void WallpaperApplication::listObjectsForProject (const std::string& background, const Project& project) {
     if (!project.wallpaper->is<Scene> ()) {
 	return;
     }
@@ -2149,11 +2389,11 @@ void WallpaperApplication::listObjects () const {
     }
 
     for (const auto& [background, info] : this->m_backgrounds) {
-	this->listObjectsForProject (background, *info);
+	WallpaperEngine::Application::WallpaperApplication::listObjectsForProject (background, *info);
     }
 }
 
-void WallpaperApplication::listEffectsForProject (const std::string& background, const Project& project) const {
+void WallpaperApplication::listEffectsForProject (const std::string& background, const Project& project) {
     if (!project.wallpaper->is<Scene> ()) {
 	return;
     }
@@ -2184,11 +2424,11 @@ void WallpaperApplication::listEffects () const {
     }
 
     for (const auto& [background, info] : this->m_backgrounds) {
-	this->listEffectsForProject (background, *info);
+	WallpaperEngine::Application::WallpaperApplication::listEffectsForProject (background, *info);
     }
 }
 
-void WallpaperApplication::listFontsForProject (const std::string& background, const Project& project) const {
+void WallpaperApplication::listFontsForProject (const std::string& background, const Project& project) {
     if (!project.wallpaper->is<Scene> ()) {
 	return;
     }
@@ -2258,7 +2498,7 @@ void WallpaperApplication::listFonts () const {
     }
 
     for (const auto& [background, info] : this->m_backgrounds) {
-	this->listFontsForProject (background, *info);
+	WallpaperEngine::Application::WallpaperApplication::listFontsForProject (background, *info);
     }
 }
 
@@ -2327,7 +2567,7 @@ float readScriptPropertyFloat (DynamicValue& value, const std::string& key) {
 }
 }
 
-void WallpaperApplication::listAudioObjectsForProject (const std::string& background, const Project& project) const {
+void WallpaperApplication::listAudioObjectsForProject (const std::string& background, const Project& project) {
     if (!project.wallpaper->is<Scene> ()) {
 	return;
     }
@@ -2355,7 +2595,7 @@ void WallpaperApplication::listAudioObjects () const {
     }
 
     for (const auto& [background, info] : this->m_backgrounds) {
-	this->listAudioObjectsForProject (background, *info);
+	WallpaperEngine::Application::WallpaperApplication::listAudioObjectsForProject (background, *info);
     }
 }
 
@@ -2789,8 +3029,10 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
 	auto* bitmap = new uint8_t[width * height * 3] { 0 };
 
 	for (const auto& capture : captures) {
-	    const float spanX = std::abs (capture.uend - capture.ustart) * capture.readWidth / capture.vpWidth;
-	    const float spanY = std::abs (capture.vend - capture.vstart) * capture.readHeight / capture.vpHeight;
+	    const float spanX = std::abs (capture.uend - capture.ustart) * static_cast<float> (capture.readWidth)
+		/ static_cast<float> (capture.vpWidth);
+	    const float spanY = std::abs (capture.vend - capture.vstart) * static_cast<float> (capture.readHeight)
+		/ static_cast<float> (capture.vpHeight);
 	    const int samplesX = std::max (1, static_cast<int> (std::lround (spanX)));
 	    const int samplesY = std::max (1, static_cast<int> (std::lround (spanY)));
 	    // sample from the output pixel's center, its left edge truncated 250/1920*1920 to 249
@@ -2917,7 +3159,9 @@ void WallpaperApplication::setupAudio () {
 
     if (audioProcessingRequired && this->m_context.settings.audio.audioprocessing) {
 	this->m_audioRecorder
-	    = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PulseAudioPlaybackRecorder> ();
+	    = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PulseAudioPlaybackRecorder> (
+		this->audioInput ()
+	    );
 	this->m_audioCapturing = true;
     } else {
 	this->m_audioRecorder = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PlaybackRecorder> ();
@@ -2948,7 +3192,9 @@ void WallpaperApplication::ensureAudioCapture (const Project& project) {
     sLog.out ("Starting audio capture for ", project.title);
 
     this->m_previousAudioRecorder = std::move (this->m_audioRecorder);
-    this->m_audioRecorder = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PulseAudioPlaybackRecorder> ();
+    this->m_audioRecorder = std::make_unique<WallpaperEngine::Audio::Drivers::Recorders::PulseAudioPlaybackRecorder> (
+	this->audioInput ()
+    );
     this->m_audioDriver->setRecorder (*this->m_audioRecorder);
     this->m_audioCapturing = true;
 }
@@ -2971,6 +3217,31 @@ const ApplicationContext::SpanGroup* WallpaperApplication::findSpanGroup (const
     return nullptr;
 }
 
+namespace {
+/** The audio thread keeps mixing while the render thread builds the next wallpaper, so the outgoing one is silenced */
+struct OutgoingHush {
+    std::vector<std::weak_ptr<WallpaperEngine::Render::CWallpaper>> held;
+
+    OutgoingHush () = default;
+    OutgoingHush (const OutgoingHush&) = delete;
+    OutgoingHush& operator= (const OutgoingHush&) = delete;
+
+    void add (const std::shared_ptr<WallpaperEngine::Render::CWallpaper>& wallpaper) {
+	wallpaper->setAudioHushed (true);
+	this->held.push_back (wallpaper);
+    }
+
+    // whatever is still alive afterwards stays on screen (the swap failed, or a span group's other outputs)
+    ~OutgoingHush () {
+	for (const auto& weak : this->held) {
+	    if (const auto wallpaper = weak.lock ()) {
+		wallpaper->setAudioHushed (false);
+	    }
+	}
+    }
+};
+}
+
 void WallpaperApplication::installWallpaper (
     const std::string& screen, const Project& project, const std::filesystem::path& path, const bool holdPrevious,
     const bool animate
@@ -2980,6 +3251,19 @@ void WallpaperApplication::installWallpaper (
     const auto& window = this->m_context.settings.render.window;
     const auto* spanGroup = this->findSpanGroup (screen);
 
+    OutgoingHush outgoing;
+
+    if (holdPrevious) {
+	const auto& installed = this->m_renderContext->getWallpapers ();
+	const std::vector<std::string> names = spanGroup != nullptr ? spanGroup->screens : std::vector { screen };
+
+	for (const auto& name : names) {
+	    if (const auto it = installed.find (name); it != installed.end ()) {
+		outgoing.add (it->second);
+	    }
+	}
+    }
+
     if (spanGroup == nullptr) {
 	const auto scalingIt = general.screenScalings.find (screen);
 	const auto clampIt = general.screenClamps.find (screen);
@@ -3088,7 +3372,7 @@ void WallpaperApplication::setup () {
 
     this->setupAudio ();
     this->prepareOutputs ();
-    this->setupOpenGLDebugging ();
+    WallpaperEngine::Application::WallpaperApplication::setupOpenGLDebugging ();
     this->updatePowerMonitor ();
     this->updateSessionMonitor ();
 
@@ -3172,7 +3456,7 @@ void WallpaperApplication::render () {
 	const time_t seconds = time (nullptr);
 	struct tm timeinfo {};
 	localtime_r (&seconds, &timeinfo);
-	g_Daytime = static_cast<float> ((timeinfo.tm_hour * 60) + timeinfo.tm_min) / (24.0f * 60.0f);
+	g_Daytime = daytimePosition (timeinfo.tm_hour, timeinfo.tm_min);
 
 	// LWE_FIXED_TIMESTEP=<seconds>: same step every frame so frame N always shows the same moment (regression
 	// renders)

+ 29 - 8
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -14,6 +14,7 @@
 #include "WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.h"
 #include "WallpaperEngine/Render/RenderContext.h"
 
+#include "WallpaperEngine/Audio/AudioInput.h"
 #include "WallpaperEngine/Audio/Drivers/SDLAudioDriver.h"
 
 #include "WallpaperEngine/Input/InputContext.h"
@@ -66,27 +67,33 @@ private:
     AssetLocatorUniquePtr setupAssetLocator (const std::string& bg, const std::filesystem::path& overlay = {}) const;
     ProjectSource openProjectSource (const std::string& path) const;
     static void applyPreset (
-	Project& project, const WallpaperEngine::Data::JSON::JSON& preset, const std::filesystem::path& presetDir
+	Project& project, const WallpaperEngine::Data::JSON::JSON& preset, const std::filesystem::path& presetDir,
+	bool confineFiles = true
     );
     void initializeSubsystems ();
     void loadBackgrounds ();
-    [[nodiscard]] ProjectUniquePtr loadBackground (const std::string& bg);
+    [[nodiscard]] ProjectUniquePtr
+    loadBackground (const std::string& bg, const WallpaperEngine::Data::JSON::JSON* userPreset = nullptr);
+    /** what a playlist item of screen ("default" for the window modes) saved as its preset, if path is one of its items
+     */
+    [[nodiscard]] const WallpaperEngine::Data::JSON::JSON*
+    playlistItemPreset (const std::string& screen, const std::filesystem::path& path) const;
     void setupProperties ();
     void setupPropertiesForProject (const Project& project);
 
     void listObjects () const;
-    void listObjectsForProject (const std::string& background, const Project& project) const;
+    static void listObjectsForProject (const std::string& background, const Project& project);
 
     void listEffects () const;
     void listFonts () const;
-    void listFontsForProject (const std::string& background, const Project& project) const;
-    void listEffectsForProject (const std::string& background, const Project& project) const;
+    static void listFontsForProject (const std::string& background, const Project& project);
+    static void listEffectsForProject (const std::string& background, const Project& project);
 
     void setupAudioSensitivity ();
     void setupAudioSensitivityForProject (const Project& project) const;
 
     void listAudioObjects () const;
-    void listAudioObjectsForProject (const std::string& background, const Project& project) const;
+    static void listAudioObjectsForProject (const std::string& background, const Project& project);
 
     void setupSoundVolume ();
     void setupSoundVolumeForProject (const Project& project) const;
@@ -96,7 +103,7 @@ private:
     void setupAudio ();
     void ensureAudioCapture (const Project& project);
     void prepareOutputs ();
-    void setupOpenGLDebugging ();
+    static void setupOpenGLDebugging ();
     void takeScreenshot (const std::filesystem::path& filename) const;
 
     struct ActivePlaylist {
@@ -107,6 +114,11 @@ private:
 	std::chrono::steady_clock::time_point lastUpdate;
 	std::set<std::size_t> failedIndices;
 	bool introPlaying = false;
+	std::vector<float> scheduleEnds;
+	std::optional<std::size_t> scheduledItem;
+	std::optional<std::size_t> scheduleFailed;
+	std::chrono::steady_clock::time_point scheduleRetry;
+	std::chrono::steady_clock::time_point nextScheduleCheck;
     };
 
     void initializePlaylists ();
@@ -115,11 +127,20 @@ private:
     void advancePlaylist (
 	const std::string& screen, ActivePlaylist& playlist, const std::chrono::steady_clock::time_point& now
     );
-    bool selectNextCandidate (ActivePlaylist& playlist, std::size_t& outOrderIndex);
+    static bool selectNextCandidate (ActivePlaylist& playlist, std::size_t& outOrderIndex);
+    bool loadPlaylistItem (const std::string& screen, ActivePlaylist& playlist, std::size_t itemIndex);
+    void updateScheduledPlaylist (
+	const std::string& screen, ActivePlaylist& playlist, const std::chrono::steady_clock::time_point& now
+    );
     bool preflightWallpaper (const std::string& path);
     std::vector<std::size_t> buildPlaylistOrder (const ApplicationContext::PlaylistDefinition& definition);
     bool makeAnyViewportCurrent () const;
 
+    [[nodiscard]] WallpaperEngine::Audio::AudioInput audioInput () const;
+    void applyAudioInputHotswap (
+	const std::optional<std::string>& device, const std::optional<std::string>& volume,
+	const std::optional<std::string>& threshold
+    );
     void applyVolumeHotswap (int volume);
     void applyFpsHotswap (int fps);
     void applyBatteryFpsHotswap (const std::string& value);

+ 11 - 10
src/WallpaperEngine/Assets/AssetLocator.h

@@ -9,18 +9,19 @@ class AssetLocator {
 public:
     explicit AssetLocator (ContainerUniquePtr filesystem);
 
-    std::string vertexShader (const std::filesystem::path& filename) const;
-    std::string fragmentShader (const std::filesystem::path& filename) const;
-    std::string geometryShader (const std::filesystem::path& filename) const;
-    std::string includeShader (const std::filesystem::path& filename) const;
-    ReadStreamSharedPtr texture (const std::filesystem::path& filename) const;
-    std::string readString (const std::filesystem::path& filename) const;
-    ReadStreamSharedPtr read (const std::filesystem::path& path) const;
-    std::filesystem::path physicalPath (const std::filesystem::path& path) const;
-    std::optional<std::filesystem::path> resolveWorkshopDependencyAlias (const std::filesystem::path& path) const;
+    [[nodiscard]] std::string vertexShader (const std::filesystem::path& filename) const;
+    [[nodiscard]] std::string fragmentShader (const std::filesystem::path& filename) const;
+    [[nodiscard]] std::string geometryShader (const std::filesystem::path& filename) const;
+    [[nodiscard]] std::string includeShader (const std::filesystem::path& filename) const;
+    [[nodiscard]] ReadStreamSharedPtr texture (const std::filesystem::path& filename) const;
+    [[nodiscard]] std::string readString (const std::filesystem::path& filename) const;
+    [[nodiscard]] ReadStreamSharedPtr read (const std::filesystem::path& path) const;
+    [[nodiscard]] std::filesystem::path physicalPath (const std::filesystem::path& path) const;
+    [[nodiscard]] std::optional<std::filesystem::path>
+    resolveWorkshopDependencyAlias (const std::filesystem::path& path) const;
 
 private:
-    std::string shader (const std::filesystem::path& filename) const;
+    [[nodiscard]] std::string shader (const std::filesystem::path& filename) const;
 
     ContainerUniquePtr m_filesystem;
 };

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

@@ -48,7 +48,7 @@ namespace Audio {
 	[[nodiscard]] AVSampleFormat getFormat () const;
 	[[nodiscard]] int getSampleRate () const;
 	[[nodiscard]] int getChannels () const;
-	Application::ApplicationContext& getApplicationContext () const;
+	[[nodiscard]] Application::ApplicationContext& getApplicationContext () const;
 	[[nodiscard]] Drivers::Recorders::PlaybackRecorder& getRecorder () const;
 
 	[[nodiscard]] Drivers::AudioDriver& getDriver () const;

+ 16 - 0
src/WallpaperEngine/Audio/AudioInput.h

@@ -0,0 +1,16 @@
+#pragma once
+
+#include <string>
+
+namespace WallpaperEngine::Audio {
+/** WE's audioinputdevice, audioinputvolume and audioinputthreshold */
+struct AudioInput {
+    /** a source (microphone, line in, a monitor) by name or description, a sink by name for its monitor; empty or
+     * "default" is the default sink's monitor */
+    std::string device = "default";
+    /** 50 is neutral, the spectrum is scaled by volume * 0.02 */
+    int volume = 50;
+    /** packets whose loudest sample stays under threshold * 0.001 count as silence, 0 is off */
+    float threshold = 0.0f;
+};
+}

+ 19 - 21
src/WallpaperEngine/Audio/AudioStream.cpp

@@ -30,7 +30,7 @@ static int audio_read_thread (void* arg) {
 	   && stream->isInitialized ()) {
 	if (stream->getQueueSize () >= MAX_QUEUE_SIZE
 	    || (stream->getQueuePacketCount () > MIN_FRAMES
-		&& (av_q2d (stream->getTimeBase ()) * stream->getQueueDuration () > 1.0))) {
+		&& (av_q2d (stream->getTimeBase ()) * static_cast<double> (stream->getQueueDuration ()) > 1.0))) {
 	    SDL_LockMutex (waitMutex);
 	    SDL_CondWaitTimeout (stream->getWaitCondition (), waitMutex, 10);
 	    SDL_UnlockMutex (waitMutex);
@@ -78,7 +78,7 @@ static int audio_read_data_callback (void* streamarg, uint8_t* buffer, int buffe
 	return AVERROR_INVALIDDATA;
     }
 
-    return stream->getBuffer ()->gcount ();
+    return static_cast<int> (stream->getBuffer ()->gcount ());
 }
 
 static int64_t audio_seek_data_callback (void* streamarg, int64_t offset, int whence) {
@@ -212,7 +212,7 @@ void AudioStream::loadCustomContent (const char* filename) {
     for (unsigned int i = 0; i < this->m_formatContext->nb_streams; i++) {
 	if (this->m_formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO
 	    && this->m_audioStream == NO_AUDIO_STREAM) {
-	    this->m_audioStream = i;
+	    this->m_audioStream = static_cast<int> (i);
 	}
     }
 
@@ -507,6 +507,19 @@ void AudioStream::stop () {
     this->m_initialized = false;
 }
 
+int AudioStream::convertInto (const int capacity, const uint8_t** input, const int inputSamples) {
+    const size_t offset = this->m_source.size ();
+
+    this->m_source.resize (offset + static_cast<size_t> (capacity) * this->m_channels);
+
+    auto* out = reinterpret_cast<uint8_t*> (this->m_source.data () + offset);
+    const int converted = swr_convert (this->m_swrctx, &out, capacity, input, inputSamples);
+
+    this->m_source.resize (offset + static_cast<size_t> (std::max (converted, 0)) * this->m_channels);
+
+    return converted;
+}
+
 bool AudioStream::convertFrame () {
     const int samples = this->m_decodeFrame->nb_samples;
 
@@ -514,15 +527,7 @@ bool AudioStream::convertFrame () {
 	return false;
     }
 
-    const size_t offset = this->m_source.size ();
-
-    this->m_source.resize (offset + static_cast<size_t> (samples) * this->m_channels);
-
-    auto* out = reinterpret_cast<uint8_t*> (this->m_source.data () + offset);
-    const int converted
-	= swr_convert (this->m_swrctx, &out, samples, const_cast<const uint8_t**> (this->m_decodeFrame->data), samples);
-
-    this->m_source.resize (offset + static_cast<size_t> (std::max (converted, 0)) * this->m_channels);
+    const int converted = this->convertInto (samples, const_cast<const uint8_t**> (this->m_decodeFrame->data), samples);
 
     if (converted < 0) {
 	sLog.error ("swr_convert_error.");
@@ -538,14 +543,7 @@ void AudioStream::flushConverter () {
 	return;
     }
 
-    const size_t offset = this->m_source.size ();
-
-    this->m_source.resize (offset + static_cast<size_t> (samples) * this->m_channels);
-
-    auto* out = reinterpret_cast<uint8_t*> (this->m_source.data () + offset);
-    const int converted = swr_convert (this->m_swrctx, &out, samples, nullptr, 0);
-
-    this->m_source.resize (offset + static_cast<size_t> (std::max (converted, 0)) * this->m_channels);
+    this->convertInto (samples, nullptr, 0);
 }
 
 int AudioStream::decodeSource () {
@@ -692,7 +690,7 @@ std::vector<int> AudioStream::passes (const int frames) const {
     uint32_t frac = this->m_sourceFrac;
 
     for (int done = 0; done < frames;) {
-	uint64_t count = static_cast<uint64_t> (frames - done);
+	auto count = static_cast<uint64_t> (frames - done);
 
 	if (this->m_step > MixerFracOne
 	    && ((count * this->m_step + frac) >> MixerFracBits) + MaxResamplerPadding

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

@@ -88,6 +88,8 @@ public:
 
 private:
     void loadCustomContent (const char* filename = nullptr);
+    // appends what swr_convert produced to m_source, its return value
+    int convertInto (int capacity, const uint8_t** input, int inputSamples);
     bool convertFrame ();
     void flushConverter ();
     // decodes the next frame onto m_source without waiting: 1 added, 0 nothing queued, -1 end or error

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

@@ -63,7 +63,7 @@ namespace Audio {
 	    [[nodiscard]] virtual AVSampleFormat getFormat () const = 0;
 	    [[nodiscard]] virtual int getSampleRate () const = 0;
 	    [[nodiscard]] virtual int getChannels () const = 0;
-	    Application::ApplicationContext& getApplicationContext () const;
+	    [[nodiscard]] Application::ApplicationContext& getApplicationContext () const;
 	    [[nodiscard]] Detectors::AudioPlayingDetector& getAudioDetector () const;
 	    [[nodiscard]] Recorders::PlaybackRecorder& getRecorder () const;
 	    void setRecorder (Recorders::PlaybackRecorder& recorder);

+ 234 - 18
src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp

@@ -126,22 +126,16 @@ static void pa_stream_read_cb (pa_stream* stream, const size_t, void* userdata)
     }
 }
 
-void pa_server_info_cb (pa_context* ctx, const pa_server_info* info, void* userdata) {
-    if (info == nullptr || info->default_sink_name == nullptr) {
-	return;
-    }
-
-    auto* recorder = static_cast<PulseAudioPlaybackRecorder::PulseAudioData*> (userdata);
-    const std::string monitor_name = std::string (info->default_sink_name) + ".monitor";
-
+static void
+retakeCapture (PulseAudioPlaybackRecorder::PulseAudioData* recorder, pa_context* ctx, const std::string& source) {
     recorder->context = ctx;
 
     if (recorder->captureStream) {
 	// sink/source events also fire for volume and state changes (another wallpaper starting its sounds),
-	// only re-take the stream when the default sink moved or the old one died
+	// only re-take the stream when the source moved or the old one died
 	const bool alive = PA_STREAM_IS_GOOD (pa_stream_get_state (recorder->captureStream));
 
-	if (alive && monitor_name == recorder->monitorName) {
+	if (alive && source == recorder->monitorName) {
 	    return;
 	}
 
@@ -153,7 +147,7 @@ void pa_server_info_cb (pa_context* ctx, const pa_server_info* info, void* userd
 	recorder->captureStream = nullptr;
     }
 
-    recorder->monitorName = monitor_name;
+    recorder->monitorName = source;
 
     pa_sample_spec spec;
     // WE's loopback capture is float stereo, 44.1kHz gives exactly its FFT size (it scales with the rate)
@@ -163,8 +157,8 @@ void pa_server_info_cb (pa_context* ctx, const pa_server_info* info, void* userd
 
     recorder->captureStream = pa_stream_new (ctx, "output monitor", &spec, nullptr);
 
-    pa_stream_set_state_callback (recorder->captureStream, &pa_stream_notify_cb, userdata);
-    pa_stream_set_read_callback (recorder->captureStream, &pa_stream_read_cb, userdata);
+    pa_stream_set_state_callback (recorder->captureStream, &pa_stream_notify_cb, recorder);
+    pa_stream_set_read_callback (recorder->captureStream, &pa_stream_read_cb, recorder);
 
     pa_buffer_attr attr {};
 
@@ -172,15 +166,106 @@ void pa_server_info_cb (pa_context* ctx, const pa_server_info* info, void* userd
     attr.fragsize = bytesPerSec * 10 / 1000;
     attr.maxlength = attr.fragsize + bytesPerSec * 750 / 1000;
 
-    sLog.debug ("Audio processing: capturing from monitor source '", monitor_name, "' (default sink)");
+    sLog.debug ("Audio processing: capturing from source '", source, "'");
 
-    if (pa_stream_connect_record (recorder->captureStream, monitor_name.c_str (), &attr, PA_STREAM_ADJUST_LATENCY)
-	!= 0) {
+    if (pa_stream_connect_record (recorder->captureStream, source.c_str (), &attr, PA_STREAM_ADJUST_LATENCY) != 0) {
 	sLog.error ("Failed to connect to input for recording");
     }
 }
 
+static void pa_source_list_cb (pa_context* ctx, const pa_source_info* info, int eol, void* userdata) {
+    auto* recorder = static_cast<PulseAudioPlaybackRecorder::PulseAudioData*> (userdata);
+
+    if (eol == 0 && info != nullptr) {
+	const std::string name = info->name;
+	const std::string description = info->description != nullptr ? info->description : "";
+	const std::string& wanted = recorder->wantedInput;
+
+	if (name == wanted) {
+	    recorder->foundSource = name;
+	    recorder->exactMatch = true;
+	} else if (
+	    !recorder->exactMatch && recorder->foundSource.empty ()
+	    && (description == wanted || name == wanted + ".monitor")
+	) {
+	    recorder->foundSource = name;
+	}
+
+	return;
+    }
+
+    std::string target = recorder->foundSource;
+
+    // the next list starts clean, a lookup that overlaps this one must not see its result
+    recorder->foundSource.clear ();
+    recorder->exactMatch = false;
+
+    if (target.empty ()) {
+	target = recorder->defaultMonitor;
+
+	if (!recorder->missingLogged) {
+	    recorder->missingLogged = true;
+
+	    if (target.empty ()) {
+		sLog.error (
+		    "Audio input '", recorder->wantedInput, "' not found and there is no default output to capture"
+		);
+	    } else {
+		sLog.error (
+		    "Audio input '", recorder->wantedInput, "' not found, capturing the default output instead"
+		);
+	    }
+	}
+
+	if (target.empty ()) {
+	    return;
+	}
+    } else {
+	recorder->missingLogged = false;
+    }
+
+    retakeCapture (recorder, ctx, target);
+}
+
+void pa_server_info_cb (pa_context* ctx, const pa_server_info* info, void* userdata) {
+    if (info == nullptr) {
+	return;
+    }
+
+    auto* recorder = static_cast<PulseAudioPlaybackRecorder::PulseAudioData*> (userdata);
+
+    recorder->context = ctx;
+    // without a default sink there is no monitor to follow, a named source can still be captured
+    recorder->defaultMonitor
+	= info->default_sink_name != nullptr ? std::string (info->default_sink_name) + ".monitor" : std::string ();
+
+    if (recorder->wantedInput.empty () || recorder->wantedInput == "default") {
+	if (!recorder->defaultMonitor.empty ()) {
+	    retakeCapture (recorder, ctx, recorder->defaultMonitor);
+	}
+
+	return;
+    }
+
+    recorder->foundSource.clear ();
+    recorder->exactMatch = false;
+
+    if (pa_operation* o = pa_context_get_source_info_list (ctx, &pa_source_list_cb, userdata)) {
+	pa_operation_unref (o);
+    }
+}
+
 static void pa_context_subscribe_cb (pa_context* ctx, pa_subscription_event_type_t t, uint32_t idx, void* userdata) {
+    const auto* recorder = static_cast<PulseAudioPlaybackRecorder::PulseAudioData*> (userdata);
+    const auto facility = t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK;
+
+    // volume and state changes of a sink or source cannot move the capture, skip the lookups they would cost
+    if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_CHANGE
+	&& (facility == PA_SUBSCRIPTION_EVENT_SINK || facility == PA_SUBSCRIPTION_EVENT_SOURCE)
+	&& recorder->captureStream != nullptr && PA_STREAM_IS_GOOD (pa_stream_get_state (recorder->captureStream))) {
+	return;
+    }
+
     pa_operation* o = pa_context_get_server_info (ctx, &pa_server_info_cb, userdata);
     if (o) {
 	pa_operation_unref (o);
@@ -220,8 +305,14 @@ static void pa_context_notify_cb (pa_context* ctx, void* userdata) {
     }
 }
 
-PulseAudioPlaybackRecorder::PulseAudioPlaybackRecorder () :
+PulseAudioPlaybackRecorder::PulseAudioPlaybackRecorder () : PulseAudioPlaybackRecorder (Input {}) { }
+
+PulseAudioPlaybackRecorder::PulseAudioPlaybackRecorder (const Input& input) :
     m_captureData ({ .owner = this, .captureStream = nullptr, .captureLost = false }), m_analyzer (CAPTURE_RATE) {
+    this->m_inputDevice = input.device;
+    this->m_captureData.wantedInput = input.device;
+    this->m_threshold.store (input.threshold, std::memory_order_relaxed);
+    this->m_analyzer.setInputVolume (input.volume);
     this->m_stats.enabled = std::getenv ("LWE_AUDIO_STATS") != nullptr;
     this->m_dataMutex = SDL_CreateMutex ();
     this->m_mainloop = pa_mainloop_new ();
@@ -276,6 +367,103 @@ PulseAudioPlaybackRecorder::~PulseAudioPlaybackRecorder () {
     }
 }
 
+std::optional<std::vector<PulseAudioPlaybackRecorder::InputInfo>> PulseAudioPlaybackRecorder::listInputs () {
+    struct Collected {
+	std::vector<InputInfo> inputs;
+	bool done = false;
+	bool failed = false;
+    } collected;
+
+    pa_mainloop* loop = pa_mainloop_new ();
+    pa_context* ctx = pa_context_new (pa_mainloop_get_api (loop), "wallpaperengine-list-inputs");
+
+    auto finish = [&] () -> std::optional<std::vector<InputInfo>> {
+	pa_context_disconnect (ctx);
+	pa_context_unref (ctx);
+	pa_mainloop_free (loop);
+
+	if (!collected.done || collected.failed) {
+	    return std::nullopt;
+	}
+
+	return std::move (collected.inputs);
+    };
+
+    if (pa_context_connect (ctx, nullptr, PA_CONTEXT_NOAUTOSPAWN, nullptr) < 0) {
+	return finish ();
+    }
+
+    bool asked = false;
+    const auto deadline = std::chrono::steady_clock::now () + std::chrono::seconds (5);
+
+    while (!collected.done && std::chrono::steady_clock::now () < deadline) {
+	const auto state = pa_context_get_state (ctx);
+
+	if (!PA_CONTEXT_IS_GOOD (state)) {
+	    break;
+	}
+
+	if (state == PA_CONTEXT_READY && !asked) {
+	    asked = true;
+
+	    pa_operation* o = pa_context_get_source_info_list (
+		ctx,
+		[] (pa_context*, const pa_source_info* info, int eol, void* userdata) {
+		    auto* result = static_cast<Collected*> (userdata);
+
+		    if (eol != 0 || info == nullptr) {
+			result->failed = eol < 0;
+			result->done = true;
+			return;
+		    }
+
+		    result->inputs.push_back (
+			{ info->name, info->description != nullptr ? info->description : "",
+			  info->monitor_of_sink != PA_INVALID_INDEX }
+		    );
+		},
+		&collected
+	    );
+
+	    if (o != nullptr) {
+		pa_operation_unref (o);
+	    } else {
+		break;
+	    }
+	}
+
+	if (pa_mainloop_prepare (loop, 100000) < 0 || pa_mainloop_poll (loop) < 0 || pa_mainloop_dispatch (loop) < 0) {
+	    break;
+	}
+    }
+
+    return finish ();
+}
+
+void PulseAudioPlaybackRecorder::setInput (const Input& input) {
+    this->m_analyzer.setInputVolume (input.volume);
+    this->m_threshold.store (input.threshold, std::memory_order_relaxed);
+
+    {
+	Debugging::LockGuard guard (this->m_inputMutex);
+
+	if (this->m_inputDevice == input.device) {
+	    return;
+	}
+
+	this->m_inputDevice = input.device;
+    }
+
+    this->m_inputChanged.store (true, std::memory_order_release);
+    pa_mainloop_wakeup (this->m_mainloop);
+}
+
+std::string PulseAudioPlaybackRecorder::wantedInput () const {
+    Debugging::LockGuard guard (this->m_inputMutex);
+
+    return this->m_inputDevice;
+}
+
 void PulseAudioPlaybackRecorder::lock () const { SDL_LockMutex (this->m_dataMutex); }
 void PulseAudioPlaybackRecorder::unlock () const { SDL_UnlockMutex (this->m_dataMutex); }
 
@@ -288,6 +476,20 @@ void PulseAudioPlaybackRecorder::captureLoop () {
 	    break;
 	}
 
+	if (this->m_inputChanged.exchange (false, std::memory_order_acquire)) {
+	    this->m_captureData.wantedInput = this->wantedInput ();
+	    this->m_captureData.missingLogged = false;
+
+	    sLog.out ("Audio input: ", this->m_captureData.wantedInput);
+
+	    if (pa_context_get_state (this->m_context) == PA_CONTEXT_READY) {
+		if (pa_operation* o
+		    = pa_context_get_server_info (this->m_context, &pa_server_info_cb, &this->m_captureData)) {
+		    pa_operation_unref (o);
+		}
+	    }
+	}
+
 	const bool stale = std::chrono::steady_clock::now () - this->m_lastSamples > CAPTURE_TIMEOUT;
 
 	if (stale && !cleared) {
@@ -343,10 +545,24 @@ void PulseAudioPlaybackRecorder::consumeSamples (const float* samples, std::size
 	this->m_stats.count += static_cast<double> (frames * CAPTURE_CHANNELS);
     }
 
+    // audioinputthreshold: a packet whose loudest left sample (never below 0) stays under it is silence (sub_1400D02B0)
+    const float threshold = this->m_threshold.load (std::memory_order_relaxed) * 0.001f;
+    bool belowThreshold = false;
+
+    if (threshold > 1.1920929e-7f && frames > 0) {
+	float loudest = 0.0f;
+
+	for (std::size_t i = 0; i < frames; i++) {
+	    loudest = std::max (loudest, samples[i * CAPTURE_CHANNELS]);
+	}
+
+	belowThreshold = threshold > loudest;
+    }
+
     // 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) {
+    if (belowThreshold || std::all_of (samples, samples + frames * CAPTURE_CHANNELS, [] (float sample) {
 	    return Data::Utils::isZero (sample);
 	})) {
 	const auto now = std::chrono::steady_clock::now ();

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

@@ -1,33 +1,59 @@
 #pragma once
 
 #include "PlaybackRecorder.h"
+#include "WallpaperEngine/Audio/AudioInput.h"
 #include "WallpaperEngine/Audio/SpectrumAnalyzer.h"
 #include <SDL.h>
 #include <atomic>
 #include <chrono>
+#include <optional>
 #include <pulse/pulseaudio.h>
 #include <string>
 #include <thread>
+#include <vector>
 
 namespace WallpaperEngine::Audio::Drivers::Recorders {
 class PlaybackRecorder;
 
 class PulseAudioPlaybackRecorder final : public PlaybackRecorder {
 public:
+    using Input = WallpaperEngine::Audio::AudioInput;
+
     struct PulseAudioData {
 	PulseAudioPlaybackRecorder* owner = nullptr;
 	pa_stream* captureStream = nullptr;
 	std::string monitorName;
 	bool captureLost = false;
 	pa_context* context = nullptr;
+	/** capture thread only: the device asked for and what the source list lookup found so far */
+	std::string wantedInput = "default";
+	std::string defaultMonitor;
+	std::string foundSource;
+	bool exactMatch = false;
+	bool missingLogged = false;
+    };
+
+    struct InputInfo {
+	std::string name;
+	std::string description;
+	bool monitor = false;
     };
 
+    /** the server's sources, what --audio-input takes; nothing when the sound server did not answer in time */
+    [[nodiscard]] static std::optional<std::vector<InputInfo>> listInputs ();
+
     PulseAudioPlaybackRecorder ();
+    explicit PulseAudioPlaybackRecorder (const Input& input);
     ~PulseAudioPlaybackRecorder () override;
 
     void lock () const override;
     void unlock () const override;
 
+    /** applied by the capture thread within 100 ms, a changed device re-takes the stream */
+    void setInput (const Input& input);
+
+    [[nodiscard]] std::string wantedInput () const;
+
     void consumeSamples (const float* samples, std::size_t frames);
     void dropBlock ();
 
@@ -60,6 +86,11 @@ private:
 	float highMax = 0.0f;
     } m_stats;
 
+    mutable Debugging::Mutex m_inputMutex;
+    std::string m_inputDevice LWE_GUARDED_BY (m_inputMutex) = "default";
+    std::atomic<float> m_threshold { 0.0f };
+    std::atomic<bool> m_inputChanged { false };
+
     std::thread m_captureThread;
     mutable SDL_mutex* m_dataMutex = nullptr;
     std::atomic<bool> m_running { true };

+ 9 - 6
src/WallpaperEngine/Audio/SpectrumAnalyzer.cpp

@@ -12,8 +12,6 @@ constexpr float BAND_EXPONENT = 0.25f;
 constexpr float TILT = 0.501f;
 constexpr float SIZE_FACTOR = 30.0f;
 constexpr float BIN_FACTOR = 10.0f;
-// "audioinputvolume" (default 50) * 0.02
-constexpr float GAIN = 1.0f;
 }
 
 SpectrumAnalyzer::SpectrumAnalyzer (int sampleRate) {
@@ -35,6 +33,11 @@ SpectrumAnalyzer::SpectrumAnalyzer (int sampleRate) {
     this->m_output.resize (this->m_size);
 }
 
+void SpectrumAnalyzer::setInputVolume (int volume) {
+    // "audioinputvolume" (default 50) * 0.02 (sub_14006C280), the processor scales every band by it
+    this->m_gain.store (static_cast<float> (std::max (volume, 0)) * 0.02f, std::memory_order_relaxed);
+}
+
 SpectrumAnalyzer::~SpectrumAnalyzer () { kiss_fft_free (this->m_config); }
 
 void SpectrumAnalyzer::reset () { this->m_filled = 0; }
@@ -69,7 +72,7 @@ bool SpectrumAnalyzer::feed (const float* samples, std::size_t frames, int chann
 void SpectrumAnalyzer::analyze (int channels, float* bands) {
     std::fill_n (bands, BANDS * 2, 0.0f);
 
-    const float lastBin = static_cast<float> (this->m_binCount - 1);
+    const auto lastBin = static_cast<float> (this->m_binCount - 1);
 
     for (int c = 0; c < channels; c++) {
 	kiss_fft (this->m_config, this->m_input[c].data (), this->m_output.data ());
@@ -85,7 +88,7 @@ void SpectrumAnalyzer::analyze (int channels, float* bands) {
 		power = 0.0f;
 	    }
 
-	    const float x = static_cast<float> (bin - 1);
+	    const auto x = static_cast<float> (bin - 1);
 	    const float weight = TILT - std::cos (x * 3.1415927f / lastBin) * (1.0f - TILT);
 	    const float magnitude = std::sqrt (weight * power);
 	    const int target = static_cast<int> (std::pow (x / lastBin, BAND_EXPONENT) * 64.0f) % 64;
@@ -100,8 +103,8 @@ void SpectrumAnalyzer::analyze (int channels, float* bands) {
 	std::copy_n (bands, BANDS, bands + BANDS);
     }
 
-    const float scale
-	= GAIN * 0.001f * (static_cast<float> (this->m_binCount) / (static_cast<float> (this->m_size) * 0.5f));
+    const float scale = this->m_gain.load (std::memory_order_relaxed) * 0.001f
+	* (static_cast<float> (this->m_binCount) / (static_cast<float> (this->m_size) * 0.5f));
 
     for (int i = 0; i < BANDS * 2; i++) {
 	bands[i] *= scale;

+ 5 - 0
src/WallpaperEngine/Audio/SpectrumAnalyzer.h

@@ -1,5 +1,6 @@
 #pragma once
 
+#include <atomic>
 #include <cstddef>
 #include <vector>
 
@@ -24,6 +25,9 @@ public:
 
     void reset ();
 
+    /** WE's audioinputvolume, 50 is neutral; safe to call from another thread */
+    void setInputVolume (int volume);
+
     [[nodiscard]] int getFFTSize () const { return this->m_size; }
     [[nodiscard]] int getBlockSize () const { return this->m_blockSize; }
 
@@ -34,6 +38,7 @@ private:
     int m_blockSize;
     int m_binCount;
     int m_filled = 0;
+    std::atomic<float> m_gain { 1.0f };
     kiss_fft_cfg m_config;
     std::vector<kiss_fft_cpx> m_input[2];
     std::vector<kiss_fft_cpx> m_output;

+ 11 - 7
src/WallpaperEngine/Data/Builders/ColorBuilder.cpp

@@ -2,6 +2,7 @@
 #include "VectorBuilder.h"
 
 #include <algorithm>
+#include <cstdint>
 #include <glm/vec3.hpp>
 #include <iomanip>
 #include <sstream>
@@ -31,16 +32,18 @@ WallpaperEngine::Data::Builders::ColorBuilder::parse (const std::string& value,
 	} else if (number.size () == 4) {
 	    number = { number.at (0), number.at (0), number.at (1), number.at (1),
 		       number.at (2), number.at (2), number.at (3), number.at (3) };
-	} else if (number.size () != 6 && number.size () != 8) {
+	} else if (number.size () == 6) {
+	    std::ostringstream expanded;
+	    expanded << number << std::hex << std::setw (2) << std::setfill ('0') << static_cast<int> (alpha * 255);
+	    number = expanded.str ();
+	} else if (number.size () != 8) {
 	    sLog.exception ("Invalid CSS color notation for ", value);
 	}
 
-	const auto color = std::stoi (number, nullptr, 16);
+	const auto color = static_cast<std::uint32_t> (std::stoul (number, nullptr, 16));
 
-	return WallpaperEngine::Data::Model::Color (
-	    (color >> 24 & 0xFF) / 255.0f, (color >> 16 & 0xFF) / 255.0f, (color >> 8 & 0xFF) / 255.0f,
-	    (color & 0xFF) / 255.0f
-	);
+	return { static_cast<float> ((color >> 24 & 0xFF)) / 255.0f, static_cast<float> ((color >> 16 & 0xFF)) / 255.0f,
+		 static_cast<float> ((color >> 8 & 0xFF)) / 255.0f, static_cast<float> ((color & 0xFF)) / 255.0f };
     }
 
     int vectorSize = VectorBuilder::preparseSize (copy);
@@ -65,7 +68,8 @@ WallpaperEngine::Data::Builders::ColorBuilder::parse (const std::string& value,
 	const auto final = vectorSize == 3 ? glm::ivec4 (VectorBuilder::parse<glm::ivec3> (copy), alpha * 255)
 					   : VectorBuilder::parse<glm::ivec4> (copy);
 
-	return { final.r / 255.0f, final.g / 255.0f, final.b / 255.0f, final.a / 255.0f };
+	return { static_cast<float> (final.r) / 255.0f, static_cast<float> (final.g) / 255.0f,
+		 static_cast<float> (final.b) / 255.0f, static_cast<float> (final.a) / 255.0f };
     }
 
     return Model::Color (

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

@@ -7,7 +7,7 @@ namespace WallpaperEngine::Data::Builders {
 using namespace WallpaperEngine::Data::Model;
 class UserSettingBuilder {
 public:
-    template <typename T> static UserSettingUniquePtr fromValue (T defaultValue) {
+    template <typename T> static UserSettingUniquePtr fromValue (const T& defaultValue) {
 	DynamicValueUniquePtr value = std::make_unique<DynamicValue> (defaultValue);
 
 	return std::make_unique<UserSetting> (UserSetting {

+ 6 - 2
src/WallpaperEngine/Data/Builders/VectorBuilder.h

@@ -138,9 +138,13 @@ template <> inline uint64_t VectorBuilder::convert<uint64_t> (const char* str) {
     return std::strtoull (str, nullptr, 10);
 }
 
-template <> inline int8_t VectorBuilder::convert<int8_t> (const char* str) { return std::strtol (str, nullptr, 10); }
+template <> inline int8_t VectorBuilder::convert<int8_t> (const char* str) {
+    return static_cast<int8_t> (std::strtol (str, nullptr, 10));
+}
 
-template <> inline int16_t VectorBuilder::convert<int16_t> (const char* str) { return std::strtol (str, nullptr, 10); }
+template <> inline int16_t VectorBuilder::convert<int16_t> (const char* str) {
+    return static_cast<int16_t> (std::strtol (str, nullptr, 10));
+}
 
 template <> inline int64_t VectorBuilder::convert<int64_t> (const char* str) { return std::strtoll (str, nullptr, 10); }
 

+ 1 - 1
src/WallpaperEngine/Data/JSON.h

@@ -145,7 +145,7 @@ public:
     [[nodiscard]] UserSettingUniquePtr user (const std::string& key, const Properties& properties) const;
     template <typename T>
     [[nodiscard]] UserSettingUniquePtr
-    user (const std::string& key, const Properties& properties, T defaultValue) const {
+    user (const std::string& key, const Properties& properties, const T& defaultValue) const {
 	static_assert (std::is_same_v<T, Color> == false, "Use color() for color properties");
 	const auto value = this->optional (key);
 

+ 6 - 7
src/WallpaperEngine/Data/Model/DynamicValue.cpp

@@ -181,13 +181,17 @@ void DynamicValue::setBoolean (bool value) {
     this->m_type = UnderlyingType::Boolean;
 }
 
-void DynamicValue::update (const std::string& newValue, UpdateSource source) {
+void DynamicValue::clearNumbers () {
     this->m_vec2 = glm::vec2 (0.0f);
     this->m_vec3 = glm::vec3 (0.0f);
     this->m_vec4 = glm::vec4 (0.0f);
     this->m_float = 0.0f;
     this->m_int = 0;
     this->m_bool = false;
+}
+
+void DynamicValue::update (const std::string& newValue, UpdateSource source) {
+    this->clearNumbers ();
     this->m_string = newValue;
     this->m_type = UnderlyingType::String;
 
@@ -242,12 +246,7 @@ void DynamicValue::update (const DynamicValue& other, UpdateSource source) {
 }
 
 void DynamicValue::update (UpdateSource source) {
-    this->m_vec2 = glm::vec2 (0.0f);
-    this->m_vec3 = glm::vec3 (0.0f);
-    this->m_vec4 = glm::vec4 (0.0f);
-    this->m_float = 0.0f;
-    this->m_int = 0;
-    this->m_bool = false;
+    this->clearNumbers ();
     this->m_type = UnderlyingType::Null;
 
     this->propagate (source);

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

@@ -96,6 +96,7 @@ public:
 
 private:
     void propagate (UpdateSource source) const;
+    void clearNumbers ();
     void setBoolean (bool value);
 
     std::shared_ptr<bool> m_aliveFlag = std::make_shared<bool> (true);

+ 3 - 3
src/WallpaperEngine/Data/Model/Object.h

@@ -65,7 +65,7 @@ public:
 };
 
 struct ImageEffectPassOverride {
-    int id;
+    int id {};
     ComboMap combos;
     ShaderConstantMap constants;
     TextureMap textures;
@@ -220,7 +220,7 @@ struct ParticleEmitter {
 
 class ParticleInitializerBase : public TypeCaster {
 public:
-    virtual ~ParticleInitializerBase () = default;
+    ~ParticleInitializerBase () override = default;
 };
 
 class ColorRandomInitializer : public ParticleInitializerBase {
@@ -507,7 +507,7 @@ using ParticleInitializerUniquePtr = std::unique_ptr<ParticleInitializerBase>;
 
 class ParticleOperatorBase : public TypeCaster {
 public:
-    virtual ~ParticleOperatorBase () = default;
+    ~ParticleOperatorBase () override = default;
 };
 
 class MovementOperator : public ParticleOperatorBase {

+ 3 - 3
src/WallpaperEngine/Data/Parsers/DynamicValueParser.cpp

@@ -38,7 +38,7 @@ std::optional<glm::vec3> relativeAnimationBase (const json& value) {
 	return std::nullopt;
     }
 
-    const std::string& str = value.get_ref<const std::string&> ();
+    const auto& str = value.get_ref<const std::string&> ();
     const char* cursor = str.c_str ();
     glm::vec3 base;
 
@@ -47,7 +47,7 @@ std::optional<glm::vec3> relativeAnimationBase (const json& value) {
     }
 
     for (int component = 0; component < 2; component++) {
-	base[component] = static_cast<float> (std::atof (cursor));
+	base[component] = static_cast<float> (std::strtod (cursor, nullptr));
 
 	while (*cursor != '\0' && *cursor != ' ') {
 	    cursor++;
@@ -62,7 +62,7 @@ std::optional<glm::vec3> relativeAnimationBase (const json& value) {
 	}
     }
 
-    base[2] = static_cast<float> (std::atof (cursor));
+    base[2] = static_cast<float> (std::strtod (cursor, nullptr));
 
     return base;
 }

+ 1 - 1
src/WallpaperEngine/Data/Parsers/EffectParser.cpp

@@ -304,7 +304,7 @@ std::vector<FBOUniquePtr> EffectParser::parseFBOs (const JSON& it) {
 	    bool complete = text.empty ();
 
 	    for (int component = 0; !complete && component < 4; component++) {
-		fbo->clearColor[component] = static_cast<float> (std::atof (cursor));
+		fbo->clearColor[component] = static_cast<float> (std::strtod (cursor, nullptr));
 
 		if (component == 3) {
 		    complete = true;

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

@@ -40,7 +40,9 @@ std::vector<std::string> MaterialParser::textureNames (const Project& project, c
 		names.push_back (texture);
 	    }
 	}
-    } catch (const std::exception&) { }
+    } catch (const std::exception& e) {
+	sLog.debug ("Cannot list the textures of ", filename, ": ", e.what ());
+    }
 
     return names;
 }

+ 9 - 9
src/WallpaperEngine/Data/Parsers/ObjectParser.cpp

@@ -55,10 +55,10 @@ glm::vec3 vec3Field (const JSON& it, const char* fieldName, const glm::vec3& def
     }
     if (fieldIt->is_number ()) {
 	float val = fieldIt->get<float> ();
-	return glm::vec3 (val, val, val);
+	return { val, val, val };
     }
     if (fieldIt->is_array () && fieldIt->size () >= 3) {
-	return glm::vec3 ((*fieldIt)[0].get<float> (), (*fieldIt)[1].get<float> (), (*fieldIt)[2].get<float> ());
+	return { (*fieldIt)[0].get<float> (), (*fieldIt)[1].get<float> (), (*fieldIt)[2].get<float> () };
     }
     return defaultValue;
 }
@@ -83,7 +83,7 @@ glm::vec3 parseFloats (const std::string& text) {
     glm::vec3 result (0.0f);
     const char* cursor = text.c_str ();
     for (int i = 0; i < 3; i++) {
-	result[i] = static_cast<float> (std::atof (cursor));
+	result[i] = static_cast<float> (std::strtod (cursor, nullptr));
 	while (*cursor != '\0' && *cursor != ' ') {
 	    cursor++;
 	}
@@ -126,7 +126,7 @@ rotationBound (const JSON& it, const std::string& key, const Properties& propert
 
 template <typename T, size_t N>
 T parseName (const JSON& it, const std::string& key, const char* fallback, const char* const (&names)[N], T unknown) {
-    const std::string name = it.optional<std::string> (key, fallback);
+    const auto name = it.optional<std::string> (key, fallback);
     for (size_t i = 0; i < N; i++) {
 	if (name == names[i]) {
 	    return static_cast<T> (i);
@@ -1254,7 +1254,7 @@ ParticleEmitter ObjectParser::parseParticleEmitter (const JSON& it) {
 	    return it.optional (fieldName, defaultValue);
 	}
 	if (fieldIt->is_array () && fieldIt->size () >= 2) {
-	    return glm::vec2 ((*fieldIt)[0].get<float> (), (*fieldIt)[1].get<float> ());
+	    return { (*fieldIt)[0].get<float> (), (*fieldIt)[1].get<float> () };
 	}
 	return defaultValue;
     };
@@ -1304,7 +1304,7 @@ ParticleEmitter ObjectParser::parseParticleEmitter (const JSON& it) {
 }
 
 ParticleInitializerUniquePtr ObjectParser::parseParticleInitializer (const JSON& it, const Properties& properties) {
-    std::string name = it.optional<std::string> ("name", "");
+    auto name = it.optional<std::string> ("name", "");
 
     if (name == "colorrandom") {
 	// read as plain numbers, CParticle divides them by 255 like sub_1401C5490 does ("1 1 1" is nearly black)
@@ -1417,7 +1417,7 @@ ParticleInitializerUniquePtr ObjectParser::parseParticleInitializer (const JSON&
 }
 
 ParticleOperatorUniquePtr ObjectParser::parseParticleOperator (const JSON& it, const Properties& properties) {
-    std::string name = it.optional<std::string> ("name", "");
+    auto name = it.optional<std::string> ("name", "");
 
     if (name == "movement") {
 	return std::make_unique<MovementOperator> (
@@ -1562,7 +1562,7 @@ ParticleOperatorUniquePtr ObjectParser::parseParticleOperator (const JSON& it, c
 
 	// sub_1401C03F0: anything but slide, stop or delete bounces
 	ParticleCollisionBehavior behavior = ParticleCollisionBehavior::Bounce;
-	const std::string behaviorName = it.optional<std::string> ("collisionbehavior", "bounce");
+	const auto behaviorName = it.optional<std::string> ("collisionbehavior", "bounce");
 	for (size_t i = 0; i < std::size (behaviors); i++) {
 	    if (behaviorName == behaviors[i]) {
 		behavior = static_cast<ParticleCollisionBehavior> (i);
@@ -1594,7 +1594,7 @@ ParticleRenderer ObjectParser::parseParticleRenderer (const JSON& it) {
 
     // sub_1401C22E0, read for every renderer type: "orientation" defaults to "screen", anything but "upright" and
     // "fixed" is screen too; "axis" "0 0 0" becomes y up
-    const std::string orientation = it.optional<std::string> ("orientation", "screen");
+    const auto orientation = it.optional<std::string> ("orientation", "screen");
     const auto axisIt = it.find ("axis");
     glm::vec3 axis
 	= axisIt != it.end () && axisIt->is_string () ? parseFloats (axisIt->get<std::string> ()) : glm::vec3 (0.0f);

+ 3 - 1
src/WallpaperEngine/Data/Parsers/TextureParser.cpp

@@ -29,7 +29,9 @@ TextureUniquePtr TextureParser::parse (const BinaryReader& file) {
 
     while (file.base ().peek () != std::char_traits<char>::eof ()) {
 	const std::string tag = file.nextNullTerminatedString ();
-	const uint32_t version = tag.size () > 4 ? static_cast<uint32_t> (std::atoi (tag.c_str () + 4)) : 0;
+	const uint32_t version = tag.size () > 4
+	    ? static_cast<uint32_t> (static_cast<int> (std::strtol (tag.c_str () + 4, nullptr, 10)))
+	    : 0;
 
 	if (tag.starts_with ("TEXI")) {
 	    parseTextureHeader (*result, file, version);

+ 98 - 0
src/WallpaperEngine/Data/Utils/DecimalNumber.h

@@ -0,0 +1,98 @@
+#pragma once
+
+#include <algorithm>
+#include <cctype>
+#include <charconv>
+#include <cmath>
+#include <limits>
+#include <string_view>
+#include <system_error>
+
+namespace WallpaperEngine::Data::Utils {
+/** Reads a decimal number at position: an optional sign, digits with an optional fraction and an optional exponent.
+ * No blanks, no hex, no "inf" or "nan", and no locale. A number too big or too small for a double comes out as
+ * +-Infinity or 0, judged by its decimal magnitude. Moves position past what it read, false (and position untouched)
+ * when there is no number */
+inline bool readDecimalNumber (const char*& position, double& number) {
+    const char* cursor = position;
+    const bool negative = *cursor == '-';
+
+    if (*cursor == '+' || *cursor == '-') {
+	cursor++;
+    }
+
+    const char* start = cursor;
+    // decimal exponent of the first non zero digit, counted as in scientific notation
+    long magnitude = 0;
+    bool seenDigit = false;
+    long integerDigits = 0;
+    long leadingZeros = 0;
+
+    for (; std::isdigit (static_cast<unsigned char> (*cursor)); cursor++) {
+	if (*cursor != '0' || seenDigit) {
+	    seenDigit = true;
+	    integerDigits++;
+	}
+    }
+
+    bool any = cursor != start;
+
+    if (*cursor == '.') {
+	const char* fraction = ++cursor;
+
+	for (; std::isdigit (static_cast<unsigned char> (*cursor)); cursor++) {
+	    if (*cursor == '0' && !seenDigit) {
+		leadingZeros++;
+	    } else {
+		seenDigit = true;
+	    }
+	}
+
+	any = any || cursor != fraction;
+    }
+
+    if (!any) {
+	return false;
+    }
+
+    magnitude = integerDigits > 0 ? integerDigits - 1 : -(leadingZeros + 1);
+
+    if (*cursor == 'e' || *cursor == 'E') {
+	const char* exponent = cursor + 1;
+	const bool negativeExponent = *exponent == '-';
+
+	if (*exponent == '+' || *exponent == '-') {
+	    exponent++;
+	}
+
+	if (std::isdigit (static_cast<unsigned char> (*exponent))) {
+	    long value = 0;
+
+	    for (; std::isdigit (static_cast<unsigned char> (*exponent)); exponent++) {
+		// far past any double, the digits after it change nothing
+		value = std::min (value * 10 + (*exponent - '0'), 100000L);
+	    }
+
+	    magnitude += negativeExponent ? -value : value;
+	    cursor = exponent;
+	}
+    }
+
+    // from_chars takes no leading '+'
+    const char* begin = *position == '+' ? position + 1 : position;
+    double value = 0.0;
+    const auto result = std::from_chars (begin, cursor, value);
+
+    if (result.ec == std::errc::result_out_of_range) {
+	value = seenDigit && magnitude > 0 ? std::numeric_limits<double>::infinity () : 0.0;
+	value = negative ? -value : value;
+    } else if (result.ec != std::errc ()) {
+	return false;
+    }
+
+    number = value;
+    position = cursor;
+
+    return true;
+}
+}

+ 1 - 1
src/WallpaperEngine/Data/Utils/ScopeGuard.h

@@ -7,7 +7,7 @@ template <typename F> struct ScopeGuard {
     ScopeGuard& operator= (const ScopeGuard& other) = delete;
 
     explicit ScopeGuard (F&& f) : func (std::forward<F> (f)), owner (true) { }
-    explicit ScopeGuard (ScopeGuard&& other) noexcept : func (std::move (other.func)), owner (other.owner) {
+    ScopeGuard (ScopeGuard&& other) noexcept : func (std::move (other.func)), owner (other.owner) {
 	other.owner = false;
     }
     ~ScopeGuard () { this->execute (); }

+ 9 - 11
src/WallpaperEngine/Debugging/CallStack.cpp

@@ -63,9 +63,7 @@ using namespace std;
 const char* CallStack::Unknown_Function = "[unknown function]";
 const char* CallStack::Unknown_Module = "[unknown module]";
 
-CallStack::CallStack (void) { }
-
-CallStack::~CallStack (void) { }
+CallStack::CallStack () = default;
 
 string CallStack::Demangle (const char* name) {
 #if defined(_MSC_VER)
@@ -73,7 +71,7 @@ string CallStack::Demangle (const char* name) {
 #else
     string dname;
     int status = 0;
-    char* pdname = abi::__cxa_demangle (name, NULL, 0, &status);
+    char* pdname = abi::__cxa_demangle (name, nullptr, nullptr, &status);
     if (status == 0) {
 	dname.assign (pdname);
 	free (pdname);
@@ -280,7 +278,7 @@ void CallStack::GetCalls (vector<CallStack::CallInfo>& calls) {
     const int ncalls = backtrace (buffer, sizeof (buffer));
     char** callstrings = backtrace_symbols (buffer, ncalls);
 
-    if (callstrings == NULL) {
+    if (callstrings == nullptr) {
 	fprintf (stderr, "Error: Failed to obtain the symbol table from the executable.\n");
 	return;
     }
@@ -288,18 +286,18 @@ void CallStack::GetCalls (vector<CallStack::CallInfo>& calls) {
     calls.clear ();
     for (int i = 0; i < ncalls; ++i) {
 	const string funinfo (callstrings[i]);
-	const int posleftparenthesis = funinfo.rfind ('(');
-	const int posplus = funinfo.rfind ('+');
-	const int posleftbracket = funinfo.rfind ('[');
-	const int posrightbracket = funinfo.rfind (']');
+	const int posleftparenthesis = static_cast<int> (funinfo.rfind ('('));
+	const int posplus = static_cast<int> (funinfo.rfind ('+'));
+	const int posleftbracket = static_cast<int> (funinfo.rfind ('['));
+	const int posrightbracket = static_cast<int> (funinfo.rfind (']'));
 
 	long long unsigned int offset
-	    = strtoull (funinfo.substr (posleftbracket + 1, posrightbracket - posleftbracket - 1).c_str (), NULL, 0);
+	    = strtoull (funinfo.substr (posleftbracket + 1, posrightbracket - posleftbracket - 1).c_str (), nullptr, 0);
 	const string module_name = funinfo.substr (0, posleftparenthesis);
 	const string function
 	    = Demangle (funinfo.substr (posleftparenthesis + 1, posplus - posleftparenthesis - 1).c_str ());
 
-	calls.push_back (CallInfo (offset, function, module_name));
+	calls.emplace_back (offset, function, module_name);
     }
     free (callstrings);
 

+ 9 - 8
src/WallpaperEngine/Debugging/CallStack.h

@@ -37,10 +37,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 // mailto: zhangjunqcc@gmail.com
 //
 
-#ifndef __CALLSTACK_H__
-#define __CALLSTACK_H__
+#ifndef LWE_CALLSTACK_H
+#define LWE_CALLSTACK_H
 
 #include <string>
+#include <utility>
 #include <vector>
 
 namespace WallpaperEngine::Debugging {
@@ -49,18 +50,18 @@ using namespace std;
 
 class CallStack {
 public:
-    CallStack (void);
-    ~CallStack (void);
+    CallStack ();
+    ~CallStack () = default;
 
     static const char* Unknown_Function;
     static const char* Unknown_Module;
 
     class CallInfo {
     public:
-	CallInfo (void) : offset (0) { }
-	CallInfo (long long unsigned int toffset, const string& tfunction, const string& tmodule) :
-	    offset (toffset), function (tfunction), module (tmodule) { }
-	~CallInfo (void) { }
+	CallInfo () : offset (0) { }
+	CallInfo (long long unsigned int toffset, string tfunction, string tmodule) :
+	    offset (toffset), function (std::move (tfunction)), module (std::move (tmodule)) { }
+	~CallInfo () = default;
 	long unsigned int offset = 0;
 	string function;
 	string module;

+ 95 - 0
src/WallpaperEngine/Desktop/DlopenX11.h

@@ -0,0 +1,95 @@
+#pragma once
+
+#include <cstdlib>
+#include <dlfcn.h>
+
+namespace WallpaperEngine::Desktop {
+/** libX11 and one of its extension libraries through dlopen, none of them is a build dependency */
+class DlopenX11 {
+public:
+    DlopenX11 () = default;
+
+    ~DlopenX11 () {
+	if (this->m_display != nullptr) {
+	    this->m_closeDisplay (this->m_display);
+	}
+
+	this->unload ();
+    }
+
+    DlopenX11 (const DlopenX11&) = delete;
+    DlopenX11& operator= (const DlopenX11&) = delete;
+
+    /** Loads both libraries, false when any of it is missing */
+    bool load (const char* extensionLibrary) {
+	if (this->m_x11 != nullptr && this->m_extension != nullptr) {
+	    return true;
+	}
+
+	this->unload ();
+
+	if (std::getenv ("DISPLAY") == nullptr) {
+	    return false;
+	}
+
+	this->m_x11 = dlopen ("libX11.so.6", RTLD_NOW | RTLD_LOCAL);
+	this->m_extension = dlopen (extensionLibrary, RTLD_NOW | RTLD_LOCAL);
+
+	if (this->m_x11 == nullptr || this->m_extension == nullptr) {
+	    this->unload ();
+	    return false;
+	}
+
+	this->m_openDisplay = this->x11Symbol<void* (*)(const char*)> ("XOpenDisplay");
+	this->m_closeDisplay = this->x11Symbol<int (*) (void*)> ("XCloseDisplay");
+
+	if (this->m_openDisplay == nullptr || this->m_closeDisplay == nullptr) {
+	    this->unload ();
+	    return false;
+	}
+
+	return true;
+    }
+
+    /** Opens the display, once the caller found every symbol it needs */
+    bool connect () {
+	if (this->m_display == nullptr && this->m_openDisplay != nullptr) {
+	    this->m_display = this->m_openDisplay (nullptr);
+	}
+
+	return this->m_display != nullptr;
+    }
+
+    [[nodiscard]] void* display () const { return this->m_display; }
+
+    template <typename Function> Function x11Symbol (const char* name) const {
+	return reinterpret_cast<Function> (dlsym (this->m_x11, name));
+    }
+
+    template <typename Function> Function extensionSymbol (const char* name) const {
+	return reinterpret_cast<Function> (dlsym (this->m_extension, name));
+    }
+
+private:
+    void unload () {
+	if (this->m_extension != nullptr) {
+	    dlclose (this->m_extension);
+	    this->m_extension = nullptr;
+	}
+
+	if (this->m_x11 != nullptr) {
+	    dlclose (this->m_x11);
+	    this->m_x11 = nullptr;
+	}
+
+	this->m_openDisplay = nullptr;
+	this->m_closeDisplay = nullptr;
+    }
+
+    void* m_x11 = nullptr;
+    void* m_extension = nullptr;
+    void* m_display = nullptr;
+    void* (*m_openDisplay) (const char*) = nullptr;
+    int (*m_closeDisplay) (void*) = nullptr;
+};
+}

+ 2 - 2
src/WallpaperEngine/Desktop/HostWayland.cpp

@@ -66,6 +66,7 @@ std::string hostHelperPath () {
 bool spawnDetached (const std::vector<std::string>& arguments) {
     // built before fork, the children of a threaded process must not allocate
     std::vector<char*> argv;
+    argv.reserve (arguments.size ());
     for (const auto& argument : arguments) {
 	argv.push_back (const_cast<char*> (argument.c_str ()));
     }
@@ -133,11 +134,10 @@ int hostConnection () {
 		close (connection);
 	    }
 	}
-    }
 
-    if (listener >= 0) {
 	close (listener);
     }
+
     unlink (path.c_str ());
 
     if (fd < 0) {

+ 24 - 24
src/WallpaperEngine/Desktop/IconTheme.cpp

@@ -15,27 +15,6 @@ std::filesystem::path homeDir () {
     return home != nullptr ? home : "";
 }
 
-std::vector<std::filesystem::path> dataDirs () {
-    std::vector<std::filesystem::path> result;
-    const char* dataHome = std::getenv ("XDG_DATA_HOME");
-    const char* dirs = std::getenv ("XDG_DATA_DIRS");
-
-    result.emplace_back (
-	dataHome != nullptr && *dataHome ? std::filesystem::path (dataHome) : homeDir () / ".local/share"
-    );
-
-    std::stringstream stream (dirs != nullptr && *dirs ? dirs : "/usr/local/share:/usr/share");
-    std::string dir;
-
-    while (std::getline (stream, dir, ':')) {
-	if (!dir.empty ()) {
-	    result.emplace_back (dir);
-	}
-    }
-
-    return result;
-}
-
 std::optional<std::string>
 iniValue (const std::filesystem::path& file, const std::string& section, const std::string& key) {
     std::ifstream stream (file);
@@ -81,7 +60,7 @@ int score (const std::filesystem::path& path) {
 	    const std::string name = part.string ();
 
 	    if (!name.empty () && std::isdigit (static_cast<unsigned char> (name.front ()))) {
-		size = std::max (size, std::atoi (name.c_str ()));
+		size = std::max (size, static_cast<int> (std::strtol (name.c_str (), nullptr, 10)));
 	    }
 	}
     }
@@ -93,6 +72,27 @@ int score (const std::filesystem::path& path) {
 }
 }
 
+std::vector<std::filesystem::path> WallpaperEngine::Desktop::dataDirectories () {
+    std::vector<std::filesystem::path> result;
+    const char* dataHome = std::getenv ("XDG_DATA_HOME");
+    const char* dirs = std::getenv ("XDG_DATA_DIRS");
+
+    result.emplace_back (
+	dataHome != nullptr && *dataHome ? std::filesystem::path (dataHome) : homeDir () / ".local/share"
+    );
+
+    std::stringstream stream (dirs != nullptr && *dirs ? dirs : "/usr/local/share:/usr/share");
+    std::string dir;
+
+    while (std::getline (stream, dir, ':')) {
+	if (!dir.empty ()) {
+	    result.emplace_back (dir);
+	}
+    }
+
+    return result;
+}
+
 IconTheme& IconTheme::get () {
     static IconTheme instance;
     return instance;
@@ -101,7 +101,7 @@ IconTheme& IconTheme::get () {
 IconTheme::IconTheme () {
     const auto home = homeDir ();
 
-    for (const auto& dir : dataDirs ()) {
+    for (const auto& dir : dataDirectories ()) {
 	this->m_baseDirs.push_back (dir / "icons");
     }
 
@@ -217,7 +217,7 @@ std::optional<std::filesystem::path> IconTheme::find (const std::string& icon) {
     }
 
     for (const auto& extension : { ".svg", ".png" }) {
-	const auto path = std::filesystem::path ("/usr/share/pixmaps") / (icon + extension);
+	auto path = std::filesystem::path ("/usr/share/pixmaps") / (icon + extension);
 
 	if (std::filesystem::is_regular_file (path, error)) {
 	    return path;

+ 3 - 0
src/WallpaperEngine/Desktop/IconTheme.h

@@ -7,6 +7,9 @@
 #include <vector>
 
 namespace WallpaperEngine::Desktop {
+/** XDG_DATA_HOME, then each of XDG_DATA_DIRS, with the defaults of the spec */
+std::vector<std::filesystem::path> dataDirectories ();
+
 class IconTheme {
 public:
     static IconTheme& get ();

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

@@ -16,8 +16,6 @@
 #include <sys/file.h>
 #include <unistd.h>
 
-extern char** environ;
-
 using namespace WallpaperEngine::Desktop;
 
 namespace {

+ 16 - 43
src/WallpaperEngine/Desktop/PowerMonitor.cpp

@@ -6,13 +6,13 @@
 #include <cstdlib>
 #include <cstring>
 #include <dbus/dbus.h>
-#include <dlfcn.h>
 #include <fstream>
 #include <poll.h>
 #include <string>
 #include <sys/eventfd.h>
 #include <unistd.h>
 
+#include "WallpaperEngine/Desktop/DlopenX11.h"
 #include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Logging/ThreadGuard.h"
@@ -53,59 +53,33 @@ public:
 	if (this->m_info != nullptr) {
 	    this->m_free (this->m_info);
 	}
-
-	if (this->m_display != nullptr) {
-	    this->m_closeDisplay (this->m_display);
-	}
-
-	if (this->m_xss != nullptr) {
-	    dlclose (this->m_xss);
-	}
-
-	if (this->m_x11 != nullptr) {
-	    dlclose (this->m_x11);
-	}
     }
 
     bool open () {
-	if (std::getenv ("DISPLAY") == nullptr) {
+	if (!this->m_x.load ("libXss.so.1")) {
 	    return false;
 	}
 
-	this->m_x11 = dlopen ("libX11.so.6", RTLD_NOW | RTLD_LOCAL);
-	this->m_xss = dlopen ("libXss.so.1", RTLD_NOW | RTLD_LOCAL);
+	this->m_free = this->m_x.x11Symbol<int (*) (void*)> ("XFree");
+	this->m_rootWindow = this->m_x.x11Symbol<unsigned long (*) (void*)> ("XDefaultRootWindow");
+	auto queryExtension = this->m_x.extensionSymbol<int (*) (void*, int*, int*)> ("XScreenSaverQueryExtension");
+	auto allocInfo = this->m_x.extensionSymbol<ScreenSaverInfo* (*)()> ("XScreenSaverAllocInfo");
+	this->m_query
+	    = this->m_x.extensionSymbol<int (*) (void*, unsigned long, ScreenSaverInfo*)> ("XScreenSaverQueryInfo");
 
-	if (this->m_x11 == nullptr || this->m_xss == nullptr) {
+	if (this->m_free == nullptr || this->m_rootWindow == nullptr || queryExtension == nullptr
+	    || allocInfo == nullptr || this->m_query == nullptr) {
 	    return false;
 	}
 
-	auto openDisplay = reinterpret_cast<void* (*)(const char*)> (dlsym (this->m_x11, "XOpenDisplay"));
-	this->m_closeDisplay = reinterpret_cast<int (*) (void*)> (dlsym (this->m_x11, "XCloseDisplay"));
-	this->m_free = reinterpret_cast<int (*) (void*)> (dlsym (this->m_x11, "XFree"));
-	this->m_rootWindow = reinterpret_cast<unsigned long (*) (void*)> (dlsym (this->m_x11, "XDefaultRootWindow"));
-	auto queryExtension
-	    = reinterpret_cast<int (*) (void*, int*, int*)> (dlsym (this->m_xss, "XScreenSaverQueryExtension"));
-	auto allocInfo = reinterpret_cast<ScreenSaverInfo* (*)()> (dlsym (this->m_xss, "XScreenSaverAllocInfo"));
-	this->m_query = reinterpret_cast<int (*) (void*, unsigned long, ScreenSaverInfo*)> (
-	    dlsym (this->m_xss, "XScreenSaverQueryInfo")
-	);
-
-	if (openDisplay == nullptr || this->m_closeDisplay == nullptr || this->m_free == nullptr
-	    || this->m_rootWindow == nullptr || queryExtension == nullptr || allocInfo == nullptr
-	    || this->m_query == nullptr) {
-	    return false;
-	}
-
-	this->m_display = openDisplay (nullptr);
-
-	if (this->m_display == nullptr) {
+	if (!this->m_x.connect ()) {
 	    return false;
 	}
 
 	int eventBase = 0;
 	int errorBase = 0;
 
-	if (!queryExtension (this->m_display, &eventBase, &errorBase)) {
+	if (!queryExtension (this->m_x.display (), &eventBase, &errorBase)) {
 	    return false;
 	}
 
@@ -114,7 +88,9 @@ public:
     }
 
     std::optional<uint64_t> idleMilliseconds () {
-	if (!this->m_query (this->m_display, this->m_rootWindow (this->m_display), this->m_info)) {
+	void* display = this->m_x.display ();
+
+	if (!this->m_query (display, this->m_rootWindow (display), this->m_info)) {
 	    return std::nullopt;
 	}
 
@@ -122,11 +98,8 @@ public:
     }
 
 private:
-    void* m_x11 = nullptr;
-    void* m_xss = nullptr;
-    void* m_display = nullptr;
+    DlopenX11 m_x;
     ScreenSaverInfo* m_info = nullptr;
-    int (*m_closeDisplay) (void*) = nullptr;
     int (*m_free) (void*) = nullptr;
     unsigned long (*m_rootWindow) (void*) = nullptr;
     int (*m_query) (void*, unsigned long, ScreenSaverInfo*) = nullptr;

+ 13 - 41
src/WallpaperEngine/Desktop/SessionMonitor.cpp

@@ -6,7 +6,6 @@
 #include <cstdint>
 #include <cstdlib>
 #include <cstring>
-#include <dlfcn.h>
 #include <memory>
 #include <optional>
 #include <poll.h>
@@ -17,6 +16,7 @@
 #include <tuple>
 #include <unistd.h>
 
+#include "WallpaperEngine/Desktop/DlopenX11.h"
 #include "WallpaperEngine/Desktop/HyprlandIPC.h"
 #include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
@@ -57,52 +57,27 @@ constexpr std::array SCREEN_SAVERS = {
 // 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) {
+	if (!this->m_x.load ("libXext.so.6")) {
 	    return false;
 	}
 
-	this->m_x11 = dlopen ("libX11.so.6", RTLD_NOW | RTLD_LOCAL);
-	this->m_xext = dlopen ("libXext.so.6", RTLD_NOW | RTLD_LOCAL);
+	auto queryExtension = this->m_x.extensionSymbol<int (*) (void*, int*, int*)> ("DPMSQueryExtension");
+	auto capable = this->m_x.extensionSymbol<int (*) (void*)> ("DPMSCapable");
+	this->m_info = this->m_x.extensionSymbol<int (*) (void*, unsigned short*, unsigned char*)> ("DPMSInfo");
 
-	if (this->m_x11 == nullptr || this->m_xext == nullptr) {
+	if (queryExtension == nullptr || capable == nullptr || this->m_info == 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) {
+	if (!this->m_x.connect ()) {
 	    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);
+	return queryExtension (this->m_x.display (), &eventBase, &errorBase) && capable (this->m_x.display ());
     }
 
     /** DPMS off, standby and suspend all mean a blank screen. Nothing when DPMS is not enabled on the server */
@@ -110,7 +85,7 @@ public:
 	unsigned short level = 0;
 	unsigned char enabled = 0;
 
-	if (!this->m_info (this->m_display, &level, &enabled)) {
+	if (!this->m_info (this->m_x.display (), &level, &enabled)) {
 	    return std::nullopt;
 	}
 
@@ -118,10 +93,7 @@ public:
     }
 
 private:
-    void* m_x11 = nullptr;
-    void* m_xext = nullptr;
-    void* m_display = nullptr;
-    int (*m_closeDisplay) (void*) = nullptr;
+    DlopenX11 m_x;
     int (*m_info) (void*, unsigned short*, unsigned char*) = nullptr;
 };
 
@@ -321,7 +293,7 @@ public:
 	return nullptr;
     }
 
-    std::optional<bool> blanked () const {
+    [[nodiscard]] std::optional<bool> blanked () const {
 	const auto reply
 	    = this->m_kind == Kind::Sway ? this->swayOutputs () : hyprlandRequest (this->m_path, "j/monitors");
 
@@ -376,7 +348,7 @@ private:
 
     OutputPower (const Kind kind, std::string path) : m_kind (kind), m_path (std::move (path)) { }
 
-    std::optional<std::string> swayOutputs () const {
+    [[nodiscard]] std::optional<std::string> swayOutputs () const {
 	const int fd = connectUnixSocket (this->m_path, 100000);
 
 	if (fd < 0) {
@@ -501,7 +473,7 @@ std::string logindSessionPath (DBusConnection* bus) {
     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 ());
+    const auto 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 ()) {

+ 4 - 17
src/WallpaperEngine/Desktop/UserShortcut.cpp

@@ -19,8 +19,6 @@
 #include "WallpaperEngine/Logging/Log.h"
 #include "nlohmann/json.hpp"
 
-extern char** environ;
-
 using namespace WallpaperEngine::Desktop;
 
 namespace {
@@ -45,22 +43,10 @@ std::filesystem::path configHome () {
 }
 
 std::vector<std::filesystem::path> applicationDirs () {
-    std::vector<std::filesystem::path> result;
-    const char* dataHome = std::getenv ("XDG_DATA_HOME");
-    const char* dirs = std::getenv ("XDG_DATA_DIRS");
-
-    result.push_back (
-	(dataHome != nullptr && *dataHome ? std::filesystem::path (dataHome) : homeDir () / ".local/share")
-	/ "applications"
-    );
+    auto result = dataDirectories ();
 
-    std::stringstream stream (dirs != nullptr && *dirs ? dirs : "/usr/local/share:/usr/share");
-    std::string dir;
-
-    while (std::getline (stream, dir, ':')) {
-	if (!dir.empty ()) {
-	    result.push_back (std::filesystem::path (dir) / "applications");
-	}
+    for (auto& dir : result) {
+	dir /= "applications";
     }
 
     return result;
@@ -264,6 +250,7 @@ bool spawnDetached (std::vector<std::string> arguments, const std::string& worki
     }
 
     std::vector<char*> argv;
+    argv.reserve (arguments.size ());
     for (const auto& argument : arguments) {
 	argv.push_back (const_cast<char*> (argument.c_str ()));
     }

+ 1 - 1
src/WallpaperEngine/Desktop/UserShortcut.h

@@ -15,7 +15,7 @@ struct UserShortcut {
     std::string target;
     std::string arguments;
 
-    [[nodiscard]] static std::optional<UserShortcut> parse (const std::string& value);
+    [[nodiscard]] static std::optional<UserShortcut> parse (const std::string& raw);
 
     [[nodiscard]] std::optional<std::filesystem::path> iconPath () const;
 

+ 28 - 25
src/WallpaperEngine/FileSystem/Adapters/Directory.cpp

@@ -59,21 +59,38 @@ static std::filesystem::path resolveCase (const std::filesystem::path& base, con
     return current;
 }
 
-ReadStreamSharedPtr DirectoryAdapter::open (const std::filesystem::path& path) const {
-    auto finalpath = std::filesystem::canonical (resolveCase (this->basepath, path));
+namespace {
+enum class Lookup { Found, Missing, NotAFile };
 
-    if (!isInside (this->basepath, finalpath)) {
-	throw std::filesystem::filesystem_error ("Cannot find file", path, std::error_code ());
+// canonical throws for a path that does not exist
+Lookup
+findRegularFile (const std::filesystem::path& base, const std::filesystem::path& path, std::filesystem::path& found) {
+    found = std::filesystem::canonical (resolveCase (base, path));
+
+    if (!isInside (base, found)) {
+	return Lookup::Missing;
     }
 
-    const auto status = std::filesystem::status (finalpath);
+    const auto status = std::filesystem::status (found);
 
-    if (!std::filesystem::exists (finalpath)) {
-	throw std::filesystem::filesystem_error ("Cannot find file", path, std::error_code ());
+    if (!std::filesystem::exists (found)) {
+	return Lookup::Missing;
     }
 
-    if (!std::filesystem::is_regular_file (status)) {
-	throw std::filesystem::filesystem_error ("Expected file but found a directory", path, std::error_code ());
+    return std::filesystem::is_regular_file (status) ? Lookup::Found : Lookup::NotAFile;
+}
+}
+
+ReadStreamSharedPtr DirectoryAdapter::open (const std::filesystem::path& path) const {
+    std::filesystem::path finalpath;
+
+    switch (findRegularFile (this->basepath, path, finalpath)) {
+	case Lookup::Missing:
+	    throw std::filesystem::filesystem_error ("Cannot find file", path, std::error_code ());
+	case Lookup::NotAFile:
+	    throw std::filesystem::filesystem_error ("Expected file but found a directory", path, std::error_code ());
+	case Lookup::Found:
+	    break;
     }
 
     return std::make_shared<std::ifstream> (finalpath);
@@ -81,23 +98,9 @@ ReadStreamSharedPtr DirectoryAdapter::open (const std::filesystem::path& path) c
 
 bool DirectoryAdapter::exists (const std::filesystem::path& path) const {
     try {
-	const auto finalpath = std::filesystem::canonical (resolveCase (this->basepath, path));
-
-	if (!isInside (this->basepath, finalpath)) {
-	    return false;
-	}
-
-	const auto status = std::filesystem::status (finalpath);
-
-	if (!std::filesystem::exists (finalpath)) {
-	    return false;
-	}
-
-	if (!std::filesystem::is_regular_file (status)) {
-	    return false;
-	}
+	std::filesystem::path finalpath;
 
-	return true;
+	return findRegularFile (this->basepath, path, finalpath) == Lookup::Found;
     } catch (std::filesystem::filesystem_error&) {
 	return false;
     }

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

@@ -10,7 +10,7 @@ class MediaSource;
 }
 namespace WallpaperEngine::FileSystem::Adapters {
 struct MediaCoverFactory final : Factory {
-    MediaCoverFactory (Media::MediaSource& source) : source (source) { }
+    explicit MediaCoverFactory (Media::MediaSource& source) : source (source) { }
 
     [[nodiscard]] bool handlesMountpoint (const std::filesystem::path& path) const override;
     [[nodiscard]] AdapterSharedPtr create (const std::filesystem::path& path) const override;

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

@@ -59,7 +59,9 @@ inline std::optional<std::string> resolveShortNameAlias (std::vector<std::string
 
     if (tilde == std::string::npos || tilde == 0 || stem.size () > 8 || extension.size () > 3
 	|| tilde + 1 == stem.size ()
-	|| !std::all_of (stem.begin () + tilde + 1, stem.end (), [] (unsigned char c) { return std::isdigit (c); })) {
+	|| !std::all_of (stem.begin () + static_cast<long> (tilde) + 1, stem.end (), [] (unsigned char c) {
+	       return std::isdigit (c);
+	   })) {
 	return std::nullopt;
     }
 

+ 2 - 2
src/WallpaperEngine/FileSystem/Container.h

@@ -23,7 +23,7 @@ public:
 
     AdapterSharedPtr mount (const std::filesystem::path& path, const std::filesystem::path& mountPoint);
 
-    VirtualAdapter& getVFS () const;
+    [[nodiscard]] VirtualAdapter& getVFS () const;
 
     void registerAdapterFactory (FactoryUniquePtr factory);
 
@@ -34,7 +34,7 @@ public:
     [[nodiscard]] std::optional<std::filesystem::path> resolveShortNameAlias (const std::filesystem::path& path) const;
 
 private:
-    Adapter& resolveAdapterForFile (const std::filesystem::path& path) const;
+    [[nodiscard]] Adapter& resolveAdapterForFile (const std::filesystem::path& path) const;
     std::vector<FactoryUniquePtr> m_factories;
     std::vector<std::pair<std::filesystem::path, AdapterSharedPtr>> m_mountpoints;
     std::shared_ptr<VirtualAdapter> m_vfs;

+ 19 - 0
src/WallpaperEngine/FileSystem/StateDirectory.h

@@ -0,0 +1,19 @@
+#pragma once
+
+#include <cstdlib>
+#include <filesystem>
+
+namespace WallpaperEngine::FileSystem {
+/** $XDG_STATE_HOME/linux-wallpaperengine, else ~/.local/state/linux-wallpaperengine, empty when neither is known */
+inline std::filesystem::path stateRoot () {
+    if (const char* state = std::getenv ("XDG_STATE_HOME"); state != nullptr && state[0] == '/') {
+	return std::filesystem::path (state) / "linux-wallpaperengine";
+    }
+
+    if (const char* home = std::getenv ("HOME"); home != nullptr && home[0] != '\0') {
+	return std::filesystem::path (home) / ".local" / "state" / "linux-wallpaperengine";
+    }
+
+    return {};
+}
+}

+ 2 - 2
src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp

@@ -117,7 +117,7 @@ void WaylandMouseInput::update () {
     this->m_globalCursorFromX11 = false;
 #ifdef ENABLE_X11
     if (!globalCursor.has_value ()) {
-	globalCursor = this->queryX11CursorPosition ();
+	globalCursor = WallpaperEngine::Input::Drivers::WaylandMouseInput::queryX11CursorPosition ();
 	this->m_globalCursorFromX11 = globalCursor.has_value ();
     }
 #endif
@@ -299,7 +299,7 @@ std::optional<glm::dvec2> WaylandMouseInput::queryHyprlandCursorPosition () {
 }
 
 #ifdef ENABLE_X11
-std::optional<glm::dvec2> WaylandMouseInput::queryX11CursorPosition () const {
+std::optional<glm::dvec2> WaylandMouseInput::queryX11CursorPosition () {
     Display* display = XOpenDisplay (nullptr);
     if (!display) {
 	return std::nullopt;

+ 1 - 1
src/WallpaperEngine/Input/Drivers/WaylandMouseInput.h

@@ -43,7 +43,7 @@ private:
     [[nodiscard]] static std::string findHyprlandSocket ();
 #ifdef ENABLE_X11
     // last resort: XWayland's root pointer only tracks the cursor over XWayland windows
-    [[nodiscard]] std::optional<glm::dvec2> queryX11CursorPosition () const;
+    [[nodiscard]] static std::optional<glm::dvec2> queryX11CursorPosition ();
 #endif
     /** the pointer in that output's buffer pixels, y up */
     [[nodiscard]] glm::dvec2 positionOn (const Render::Drivers::Output::WaylandOutputViewport& viewport) const;

+ 42 - 44
src/WallpaperEngine/Led/OpenRgbProtocol.h

@@ -6,48 +6,46 @@
 #include <string>
 #include <vector>
 
-namespace WallpaperEngine::Led {
-namespace OpenRgb {
-    constexpr uint32_t kProtocolVersion = 3;
-    constexpr size_t kHeaderSize = 16;
-
-    enum PacketId : uint32_t {
-	RequestControllerCount = 0,
-	RequestControllerData = 1,
-	RequestProtocolVersion = 40,
-	SetClientName = 50,
-	DeviceListUpdated = 100,
-	UpdateLeds = 1050,
-	SetCustomMode = 1100,
-    };
-
-    void put32 (std::vector<uint8_t>& out, uint32_t value);
-
-    struct Header {
-	uint32_t device = 0;
-	uint32_t id = 0;
-	uint32_t size = 0;
-    };
-
-    struct Zone {
-	std::string name;
-	uint32_t leds = 0;
-	/** row-major led indices inside the zone, 0xFFFFFFFF for an empty cell; empty for a linear zone */
-	std::vector<uint32_t> matrix;
-	uint32_t matrixWidth = 0;
-	uint32_t matrixHeight = 0;
-    };
-
-    struct Device {
-	uint32_t index = 0;
-	std::string name;
-	uint32_t ledCount = 0;
-	std::vector<Zone> zones;
-    };
-
-    [[nodiscard]] std::vector<uint8_t> makePacket (uint32_t device, uint32_t id, std::span<const uint8_t> payload = {});
-    [[nodiscard]] std::optional<Header> parseHeader (std::span<const uint8_t> bytes);
-    [[nodiscard]] std::optional<Device> parseController (std::span<const uint8_t> payload, uint32_t index);
-    [[nodiscard]] std::vector<uint8_t> makeUpdateLeds (uint32_t device, std::span<const uint8_t> rgb);
-}
+namespace WallpaperEngine::Led::OpenRgb {
+constexpr uint32_t kProtocolVersion = 3;
+constexpr size_t kHeaderSize = 16;
+
+enum PacketId : uint32_t {
+    RequestControllerCount = 0,
+    RequestControllerData = 1,
+    RequestProtocolVersion = 40,
+    SetClientName = 50,
+    DeviceListUpdated = 100,
+    UpdateLeds = 1050,
+    SetCustomMode = 1100,
+};
+
+void put32 (std::vector<uint8_t>& out, uint32_t value);
+
+struct Header {
+    uint32_t device = 0;
+    uint32_t id = 0;
+    uint32_t size = 0;
+};
+
+struct Zone {
+    std::string name;
+    uint32_t leds = 0;
+    /** row-major led indices inside the zone, 0xFFFFFFFF for an empty cell; empty for a linear zone */
+    std::vector<uint32_t> matrix;
+    uint32_t matrixWidth = 0;
+    uint32_t matrixHeight = 0;
+};
+
+struct Device {
+    uint32_t index = 0;
+    std::string name;
+    uint32_t ledCount = 0;
+    std::vector<Zone> zones;
+};
+
+[[nodiscard]] std::vector<uint8_t> makePacket (uint32_t device, uint32_t id, std::span<const uint8_t> payload = {});
+[[nodiscard]] std::optional<Header> parseHeader (std::span<const uint8_t> bytes);
+[[nodiscard]] std::optional<Device> parseController (std::span<const uint8_t> payload, uint32_t index);
+[[nodiscard]] std::vector<uint8_t> makeUpdateLeds (uint32_t device, std::span<const uint8_t> rgb);
 }

+ 3 - 5
src/WallpaperEngine/Maths.cpp

@@ -13,9 +13,7 @@ float WallpaperEngine::Maths::randomFloat (std::mt19937& rng, float min, float m
 }
 
 glm::vec3 WallpaperEngine::Maths::randomVec3 (std::mt19937& rng, const glm::vec3& min, const glm::vec3& max) {
-    return glm::vec3 (
-	randomFloat (rng, min.x, max.x), randomFloat (rng, min.y, max.y), randomFloat (rng, min.z, max.z)
-    );
+    return { randomFloat (rng, min.x, max.x), randomFloat (rng, min.y, max.y), randomFloat (rng, min.z, max.z) };
 }
 
 float WallpaperEngine::Maths::lerp (float t, float a, float b) { return a + t * (b - a); }
@@ -34,8 +32,8 @@ float WallpaperEngine::Maths::fadeValue (float life, float startTime, float endT
 /** sub_1401B8C70 */
 glm::vec3 WallpaperEngine::Maths::hsvToRgb (const glm::vec3& hsv) {
     const float chroma = hsv.z * hsv.y;
-    const float sector = static_cast<float> (std::fmod (static_cast<double> (hsv.x * 6.0f), 6.0));
-    const float second = static_cast<float> (
+    const auto sector = static_cast<float> (std::fmod (static_cast<double> (hsv.x * 6.0f), 6.0));
+    const auto second = static_cast<float> (
 	(1.0 - std::fabs (std::fmod (static_cast<double> (sector), 2.0) - 1.0)) * static_cast<double> (chroma)
     );
     const float base = hsv.z - chroma;

+ 1 - 1
src/WallpaperEngine/Media/CoverDownloader.cpp

@@ -96,7 +96,7 @@ std::optional<std::filesystem::path> CoverDownloader::request (const std::string
 	}
     }
 
-    const auto target = this->cachePath (url);
+    auto target = this->cachePath (url);
     std::error_code error;
 
     if (std::filesystem::is_regular_file (target, error)) {

+ 24 - 35
src/WallpaperEngine/Media/DBusMediaSource.cpp

@@ -9,6 +9,22 @@
 
 using namespace WallpaperEngine::Media;
 
+namespace {
+/** Key of the dict entry the iterator is at, value is left at its variant */
+std::string dictEntry (DBusMessageIter& dict, DBusMessageIter& value) {
+    DBusMessageIter entry;
+    dbus_message_iter_recurse (&dict, &entry);
+
+    const char* key = nullptr;
+    dbus_message_iter_get_basic (&entry, &key);
+
+    dbus_message_iter_next (&entry);
+    dbus_message_iter_recurse (&entry, &value);
+
+    return key ?: "";
+}
+}
+
 static DBusHandlerResult dbus_message_filter (DBusConnection* connection, DBusMessage* message, void* user_data) {
     const auto mediaSource = static_cast<DBusMediaSource*> (user_data);
 
@@ -74,17 +90,8 @@ static DBusHandlerResult dbus_message_filter (DBusConnection* connection, DBusMe
     }
 
     while (dbus_message_iter_get_arg_type (&changed) == DBUS_TYPE_DICT_ENTRY) {
-	DBusMessageIter entry;
-	dbus_message_iter_recurse (&changed, &entry);
-
-	const char* key = nullptr;
-	dbus_message_iter_get_basic (&entry, &key);
-
-	std::string keyStr = key ?: "";
-
 	DBusMessageIter value;
-	dbus_message_iter_next (&entry);
-	dbus_message_iter_recurse (&entry, &value);
+	const std::string keyStr = dictEntry (changed, value);
 
 	if (keyStr == "Metadata") {
 	    mediaSource->parseMetadata (value);
@@ -214,17 +221,8 @@ void DBusMediaSource::parseMetadata (DBusMessageIter& variant) {
     bool albumUpdate = false;
 
     while (dbus_message_iter_get_arg_type (&dict) == DBUS_TYPE_DICT_ENTRY) {
-	DBusMessageIter entry;
-	dbus_message_iter_recurse (&dict, &entry);
-
-	const char* key = nullptr;
-	dbus_message_iter_get_basic (&entry, &key);
-
-	std::string keyStr = key ?: "";
-
 	DBusMessageIter value;
-	dbus_message_iter_next (&entry);
-	dbus_message_iter_recurse (&entry, &value);
+	const std::string keyStr = dictEntry (dict, value);
 
 	if (keyStr == "xesam:title") {
 	    const char* title = nullptr;
@@ -288,10 +286,7 @@ void DBusMediaSource::parseMetadata (DBusMessageIter& variant) {
 	    if (artUrlStr.empty () && this->m_mediaInfo.url.has_value ()) {
 		this->m_mediaInfo.url.reset ();
 		albumUpdate = true;
-	    } else if (this->m_mediaInfo.url.has_value () && artUrlStr != *this->m_mediaInfo.url) {
-		this->m_mediaInfo.url = artUrlStr;
-		albumUpdate = true;
-	    } else if (!this->m_mediaInfo.url.has_value ()) {
+	    } else if (!this->m_mediaInfo.url.has_value () || artUrlStr != *this->m_mediaInfo.url) {
 		this->m_mediaInfo.url = artUrlStr;
 		albumUpdate = true;
 	    }
@@ -299,8 +294,8 @@ void DBusMediaSource::parseMetadata (DBusMessageIter& variant) {
 	    int64_t length = 0;
 	    dbus_message_iter_get_basic (&value, &length);
 
-	    if (!WallpaperEngine::Data::Utils::sameFloat (this->m_mediaInfo.duration, length)) {
-		this->m_mediaInfo.duration = length;
+	    if (!WallpaperEngine::Data::Utils::sameFloat (this->m_mediaInfo.duration, static_cast<double> (length))) {
+		this->m_mediaInfo.duration = static_cast<double> (length);
 		metadataUpdate = true;
 	    }
 	}
@@ -388,8 +383,8 @@ void DBusMediaSource::parsePosition (DBusMessageIter& variant) {
     int64_t position = 0;
     dbus_message_iter_get_basic (&variant, &position);
 
-    if (!WallpaperEngine::Data::Utils::sameFloat (this->m_mediaInfo.position, position)) {
-	this->m_mediaInfo.position = position;
+    if (!WallpaperEngine::Data::Utils::sameFloat (this->m_mediaInfo.position, static_cast<double> (position))) {
+	this->m_mediaInfo.position = static_cast<double> (position);
 	this->fireMetadataListeners ();
     }
 }
@@ -642,11 +637,5 @@ void DBusMediaSource::performUpdate () {
     DBusMessageIter variant;
     dbus_message_iter_recurse (&outer, &variant);
 
-    dbus_int64_t position = 0;
-    dbus_message_iter_get_basic (&variant, &position);
-
-    if (!WallpaperEngine::Data::Utils::sameFloat (this->m_mediaInfo.position, position)) {
-	this->m_mediaInfo.position = position;
-	this->fireMetadataListeners ();
-    }
+    this->parsePosition (variant);
 }

+ 2 - 2
src/WallpaperEngine/Media/MediaSource.cpp

@@ -55,7 +55,7 @@ void MediaSource::update () {
 }
 
 std::function<void ()> MediaSource::addMetadataListener (std::function<void (const MediaInfo&)> listener) {
-    int listenerId = ++m_metadataListenerId;
+    int listenerId = static_cast<int> (++m_metadataListenerId);
 
     m_metadataListeners.emplace (listenerId, listener);
 
@@ -71,7 +71,7 @@ std::function<void ()> MediaSource::addMetadataListener (std::function<void (con
 }
 
 std::function<void ()> MediaSource::addAlbumArtListener (std::function<void (const MediaInfo&)> listener) {
-    int listenerId = ++m_albumArtListenerId;
+    int listenerId = static_cast<int> (++m_albumArtListenerId);
 
     m_albumArtListeners.emplace (listenerId, listener);
 

+ 3 - 3
src/WallpaperEngine/Render/AlbumTexture.cpp

@@ -47,15 +47,15 @@ void AlbumTexture::update () const { }
 void AlbumTexture::copyContents (const TextureProvider& other) const noexcept {
     size_t bufferSize = static_cast<size_t> (other.getTextureWidth (0)) * other.getTextureHeight (0) * 4;
 
-    uint8_t* buffer = new uint8_t[bufferSize];
+    auto* buffer = new uint8_t[bufferSize];
 
     glBindTexture (GL_TEXTURE_2D, other.getTextureID (0));
     glGetTexImage (GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
 
     glBindTexture (GL_TEXTURE_2D, this->m_textureID);
     glTexImage2D (
-	GL_TEXTURE_2D, 0, GL_RGBA8, other.getTextureWidth (0), other.getTextureHeight (0), 0, GL_RGBA, GL_UNSIGNED_BYTE,
-	buffer
+	GL_TEXTURE_2D, 0, GL_RGBA8, static_cast<GLsizei> (other.getTextureWidth (0)),
+	static_cast<GLsizei> (other.getTextureHeight (0)), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer
     );
 
     delete[] buffer;

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

@@ -34,7 +34,7 @@ public:
 
 private:
     std::vector<FrameSharedPtr> m_frames;
-    mutable glm::vec4 m_resolution;
+    mutable glm::vec4 m_resolution {};
     mutable uint32_t m_width = 0;
     mutable uint32_t m_height = 0;
     GLuint m_textureID = GL_NONE;

+ 40 - 45
src/WallpaperEngine/Render/CFBO.cpp

@@ -70,11 +70,12 @@ CFBO::CFBO (
 
     for (uint32_t level = 0; level < this->m_mipLevels; level++) {
 	glTexImage2D (
-	    GL_TEXTURE_2D, level, internalFormat (format), std::max (textureWidth >> level, 1u),
-	    std::max (textureHeight >> level, 1u), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr
+	    GL_TEXTURE_2D, static_cast<GLint> (level), internalFormat (format),
+	    static_cast<GLsizei> (std::max (textureWidth >> level, 1u)),
+	    static_cast<GLsizei> (std::max (textureHeight >> level, 1u)), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr
 	);
     }
-    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, this->m_mipLevels - 1);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, static_cast<GLint> (this->m_mipLevels - 1));
 #if !NDEBUG
     glObjectLabel (GL_TEXTURE, this->m_texture, -1, this->m_name.c_str ());
 #endif
@@ -114,8 +115,9 @@ CFBO::CFBO (
 	sLog.error ("FBO ", this->m_name, " can't render to format ", format, ", falling back to RGBA8");
 	for (uint32_t level = 0; level < this->m_mipLevels; level++) {
 	    glTexImage2D (
-		GL_TEXTURE_2D, level, GL_RGBA8, std::max (textureWidth >> level, 1u),
-		std::max (textureHeight >> level, 1u), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr
+		GL_TEXTURE_2D, static_cast<GLint> (level), GL_RGBA8,
+		static_cast<GLsizei> (std::max (textureWidth >> level, 1u)),
+		static_cast<GLsizei> (std::max (textureHeight >> level, 1u)), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr
 	    );
 	}
 	this->m_format = TextureFormat_ARGB8888;
@@ -138,10 +140,10 @@ CFBO::CFBO (
 
     frame->frameNumber = 0;
     frame->frametime = 0;
-    frame->height1 = textureHeight;
-    frame->height2 = realHeight;
-    frame->width1 = textureWidth;
-    frame->width2 = realWidth;
+    frame->height1 = static_cast<float> (textureHeight);
+    frame->height2 = static_cast<float> (realHeight);
+    frame->width1 = static_cast<float> (textureWidth);
+    frame->width2 = static_cast<float> (realWidth);
     frame->x = 0;
     frame->y = 0;
 
@@ -241,46 +243,39 @@ void CFBO::resize (uint32_t width, uint32_t height, const uint32_t mipLevels) {
 	glBindTexture (GL_TEXTURE_2D, this->m_texture);
 	this->setupDepthOnly (width, height);
 	glBindFramebuffer (GL_FRAMEBUFFER, previous);
-	this->m_resolution = { width, height, width, height };
-
-	for (const auto& frame : this->m_frames) {
-	    frame->width1 = frame->width2 = width;
-	    frame->height1 = frame->height2 = height;
+    } else {
+	glBindTexture (GL_TEXTURE_2D, this->m_texture);
+	for (uint32_t level = 0; level < this->m_mipLevels; level++) {
+	    glTexImage2D (
+		GL_TEXTURE_2D, static_cast<GLint> (level), internalFormat (this->m_format),
+		static_cast<GLsizei> (std::max (width >> level, 1u)),
+		static_cast<GLsizei> (std::max (height >> level, 1u)), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr
+	    );
 	}
+	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, static_cast<GLint> (this->m_mipLevels - 1));
 
-	return;
-    }
-
-    glBindTexture (GL_TEXTURE_2D, this->m_texture);
-    for (uint32_t level = 0; level < this->m_mipLevels; level++) {
-	glTexImage2D (
-	    GL_TEXTURE_2D, level, internalFormat (this->m_format), std::max (width >> level, 1u),
-	    std::max (height >> level, 1u), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr
-	);
-    }
-    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, this->m_mipLevels - 1);
+	if (this->m_depthbuffer != GL_NONE) {
+	    glBindRenderbuffer (GL_RENDERBUFFER, this->m_depthbuffer);
+	    glRenderbufferStorage (
+		GL_RENDERBUFFER, GL_DEPTH_COMPONENT32F, static_cast<GLsizei> (width), static_cast<GLsizei> (height)
+	    );
+	    glBindRenderbuffer (GL_RENDERBUFFER, 0);
+	}
 
-    if (this->m_depthbuffer != GL_NONE) {
-	glBindRenderbuffer (GL_RENDERBUFFER, this->m_depthbuffer);
-	glRenderbufferStorage (
-	    GL_RENDERBUFFER, GL_DEPTH_COMPONENT32F, static_cast<GLsizei> (width), static_cast<GLsizei> (height)
-	);
-	glBindRenderbuffer (GL_RENDERBUFFER, 0);
+	glBindFramebuffer (GL_FRAMEBUFFER, this->m_framebuffer);
+	GLfloat previousClearColor[4] = {};
+	glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
+	glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
+	glClear (GL_COLOR_BUFFER_BIT);
+	glClearColor (previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]);
+	glBindFramebuffer (GL_FRAMEBUFFER, previous);
     }
 
-    glBindFramebuffer (GL_FRAMEBUFFER, this->m_framebuffer);
-    GLfloat previousClearColor[4] = {};
-    glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
-    glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
-    glClear (GL_COLOR_BUFFER_BIT);
-    glClearColor (previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]);
-    glBindFramebuffer (GL_FRAMEBUFFER, previous);
-
     this->m_resolution = { width, height, width, height };
 
     for (const auto& frame : this->m_frames) {
-	frame->width1 = frame->width2 = width;
-	frame->height1 = frame->height2 = height;
+	frame->width1 = frame->width2 = static_cast<float> (width);
+	frame->height1 = frame->height2 = static_cast<float> (height);
     }
 }
 
@@ -309,13 +304,13 @@ GLuint CFBO::getDepthbuffer () const { return this->m_depthbuffer; }
 
 GLuint CFBO::getTextureID (uint32_t imageIndex) const { return this->m_texture; }
 
-uint32_t CFBO::getTextureWidth (uint32_t imageIndex) const { return this->m_resolution.x; }
+uint32_t CFBO::getTextureWidth (uint32_t imageIndex) const { return static_cast<uint32_t> (this->m_resolution.x); }
 
-uint32_t CFBO::getTextureHeight (uint32_t imageIndex) const { return this->m_resolution.y; }
+uint32_t CFBO::getTextureHeight (uint32_t imageIndex) const { return static_cast<uint32_t> (this->m_resolution.y); }
 
-uint32_t CFBO::getRealWidth () const { return this->m_resolution.z; }
+uint32_t CFBO::getRealWidth () const { return static_cast<uint32_t> (this->m_resolution.z); }
 
-uint32_t CFBO::getRealHeight () const { return this->m_resolution.w; }
+uint32_t CFBO::getRealHeight () const { return static_cast<uint32_t> (this->m_resolution.w); }
 
 const std::vector<FrameSharedPtr>& CFBO::getFrames () const { return this->m_frames; }
 

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

@@ -11,9 +11,9 @@ namespace WallpaperEngine::Render {
 class CFBO final : public TextureProvider {
 public:
     CFBO (
-	std::string name, const TextureFormat format, const uint32_t flags, const float scale, uint32_t realWidth,
-	uint32_t realHeight, uint32_t textureWidth, uint32_t textureHeight,
-	const glm::vec4& borderColor = { 0.0f, 0.0f, 0.0f, 1.0f }, uint32_t mipLevels = 1
+	std::string name, TextureFormat format, uint32_t flags, float scale, uint32_t realWidth, uint32_t realHeight,
+	uint32_t textureWidth, uint32_t textureHeight, const glm::vec4& borderColor = { 0.0f, 0.0f, 0.0f, 1.0f },
+	uint32_t mipLevels = 1
     );
     ~CFBO () override;
 
@@ -46,7 +46,7 @@ public:
     void incrementUsageCount () const override;
     void decrementUsageCount () const override;
     void update () const override;
-    bool isReady () const override;
+    [[nodiscard]] bool isReady () const override;
 
 private:
     void setupDepthOnly (uint32_t width, uint32_t height);

+ 1 - 1
src/WallpaperEngine/Render/CObject.cpp

@@ -5,7 +5,7 @@ using namespace WallpaperEngine::Render;
 using namespace WallpaperEngine::Render::Wallpapers;
 
 CObject::CObject (Wallpapers::CScene& scene, const Object& object) :
-    Helpers::ContextAware (scene), m_scene (scene), m_object (object) { }
+    Helpers::ContextAware (&scene), m_scene (scene), m_object (object) { }
 
 void CObject::setup () { }
 void CObject::render () { }

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

@@ -14,7 +14,7 @@ namespace WallpaperEngine::Render {
 class CObject : public Helpers::ContextAware, public TypeCaster {
 public:
     CObject (Wallpapers::CScene& scene, const Object& object);
-    virtual ~CObject () override = default;
+    ~CObject () override = default;
 
     virtual void setup ();
     virtual void render ();

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

@@ -61,7 +61,7 @@ CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
     }
 
     this->m_textureID = new GLuint[this->m_header->imageCount];
-    glGenTextures (this->m_header->imageCount, this->m_textureID);
+    glGenTextures (static_cast<GLsizei> (this->m_header->imageCount), this->m_textureID);
 
     // WE decodes the first frame when the texture is made, a GIF it can't play fails to load there, here it falls
     // back to the still image below
@@ -127,7 +127,11 @@ void CTexture::uploadImages (const UploadFormat& upload) const {
 	for (const auto& [index, mipmaps] : this->m_header->images) {
 	    for (const auto& mipmap : mipmaps) {
 		if (mipmap->composedPixels.empty () && mipmap->decodedPixels == nullptr) {
-		    decoded.push_back ({ .mipmap = mipmap.get (), .width = mipmap->width, .height = mipmap->height });
+		    decoded.push_back (
+			{ .mipmap = mipmap.get (),
+			  .width = static_cast<int> (mipmap->width),
+			  .height = static_cast<int> (mipmap->height) }
+		    );
 		}
 	    }
 	}
@@ -216,8 +220,8 @@ void CTexture::uploadImages (const UploadFormat& upload) const {
 		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;
+		int width = static_cast<int> (mipmap->width);
+		int height = static_cast<int> (mipmap->height);
 
 		if (!mipmap->composedPixels.empty ()) {
 		    dataptr = mipmap->composedPixels.data ();
@@ -320,7 +324,7 @@ CTexture::~CTexture () {
     if (this->m_header->isVideoMp4 || this->m_header->flags & TextureFlags_Video) {
 	glDeleteTextures (1, this->m_textureID);
     } else {
-	glDeleteTextures (this->m_header->imageCount, this->m_textureID);
+	glDeleteTextures (static_cast<GLsizei> (this->m_header->imageCount), this->m_textureID);
     }
 
     delete[] this->m_textureID;
@@ -392,7 +396,9 @@ void CTexture::setupOpenGLParameters (const uint32_t textureID) const {
     glBindTexture (GL_TEXTURE_2D, this->m_textureID[textureID]);
 
     glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
-    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, this->m_header->images[textureID].size () - 1);
+    glTexParameteri (
+	GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, static_cast<GLint> (this->m_header->images[textureID].size () - 1)
+    );
 
     if (this->m_header->flags & TextureFlags_ClampUVs) {
 	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);

+ 9 - 7
src/WallpaperEngine/Render/CWallpaper.cpp

@@ -106,7 +106,7 @@ void CWallpaper::prepareBackBuffer (const glm::ivec2& size, const GLenum format)
     }
 
     glBindTexture (GL_TEXTURE_2D, back.texture);
-    glTexImage2D (GL_TEXTURE_2D, 0, format, size.x, size.y, 0, GL_RGBA, GL_FLOAT, nullptr);
+    glTexImage2D (GL_TEXTURE_2D, 0, static_cast<GLint> (format), size.x, size.y, 0, GL_RGBA, GL_FLOAT, nullptr);
     glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
     glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
     glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
@@ -575,10 +575,10 @@ void CWallpaper::present (const glm::ivec4& viewport, const glm::ivec2& globalPo
 
     if (this->m_spanInfo.has_value ()) {
 	const auto& span = this->m_spanInfo.value ();
-	const float spanW = static_cast<float> (span.totalBounds.z);
-	const float spanH = static_cast<float> (span.totalBounds.w);
-	const float spanX = static_cast<float> (span.totalBounds.x);
-	const float spanY = static_cast<float> (span.totalBounds.y);
+	const auto spanW = static_cast<float> (span.totalBounds.z);
+	const auto spanH = static_cast<float> (span.totalBounds.w);
+	const auto spanX = static_cast<float> (span.totalBounds.x);
+	const auto spanY = static_cast<float> (span.totalBounds.y);
 
 	const glm::vec4 base = this->getOutputUVs ();
 	const float baseUstart = base.x;
@@ -754,6 +754,8 @@ void CWallpaper::setPause (bool newState) { }
 
 void CWallpaper::setAudioPolicy (bool muted, std::optional<int> ambientVolume) { }
 
+void CWallpaper::setAudioHushed (bool hushed) { }
+
 void CWallpaper::setupFramebuffers (const bool depth, const TextureFormat format) {
     const uint32_t width = this->getCanvasWidth ();
     const uint32_t height = this->getCanvasHeight ();
@@ -917,8 +919,8 @@ void CWallpaper::loadLut (const std::string& name) {
 	glTexParameteri (GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
 	glPixelStorei (GL_UNPACK_ALIGNMENT, 4);
 	glTexImage3D (
-	    GL_TEXTURE_3D, 0, GL_RGBA8, mipmap->width, mipmap->height, mipmap->depth, 0, GL_RGBA, GL_UNSIGNED_BYTE,
-	    pixels
+	    GL_TEXTURE_3D, 0, GL_RGBA8, static_cast<GLsizei> (mipmap->width), static_cast<GLsizei> (mipmap->height),
+	    static_cast<GLsizei> (mipmap->depth), 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels
 	);
 	glBindTexture (GL_TEXTURE_3D, 0);
 

+ 8 - 4
src/WallpaperEngine/Render/CWallpaper.h

@@ -48,10 +48,10 @@ public:
 	double scale = 1.0;
     };
 
-    virtual ~CWallpaper () override;
+    ~CWallpaper () override;
 
     void render (
-	const glm::ivec4& viewport, const bool vflip, const glm::ivec2& globalPosition = { 0, 0 },
+	const glm::ivec4& viewport, bool vflip, const glm::ivec2& globalPosition = { 0, 0 },
 	const glm::ivec2& logicalSize = { 0, 0 }
     );
 
@@ -66,6 +66,9 @@ public:
 
     virtual void setAudioPolicy (bool muted, std::optional<int> ambientVolume);
 
+    /** Silences the wallpaper right away, on top of the audio policy, and gives it back when called with false */
+    virtual void setAudioHushed (bool hushed);
+
     [[nodiscard]] const AssetLocator& getAssetLocator () const;
     AudioContext& getAudioContext () const;
     [[nodiscard]] const WallpaperState& getState () const;
@@ -103,7 +106,7 @@ public:
     [[nodiscard]] std::shared_ptr<const CFBO> findFBO (const std::string& name) const;
     [[nodiscard]] std::shared_ptr<const CFBO> getFBO () const;
 
-    void updateUVs (const glm::ivec4& viewport, const bool vflip);
+    void updateUVs (const glm::ivec4& viewport, bool vflip);
     void setDestinationFramebuffer (GLuint framebuffer);
     void setSpanInfo (const SpanInfo& spanInfo);
     [[nodiscard]] const SpanInfo* getSpanInfo () const;
@@ -121,7 +124,8 @@ public:
     [[nodiscard]] virtual int getCanvasHeight () const { return this->getHeight (); }
     /** 0 when any size fits (web pages); sizes split slots */
     [[nodiscard]] virtual float getAspectRatio () const {
-	return this->getHeight () > 0 ? static_cast<float> (this->getWidth ()) / this->getHeight () : 0.0f;
+	return this->getHeight () > 0 ? static_cast<float> (this->getWidth ()) / static_cast<float> (this->getHeight ())
+				      : 0.0f;
     }
     [[nodiscard]] virtual bool rendersAtOutputSize () const { return false; }
     [[nodiscard]] virtual bool wantsPointerButtons () const { return false; }

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

@@ -15,8 +15,6 @@ Camera::Camera (Wallpapers::CScene& scene, const SceneData::Camera& camera) :
     this->m_lookat = glm::lookAt (this->getEye (), this->getCenter (), this->getUp ());
 }
 
-Camera::~Camera () = default;
-
 const glm::vec3& Camera::getCenter () const { return this->m_camera.configuration.center; }
 
 const glm::vec3& Camera::getEye () const { return this->m_eye; }

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

@@ -17,7 +17,7 @@ using namespace WallpaperEngine::Data::Model;
 class Camera {
 public:
     Camera (Wallpapers::CScene& scene, const SceneData::Camera& camera);
-    ~Camera ();
+    ~Camera () = default;
 
     // width/height is the layout objects are positioned in, canvas the rendered size centered on it (0 = layout size)
     void setOrthogonalProjection (float width, float height, float canvasWidth = 0.0f, float canvasHeight = 0.0f);

+ 14 - 10
src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp

@@ -60,6 +60,14 @@ namespace {
 	}
     }
 
+    template <typename Visitor> void forEachState (const wl_array* state, Visitor&& visit) {
+	const auto begin = static_cast<const uint32_t*> (state->data);
+
+	for (auto it = begin; it < begin + state->size / sizeof (uint32_t); ++it) {
+	    visit (*it);
+	}
+    }
+
     void toplevelOutputEnter (void* data, zwlr_foreign_toplevel_handle_v1*, wl_output* output) {
 	static_cast<Toplevel*> (data)->outputs.insert (output);
     }
@@ -70,14 +78,12 @@ namespace {
 
     void toplevelState (void* data, zwlr_foreign_toplevel_handle_v1*, wl_array* state) {
 	const auto toplevel = static_cast<Toplevel*> (data);
-	const auto begin = static_cast<uint32_t*> (state->data);
-
 	toplevel->fullscreen = false;
 	toplevel->maximized = false;
 	toplevel->activated = false;
 
-	for (auto it = begin; it < begin + state->size / sizeof (uint32_t); ++it) {
-	    switch (*it) {
+	forEachState (state, [toplevel] (const uint32_t value) {
+	    switch (value) {
 		case ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN:
 		    toplevel->fullscreen = true;
 		    break;
@@ -90,7 +96,7 @@ namespace {
 		default:
 		    break;
 	    }
-	}
+	});
     }
 
     void toplevelDone (void*, zwlr_foreign_toplevel_handle_v1*) { }
@@ -173,15 +179,13 @@ namespace {
 
     void cosmicState (void* data, zcosmic_toplevel_handle_v1*, wl_array* state) {
 	const auto toplevel = static_cast<Toplevel*> (data);
-	const auto begin = static_cast<uint32_t*> (state->data);
-
 	toplevel->fullscreen = false;
 	toplevel->maximized = false;
 	toplevel->activated = false;
 	toplevel->minimized = false;
 
-	for (auto it = begin; it < begin + state->size / sizeof (uint32_t); ++it) {
-	    switch (*it) {
+	forEachState (state, [toplevel] (const uint32_t value) {
+	    switch (value) {
 		case ZCOSMIC_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN:
 		    toplevel->fullscreen = true;
 		    break;
@@ -197,7 +201,7 @@ namespace {
 		default:
 		    break;
 	    }
-	}
+	});
     }
 
     void cosmicGeometry (void*, zcosmic_toplevel_handle_v1*, wl_output*, int32_t, int32_t, int32_t, int32_t) { }

+ 25 - 88
src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp

@@ -1,5 +1,6 @@
 #include "X11FullScreenDetector.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/Drivers/X11RandR.h"
 #include "WallpaperEngine/Render/Drivers/X11WindowType.h"
 
 #include <algorithm>
@@ -92,13 +93,18 @@ bool X11FullScreenDetector::anythingFullscreen () const {
 	// only managed windows count, WM/compositor helpers and our desktop window cover the screen too
 	const Window client = this->clientOf (children[i]);
 
-	if (client == None || client == ourWindow || hasDesktopWindowType (this->m_display, client)
-	    || this->isHidden (client) || !this->onCurrentDesktop (client)) {
+	if (client == None || client == ourWindow || hasDesktopWindowType (this->m_display, client)) {
+	    continue;
+	}
+
+	const auto states = windowAtoms (this->m_display, client, "_NET_WM_STATE");
+
+	if (this->isHidden (client, states) || !this->onCurrentDesktop (client)) {
 	    continue;
 	}
 
 	fullscreen
-	    = this->hasFullscreenState (client) || this->hasMaximizedState (client) || this->coversScreen (client);
+	    = this->hasFullscreenState (states) || this->hasMaximizedState (states) || this->coversScreen (client);
     }
 
     XFree (children);
@@ -164,35 +170,19 @@ bool X11FullScreenDetector::applicationFocused (Window ourWindow) const {
     return XGetWindowAttributes (this->m_display, active, &attributes) && attributes.map_state == IsViewable;
 }
 
-bool X11FullScreenDetector::isHidden (Window client) const {
+bool X11FullScreenDetector::isHidden (Window client, const std::vector<Atom>& states) const {
     // minimized, or tabbed out: some window managers keep the frame of such a window mapped
-    const Atom stateAtom = XInternAtom (this->m_display, "_NET_WM_STATE", False);
-    const Atom hiddenAtom = XInternAtom (this->m_display, "_NET_WM_STATE_HIDDEN", False);
-    Atom type;
-    int format;
-    unsigned long count, remaining;
-    unsigned char* data = nullptr;
-    bool hidden = false;
-
-    if (XGetWindowProperty (
-	    this->m_display, client, stateAtom, 0, 32, False, XA_ATOM, &type, &format, &count, &remaining, &data
-	) == Success
-	&& data != nullptr && format == 32) {
-	const auto* atoms = reinterpret_cast<const Atom*> (data);
-	hidden = std::find (atoms, atoms + count, hiddenAtom) != atoms + count;
-    }
-
-    if (data != nullptr) {
-	XFree (data);
-    }
-
-    if (hidden) {
+    if (hasAtom (states, XInternAtom (this->m_display, "_NET_WM_STATE_HIDDEN", False))) {
 	return true;
     }
 
     // ICCCM: WM_STATE 3 is iconic
     const Atom wmState = XInternAtom (this->m_display, "WM_STATE", False);
-    data = nullptr;
+    Atom type;
+    int format;
+    unsigned long count, remaining;
+    unsigned char* data = nullptr;
+    bool hidden = false;
 
     if (XGetWindowProperty (
 	    this->m_display, client, wmState, 0, 2, False, wmState, &type, &format, &count, &remaining, &data
@@ -244,54 +234,13 @@ bool X11FullScreenDetector::onCurrentDesktop (Window client) const {
     return windowDesktop == currentDesktop;
 }
 
-bool X11FullScreenDetector::hasFullscreenState (Window client) const {
-    const Atom stateAtom = XInternAtom (this->m_display, "_NET_WM_STATE", False);
-    const Atom fullscreenAtom = XInternAtom (this->m_display, "_NET_WM_STATE_FULLSCREEN", False);
-    Atom type;
-    int format;
-    unsigned long count, remaining;
-    unsigned char* data = nullptr;
-    bool fullscreen = false;
-
-    if (XGetWindowProperty (
-	    this->m_display, client, stateAtom, 0, 32, False, XA_ATOM, &type, &format, &count, &remaining, &data
-	) == Success
-	&& data != nullptr && format == 32) {
-	const auto* atoms = reinterpret_cast<const Atom*> (data);
-	fullscreen = std::find (atoms, atoms + count, fullscreenAtom) != atoms + count;
-    }
-
-    if (data != nullptr) {
-	XFree (data);
-    }
-
-    return fullscreen;
+bool X11FullScreenDetector::hasFullscreenState (const std::vector<Atom>& states) const {
+    return hasAtom (states, XInternAtom (this->m_display, "_NET_WM_STATE_FULLSCREEN", False));
 }
 
-bool X11FullScreenDetector::hasMaximizedState (Window client) const {
-    const Atom stateAtom = XInternAtom (this->m_display, "_NET_WM_STATE", False);
-    const Atom vertAtom = XInternAtom (this->m_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
-    const Atom horzAtom = XInternAtom (this->m_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
-    Atom type;
-    int format;
-    unsigned long count, remaining;
-    unsigned char* data = nullptr;
-    bool maximized = false;
-
-    if (XGetWindowProperty (
-	    this->m_display, client, stateAtom, 0, 32, False, XA_ATOM, &type, &format, &count, &remaining, &data
-	) == Success
-	&& data != nullptr && format == 32) {
-	const auto* atoms = reinterpret_cast<const Atom*> (data);
-	maximized = std::find (atoms, atoms + count, vertAtom) != atoms + count
-	    && std::find (atoms, atoms + count, horzAtom) != atoms + count;
-    }
-
-    if (data != nullptr) {
-	XFree (data);
-    }
-
-    return maximized;
+bool X11FullScreenDetector::hasMaximizedState (const std::vector<Atom>& states) const {
+    return hasAtom (states, XInternAtom (this->m_display, "_NET_WM_STATE_MAXIMIZED_VERT", False))
+	&& hasAtom (states, XInternAtom (this->m_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False));
 }
 
 bool X11FullScreenDetector::coversScreen (Window client) const {
@@ -382,23 +331,11 @@ void X11FullScreenDetector::initialize () {
 	return;
     }
 
-    for (int i = 0; i < screenResources->noutput; i++) {
-	const XRROutputInfo* info = XRRGetOutputInfo (this->m_display, screenResources, screenResources->outputs[i]);
-
-	if (info == nullptr || info->connection != RR_Connected) {
-	    continue;
+    forEachConnectedOutput (
+	this->m_display, screenResources, [this] (const XRROutputInfo& info, const XRRCrtcInfo& crtc) {
+	    this->m_screens.emplace (std::string (info.name), glm::ivec4 (crtc.x, crtc.y, crtc.width, crtc.height));
 	}
-
-	XRRCrtcInfo* crtc = XRRGetCrtcInfo (this->m_display, screenResources, info->crtc);
-
-	if (crtc == nullptr) {
-	    continue;
-	}
-
-	this->m_screens.emplace (std::string (info->name), glm::ivec4 (crtc->x, crtc->y, crtc->width, crtc->height));
-
-	XRRFreeCrtcInfo (crtc);
-    }
+    );
 
     XRRFreeScreenResources (screenResources);
 }

+ 3 - 3
src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.h

@@ -25,9 +25,9 @@ namespace Detectors {
     private:
 	void initialize ();
 	[[nodiscard]] Window clientOf (Window window) const;
-	[[nodiscard]] bool hasFullscreenState (Window client) const;
-	[[nodiscard]] bool hasMaximizedState (Window client) const;
-	[[nodiscard]] bool isHidden (Window client) const;
+	[[nodiscard]] bool hasFullscreenState (const std::vector<Atom>& states) const;
+	[[nodiscard]] bool hasMaximizedState (const std::vector<Atom>& states) const;
+	[[nodiscard]] bool isHidden (Window client, const std::vector<Atom>& states) const;
 	[[nodiscard]] bool onCurrentDesktop (Window client) const;
 	[[nodiscard]] bool coversScreen (Window client) const;
 	[[nodiscard]] bool applicationFocused (Window ourWindow) const;

+ 4 - 11
src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.cpp

@@ -108,16 +108,11 @@ GLFWOpenGLDriver::GLFWOpenGLDriver (const char* windowTitle, ApplicationContext&
 
     glfwMakeContextCurrent (this->m_window);
 
-    // GLEW built for GLX finds no GLX display behind an EGL context, the functions still load
-    glewExperimental = GL_TRUE;
+    initializeGlew ();
 
-    if (const GLenum result = glewInit (); result != GLEW_OK && result != GLEW_ERROR_NO_GLX_DISPLAY) {
-	sLog.error ("Failed to initialize GLEW: ", glewGetErrorString (result));
-    }
+    this->m_output = this->createWindowOutput (context);
 
-    if (context.settings.render.mode == ApplicationContext::EXPLICIT_WINDOW
-	|| context.settings.render.mode == ApplicationContext::NORMAL_WINDOW) {
-	m_output = new WallpaperEngine::Render::Drivers::Output::GLFWWindowOutput (context, *this);
+    if (this->m_output != nullptr) {
 	this->m_offscreen = context.settings.render.mode == ApplicationContext::EXPLICIT_WINDOW
 	    && context.settings.render.window.asBackground && m_output->haveImageBuffer ();
     }
@@ -207,9 +202,7 @@ void GLFWOpenGLDriver::dispatchEventQueue () {
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_targetFramebuffer);
     glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 
-    for (const auto& [screen, viewport] : this->m_output->getViewports ()) {
-	this->getApp ().update (viewport);
-    }
+    this->updateViewports (*this->m_output);
 
     if (this->m_output->haveImageBuffer ()) {
 	glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_targetFramebuffer);

+ 1 - 1
src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.h

@@ -34,7 +34,7 @@ public:
     [[nodiscard]] void* getProcAddress (const char* name) const override;
     [[nodiscard]] void* getX11Display () const override;
 
-    GLFWwindow* getWindow () const;
+    [[nodiscard]] GLFWwindow* getWindow () const;
 
 private:
     void createOffscreenTarget (int width, int height);

+ 1 - 6
src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.cpp

@@ -160,12 +160,7 @@ HeadlessOpenGLDriver::HeadlessOpenGLDriver (ApplicationContext& context, Wallpap
 
     this->createSurface ();
 
-    glewExperimental = GL_TRUE;
-
-    // GLEW built with GLX support fails its GLX part without an X display, the GL functions are loaded by then
-    if (const GLenum result = glewInit (); result != GLEW_OK && result != GLEW_ERROR_NO_GLX_DISPLAY) {
-	sLog.error ("Failed to initialize GLEW: ", glewGetErrorString (result));
-    }
+    initializeGlew ();
 
     this->m_output = new Output::GLFWWindowOutput (context, *this);
 }

+ 2 - 2
src/WallpaperEngine/Render/Drivers/Output/Output.cpp

@@ -18,8 +18,8 @@ void Output::readImageBuffer () const {
     // glReadnPixels requires GL 4.5; older drivers fall back to glReadPixels
     if (GLEW_VERSION_4_5) {
 	glReadnPixels (
-	    0, 0, this->getFullWidth (), this->getFullHeight (), GL_BGRA, GL_UNSIGNED_BYTE, this->getImageBufferSize (),
-	    this->getImageBuffer ()
+	    0, 0, this->getFullWidth (), this->getFullHeight (), GL_BGRA, GL_UNSIGNED_BYTE,
+	    static_cast<GLsizei> (this->getImageBufferSize ()), this->getImageBuffer ()
 	);
     } else {
 	glReadPixels (

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

@@ -746,7 +746,7 @@ void WaylandOutputViewport::updateBufferSize () {
     this->resize ();
 }
 
-void WaylandOutputViewport::resize () {
+void WaylandOutputViewport::resize () const {
     if (!this->eglWindow) {
 	return;
     }

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

@@ -43,7 +43,7 @@ namespace Output {
     public:
 	WaylandOutputViewport (WaylandOpenGLDriver* driver, uint32_t waylandName, struct wl_registry* registry);
 
-	WaylandOpenGLDriver* getDriver () const;
+	[[nodiscard]] WaylandOpenGLDriver* getDriver () const;
 
 	wl_output* output = nullptr;
 	glm::ivec2 size = {};
@@ -131,7 +131,7 @@ namespace Output {
 	void makeCurrent () override;
 	void renderFrame ();
 	void swapOutput () override;
-	void resize ();
+	void resize () const;
 
     private:
 	void prepareSurface ();

+ 16 - 46
src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp

@@ -1,6 +1,8 @@
 #include "X11Output.h"
 #include "GLFWOutputViewport.h"
+#include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/Drivers/X11RandR.h"
 #include "WallpaperEngine/Render/Drivers/X11WindowType.h"
 
 #include <algorithm>
@@ -143,34 +145,23 @@ void X11Output::loadScreenInfo () {
 }
 
 void X11Output::discoverOutputs (XRRScreenResources* screenResources) {
-    for (int i = 0; i < screenResources->noutput; i++) {
-	const XRROutputInfo* info = XRRGetOutputInfo (this->m_display, screenResources, screenResources->outputs[i]);
-
-	if (info == nullptr || info->connection != RR_Connected) {
-	    continue;
-	}
-
-	XRRCrtcInfo* crtc = XRRGetCrtcInfo (this->m_display, screenResources, info->crtc);
-
-	if (crtc == nullptr) {
-	    continue;
-	}
+    forEachConnectedOutput (
+	this->m_display, screenResources, [this] (const XRROutputInfo& info, const XRRCrtcInfo& crtc) {
+	    if (!this->m_context.isScreenRequested (info.name)) {
+		return;
+	    }
 
-	if (this->m_context.isScreenRequested (info->name)) {
 	    sLog.out (
-		"Found requested screen: ", info->name, " -> ", crtc->x, "x", crtc->y, ":", crtc->width, "x",
-		crtc->height
+		"Found requested screen: ", info.name, " -> ", crtc.x, "x", crtc.y, ":", crtc.width, "x", crtc.height
 	    );
 
-	    auto* vp = new GLFWOutputViewport { { crtc->x, crtc->y, crtc->width, crtc->height }, info->name };
-	    vp->globalPosition = { crtc->x, crtc->y };
-	    vp->logicalSize = { crtc->width, crtc->height };
+	    auto* vp = new GLFWOutputViewport { { crtc.x, crtc.y, crtc.width, crtc.height }, info.name };
+	    vp->globalPosition = { crtc.x, crtc.y };
+	    vp->logicalSize = { crtc.width, crtc.height };
 	    this->m_screens.push_back (vp);
-	    this->m_viewports[info->name] = vp;
+	    this->m_viewports[info.name] = vp;
 	}
-
-	XRRFreeCrtcInfo (crtc);
-    }
+    );
 }
 
 void X11Output::validateOutputs () const {
@@ -201,30 +192,8 @@ bool X11Output::desktopHidesRootWindow () {
 	return forced[0] != '0';
     }
 
-    const char* desktops = std::getenv ("XDG_CURRENT_DESKTOP");
-
-    if (desktops == nullptr) {
-	return false;
-    }
-
-    std::string_view rest (desktops);
-
-    while (!rest.empty ()) {
-	const auto colon = rest.find (':');
-	const auto name = rest.substr (0, colon);
-
-	if (name == "GNOME" || name == "Pantheon" || name == "X-Cinnamon") {
-	    return true;
-	}
-
-	if (colon == std::string_view::npos) {
-	    break;
-	}
-
-	rest.remove_prefix (colon + 1);
-    }
-
-    return false;
+    return Desktop::desktopListHas ("GNOME") || Desktop::desktopListHas ("Pantheon")
+	|| Desktop::desktopListHas ("X-Cinnamon");
 }
 
 void X11Output::initX11Background () {
@@ -469,6 +438,7 @@ void X11Output::updateDesktopIcons (const std::vector<Window>& covering) const {
     this->m_iconsTried = true;
     std::vector<std::string> names;
 
+    names.reserve (this->m_screens.size ());
     for (const auto* screen : this->m_screens) {
 	names.push_back (screen->name);
     }

+ 32 - 1
src/WallpaperEngine/Render/Drivers/VideoDriver.cpp

@@ -1,6 +1,14 @@
 #include "VideoDriver.h"
 
+#include <GL/glew.h>
+
+#include "WallpaperEngine/Application/ApplicationContext.h"
+#include "WallpaperEngine/Application/WallpaperApplication.h"
+#include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.h"
+
 using namespace WallpaperEngine::Input;
+using WallpaperEngine::Application::ApplicationContext;
 using namespace WallpaperEngine::Render::Drivers;
 
 VideoDriver::VideoDriver (WallpaperApplication& app, MouseInput& mouseInput) :
@@ -8,4 +16,27 @@ VideoDriver::VideoDriver (WallpaperApplication& app, MouseInput& mouseInput) :
 
 WallpaperApplication& VideoDriver::getApp () const { return this->m_app; }
 
-InputContext& VideoDriver::getInputContext () { return this->m_inputContext; }
+InputContext& VideoDriver::getInputContext () { return this->m_inputContext; }
+
+void VideoDriver::initializeGlew () {
+    glewExperimental = GL_TRUE;
+
+    if (const GLenum result = glewInit (); result != GLEW_OK && result != GLEW_ERROR_NO_GLX_DISPLAY) {
+	sLog.error ("Failed to initialize GLEW: ", glewGetErrorString (result));
+    }
+}
+
+void VideoDriver::updateViewports (const Output::Output& output) const {
+    for (const auto& [screen, viewport] : output.getViewports ()) {
+	this->getApp ().update (viewport);
+    }
+}
+
+Output::Output* VideoDriver::createWindowOutput (ApplicationContext& context) {
+    if (context.settings.render.mode != ApplicationContext::EXPLICIT_WINDOW
+	&& context.settings.render.mode != ApplicationContext::NORMAL_WINDOW) {
+	return nullptr;
+    }
+
+    return new Output::GLFWWindowOutput (context, *this);
+}

+ 9 - 0
src/WallpaperEngine/Render/Drivers/VideoDriver.h

@@ -9,6 +9,7 @@
 #include <string>
 
 namespace WallpaperEngine::Application {
+class ApplicationContext;
 class WallpaperApplication;
 }
 
@@ -54,6 +55,14 @@ public:
     [[nodiscard]] WallpaperApplication& getApp () const;
     [[nodiscard]] Input::InputContext& getInputContext ();
 
+protected:
+    // loads GL's functions for the current context, also where GLEW has no GLX display (EGL contexts)
+    static void initializeGlew ();
+    // the output of a window mode (explicit or normal), nothing for the other modes
+    [[nodiscard]] Output::Output* createWindowOutput (Application::ApplicationContext& context);
+    // draws every viewport of the output
+    void updateViewports (const Output::Output& output) const;
+
 private:
     WallpaperApplication& m_app;
     Input::InputContext m_inputContext;

+ 5 - 5
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp

@@ -28,8 +28,8 @@ extern "C" {
 
 #include <algorithm>
 #include <cerrno>
+#include <cstring>
 #include <poll.h>
-#include <string.h>
 #include <unistd.h>
 
 using namespace WallpaperEngine::Render::Drivers;
@@ -57,8 +57,8 @@ static void handlePointerEnter (
     wl_surface_set_buffer_scale (viewport->cursorSurface, viewport->scale);
     wl_surface_attach (viewport->cursorSurface, wl_cursor_image_get_buffer (viewport->pointer->images[0]), 0, 0);
     wl_pointer_set_cursor (
-	wl_pointer, serial, viewport->cursorSurface, viewport->pointer->images[0]->hotspot_x,
-	viewport->pointer->images[0]->hotspot_y
+	wl_pointer, serial, viewport->cursorSurface, static_cast<int32_t> (viewport->pointer->images[0]->hotspot_x),
+	static_cast<int32_t> (viewport->pointer->images[0]->hotspot_y)
     );
     wl_surface_commit (viewport->cursorSurface);
 }
@@ -87,7 +87,7 @@ static void handlePointerMotion (
     }
 
     // Wayland has Y=0 at the top, OpenGL has Y=0 at the bottom
-    const double viewportHeight = static_cast<double> (driver->viewportInFocus->size.y);
+    const auto viewportHeight = static_cast<double> (driver->viewportInFocus->size.y);
     y = viewportHeight - y;
 
     // buffer pixels, WE maps the cursor into the window's physical client area
@@ -542,7 +542,7 @@ void WaylandOpenGLDriver::onSurfaceClosed (Output::WaylandOutputViewport* viewpo
     }
 }
 
-void WaylandOpenGLDriver::makeSurfacelessCurrent () {
+void WaylandOpenGLDriver::makeSurfacelessCurrent () const {
     if (eglMakeCurrent (m_eglContext.display, EGL_NO_SURFACE, EGL_NO_SURFACE, m_eglContext.context) == EGL_FALSE) {
 	sLog.exception (
 	    "The compositor shows no wallpaper surface and EGL can't use the GL context without one "

+ 2 - 2
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h

@@ -112,7 +112,7 @@ public:
     void releaseSurface (Output::WaylandOutputViewport*);
     void removeOutput (Output::WaylandOutputViewport*);
     void onSurfaceClosed (Output::WaylandOutputViewport*);
-    void makeSurfacelessCurrent ();
+    void makeSurfacelessCurrent () const;
     [[nodiscard]] bool hasGlobalCursor () const { return this->m_mouseInput.hasGlobalCursor (); }
     [[nodiscard]] Desktop::GnomeShell* getGnomeShell () const { return this->m_gnomeShell.get (); }
     [[nodiscard]] bool hasCapturedCursor () const;
@@ -143,7 +143,7 @@ private:
     void setupOutputLayerSurfaces ();
     void setupLateOutputs ();
     void initEGL ();
-    void initGLEW ();
+    static void initGLEW ();
     void finishEGL () const;
     void initColorManagement ();
 

+ 27 - 0
src/WallpaperEngine/Render/Drivers/X11RandR.h

@@ -0,0 +1,27 @@
+#pragma once
+
+#include <X11/Xlib.h>
+#include <X11/extensions/Xrandr.h>
+
+namespace WallpaperEngine::Render::Drivers {
+/** Calls visit with the info and crtc of every connected output that has one */
+template <typename Visitor>
+void forEachConnectedOutput (Display* display, XRRScreenResources* resources, Visitor&& visit) {
+    for (int i = 0; i < resources->noutput; i++) {
+	XRROutputInfo* info = XRRGetOutputInfo (display, resources, resources->outputs[i]);
+
+	if (info == nullptr) {
+	    continue;
+	}
+
+	if (info->connection == RR_Connected) {
+	    if (XRRCrtcInfo* crtc = XRRGetCrtcInfo (display, resources, info->crtc); crtc != nullptr) {
+		visit (*info, *crtc);
+		XRRFreeCrtcInfo (crtc);
+	    }
+	}
+
+	XRRFreeOutputInfo (info);
+    }
+}
+}

+ 22 - 9
src/WallpaperEngine/Render/Drivers/X11WindowType.h

@@ -1,31 +1,44 @@
 #pragma once
 
 #include <algorithm>
+#include <vector>
 
 #include <X11/Xatom.h>
 #include <X11/Xlib.h>
 
 namespace WallpaperEngine::Render::Drivers {
-inline bool hasDesktopWindowType (Display* display, Window window) {
-    const Atom typeAtom = XInternAtom (display, "_NET_WM_WINDOW_TYPE", False);
-    const Atom desktopAtom = XInternAtom (display, "_NET_WM_WINDOW_TYPE_DESKTOP", False);
+/** The atoms of an XA_ATOM property of a window, empty when it is not set */
+inline std::vector<Atom> windowAtoms (Display* display, Window window, const char* property) {
+    const Atom propertyAtom = XInternAtom (display, property, False);
     Atom type;
     int format;
     unsigned long count, remaining;
     unsigned char* data = nullptr;
-    bool desktop = false;
+    std::vector<Atom> atoms;
 
-    if (XGetWindowProperty (display, window, typeAtom, 0, 16, False, XA_ATOM, &type, &format, &count, &remaining, &data)
-	    == Success
+    if (XGetWindowProperty (
+	    display, window, propertyAtom, 0, 32, False, XA_ATOM, &type, &format, &count, &remaining, &data
+	) == Success
 	&& data != nullptr && format == 32) {
-	const auto* atoms = reinterpret_cast<const Atom*> (data);
-	desktop = std::find (atoms, atoms + count, desktopAtom) != atoms + count;
+	const auto* values = reinterpret_cast<const Atom*> (data);
+	atoms.assign (values, values + count);
     }
 
     if (data != nullptr) {
 	XFree (data);
     }
 
-    return desktop;
+    return atoms;
+}
+
+inline bool hasAtom (const std::vector<Atom>& atoms, const Atom atom) {
+    return std::find (atoms.begin (), atoms.end (), atom) != atoms.end ();
+}
+
+inline bool hasDesktopWindowType (Display* display, Window window) {
+    return hasAtom (
+	windowAtoms (display, window, "_NET_WM_WINDOW_TYPE"),
+	XInternAtom (display, "_NET_WM_WINDOW_TYPE_DESKTOP", False)
+    );
 }
 }

+ 1 - 2
src/WallpaperEngine/Render/Fonts/SystemFonts.cpp

@@ -16,8 +16,6 @@
 #include <unistd.h>
 #include <unordered_map>
 
-extern char** environ;
-
 namespace WallpaperEngine::Render::Fonts {
 namespace {
     std::string run (const std::string& config, const std::string& pattern, const std::string& format) {
@@ -37,6 +35,7 @@ namespace {
 
 	std::vector<char*> envp;
 
+	envp.reserve (environment.size ());
 	for (std::string& entry : environment) {
 	    envp.push_back (entry.data ());
 	}

+ 5 - 21
src/WallpaperEngine/Render/FrameMaterial.cpp

@@ -3,6 +3,7 @@
 #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/CFBO.h"
+#include "WallpaperEngine/Render/Helpers/ShaderCompile.h"
 #include "WallpaperEngine/Render/Shaders/GLSLContext.h"
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 
@@ -15,24 +16,6 @@ constexpr float kQuad[] = {
     -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
     -1.0f, 1.0f,  0.0f, 0.0f, 1.0f, 1.0f, 1.0f,  0.0f, 1.0f, 1.0f,
 };
-
-GLuint compile (const std::string& source, const GLenum type, const std::string& name) {
-    const GLuint shader = glCreateShader (type);
-    const char* text = source.c_str ();
-    glShaderSource (shader, 1, &text, nullptr);
-    glCompileShader (shader);
-
-    GLint compiled = GL_FALSE;
-    glGetShaderiv (shader, GL_COMPILE_STATUS, &compiled);
-
-    if (compiled == GL_FALSE) {
-	char log[2048] = {};
-	glGetShaderInfoLog (shader, sizeof (log) - 1, nullptr, log);
-	sLog.error ("Frame material ", name, " failed to compile: ", log);
-    }
-
-    return shader;
-}
 }
 
 FrameMaterial::FrameMaterial (
@@ -70,7 +53,7 @@ FrameMaterial::FrameMaterial (
 	    *project.assetLocator, this->m_pass->shader, this->m_combos, this->m_overrideCombos, this->m_pass->textures,
 	    this->m_noTextures, noConstants
 	);
-	const auto sources = Shaders::GLSLContext::get ().toGlsl (
+	const auto sources = WallpaperEngine::Render::Shaders::GLSLContext::toGlsl (
 	    this->m_shader->vertex (), this->m_shader->fragment (), this->m_pass->shader
 	);
 	this->link (sources.vertex, sources.fragment, this->m_pass->shader);
@@ -158,8 +141,9 @@ FrameMaterial::~FrameMaterial () {
 }
 
 void FrameMaterial::link (const std::string& vertex, const std::string& fragment, const std::string& name) {
-    const GLuint vertexShader = compile (vertex, GL_VERTEX_SHADER, name);
-    const GLuint fragmentShader = compile (fragment, GL_FRAGMENT_SHADER, name);
+    const GLuint vertexShader = Helpers::compileLogged (GL_VERTEX_SHADER, vertex.c_str (), "Frame material " + name);
+    const GLuint fragmentShader
+	= Helpers::compileLogged (GL_FRAGMENT_SHADER, fragment.c_str (), "Frame material " + name);
     this->m_program = glCreateProgram ();
     glAttachShader (this->m_program, vertexShader);
     glAttachShader (this->m_program, fragmentShader);

+ 26 - 0
src/WallpaperEngine/Render/Helpers/ShaderCompile.h

@@ -0,0 +1,26 @@
+#pragma once
+
+#include <GL/glew.h>
+#include <string_view>
+
+#include "WallpaperEngine/Logging/Log.h"
+
+namespace WallpaperEngine::Render::Helpers {
+/** Compiles one stage, a failure is logged under the given name and the shader is returned anyway */
+inline GLuint compileLogged (const GLenum type, const char* source, const std::string_view name) {
+    const GLuint shader = glCreateShader (type);
+    glShaderSource (shader, 1, &source, nullptr);
+    glCompileShader (shader);
+
+    GLint compiled = GL_FALSE;
+    glGetShaderiv (shader, GL_COMPILE_STATUS, &compiled);
+
+    if (compiled == GL_FALSE) {
+	char log[2048] = {};
+	glGetShaderInfoLog (shader, sizeof (log) - 1, nullptr, log);
+	sLog.error (name, " failed to compile: ", log);
+    }
+
+    return shader;
+}
+}

+ 3 - 19
src/WallpaperEngine/Render/LedFrameGrabber.cpp

@@ -4,6 +4,7 @@
 
 #include "WallpaperEngine/Led/LedLayout.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/Helpers/ShaderCompile.h"
 
 namespace WallpaperEngine::Render {
 namespace {
@@ -31,23 +32,6 @@ void main () {
 }
 )";
 
-    GLuint compile (const GLenum type, const char* source) {
-	const GLuint shader = glCreateShader (type);
-	glShaderSource (shader, 1, &source, nullptr);
-	glCompileShader (shader);
-
-	GLint compiled = GL_FALSE;
-	glGetShaderiv (shader, GL_COMPILE_STATUS, &compiled);
-
-	if (compiled == GL_FALSE) {
-	    char log[1024] = {};
-	    glGetShaderInfoLog (shader, sizeof (log) - 1, nullptr, log);
-	    sLog.error ("LED frame shader failed to compile: ", log);
-	}
-
-	return shader;
-    }
-
     struct SavedState {
 	GLint drawFramebuffer = 0, readFramebuffer = 0, program = 0, vao = 0, activeTexture = 0, texture = 0,
 	      sampler = 0;
@@ -123,8 +107,8 @@ LedFrameGrabber::~LedFrameGrabber () {
 void LedFrameGrabber::create () {
     this->m_created = true;
 
-    const GLuint vertex = compile (GL_VERTEX_SHADER, kVertex);
-    const GLuint fragment = compile (GL_FRAGMENT_SHADER, kFragment);
+    const GLuint vertex = Helpers::compileLogged (GL_VERTEX_SHADER, kVertex, "LED frame shader");
+    const GLuint fragment = Helpers::compileLogged (GL_FRAGMENT_SHADER, kFragment, "LED frame shader");
 
     this->m_program = glCreateProgram ();
     glAttachShader (this->m_program, vertex);

+ 97 - 99
src/WallpaperEngine/Render/ModelData.h

@@ -10,115 +10,113 @@
 
 #include <glm/vec3.hpp>
 
-namespace WallpaperEngine::Render {
 // script geometry (thisScene.createModelData, 2.8.42 engine slots 10-12: sub_14018C720, sub_1401D6400, sub_14018D8B0),
 // shapes become .mdl-like meshes drawn by model layers with the token
-namespace ModelData {
-    /** Vertex format bits a script can use (scenescript64 sub_18162FD40) */
-    constexpr uint32_t FORMAT_POSITION = 0x1;
-    constexpr uint32_t FORMAT_NORMAL = 0x2;
-    constexpr uint32_t FORMAT_TANGENT_SIGNED = 0x4;
-    constexpr uint32_t FORMAT_UV = 0x8;
-    constexpr uint32_t FORMAT_COLOR = 0x8000;
+namespace WallpaperEngine::Render::ModelData {
+/** Vertex format bits a script can use (scenescript64 sub_18162FD40) */
+constexpr uint32_t FORMAT_POSITION = 0x1;
+constexpr uint32_t FORMAT_NORMAL = 0x2;
+constexpr uint32_t FORMAT_TANGENT_SIGNED = 0x4;
+constexpr uint32_t FORMAT_UV = 0x8;
+constexpr uint32_t FORMAT_COLOR = 0x8000;
 
-    /** The error codes of the engine calls, scenescript64 turns them into these SyntaxError messages */
-    enum class Error : int {
-	None = 0,
-	InvalidMaterial = 1,
-	ShaderExpectingMoreVertexData = 2,
-	InconsistentVertexBufferSize = 3,
-	InvalidToken = 4,
-	VertexBufferSizeCannotIncrease = 5,
-	IndexBufferSizeCannotIncrease = 6,
-	NotCreatedAsDynamic = 7,
-	BufferLockFailed = 8,
-	IncorrectIndexBufferType = 9,
-	CannotAddShapes = 10,
-	CannotDeleteShapes = 11,
-	CannotChangeMaterial = 12,
-	CannotChangeVertexFormat = 13,
-    };
+/** The error codes of the engine calls, scenescript64 turns them into these SyntaxError messages */
+enum class Error : int {
+    None = 0,
+    InvalidMaterial = 1,
+    ShaderExpectingMoreVertexData = 2,
+    InconsistentVertexBufferSize = 3,
+    InvalidToken = 4,
+    VertexBufferSizeCannotIncrease = 5,
+    IndexBufferSizeCannotIncrease = 6,
+    NotCreatedAsDynamic = 7,
+    BufferLockFailed = 8,
+    IncorrectIndexBufferType = 9,
+    CannotAddShapes = 10,
+    CannotDeleteShapes = 11,
+    CannotChangeMaterial = 12,
+    CannotChangeVertexFormat = 13,
+};
 
-    [[nodiscard]] const char* errorMessage (Error error);
+[[nodiscard]] const char* errorMessage (Error error);
 
-    /** One shape of a script configuration (scenescript64's 304 byte shape record, sub_181630720) */
-    struct ShapeConfig {
-	std::vector<float> vertices;
-	bool hasVertices = false;
-	std::vector<uint32_t> indices32;
-	std::vector<uint16_t> indices16;
-	bool hasIndices32 = false;
-	bool hasIndices16 = false;
-	bool deleteIndices = false;
-	uint32_t format = 0;
-	std::string material;
-	bool vertexDynamic = false;
-	bool indexDynamic = false;
-	/** the shape itself was null (replaceData deletes it) */
-	bool deleteShape = false;
+/** One shape of a script configuration (scenescript64's 304 byte shape record, sub_181630720) */
+struct ShapeConfig {
+    std::vector<float> vertices;
+    bool hasVertices = false;
+    std::vector<uint32_t> indices32;
+    std::vector<uint16_t> indices16;
+    bool hasIndices32 = false;
+    bool hasIndices16 = false;
+    bool deleteIndices = false;
+    uint32_t format = 0;
+    std::string material;
+    bool vertexDynamic = false;
+    bool indexDynamic = false;
+    /** the shape itself was null (replaceData deletes it) */
+    bool deleteShape = false;
 
-	[[nodiscard]] bool hasIndices () const { return this->hasIndices32 || this->hasIndices16; }
-	[[nodiscard]] uint32_t indexCount () const {
-	    return static_cast<uint32_t> (this->hasIndices32 ? this->indices32.size () : this->indices16.size ());
-	}
-    };
+    [[nodiscard]] bool hasIndices () const { return this->hasIndices32 || this->hasIndices16; }
+    [[nodiscard]] uint32_t indexCount () const {
+	return static_cast<uint32_t> (this->hasIndices32 ? this->indices32.size () : this->indices16.size ());
+    }
+};
 
-    struct Config {
-	std::vector<ShapeConfig> shapes;
-	std::optional<glm::vec3> boundsMin;
-	std::optional<glm::vec3> boundsMax;
-    };
+struct Config {
+    std::vector<ShapeConfig> shapes;
+    std::optional<glm::vec3> boundsMin;
+    std::optional<glm::vec3> boundsMax;
+};
 
-    /** A mesh with its GPU buffer record: the 200 byte mesh (sub_1401C2F10) and the 32 byte buffer entry of WE's model
-     */
-    struct Mesh {
-	std::string material;
-	uint32_t format = 0;
-	uint32_t stride = 0;
-	/** buffer +18 */
-	bool indexed = false;
-	/** mesh flag 1, 32 bit indices */
-	bool wideIndices = false;
-	/** buffer +16 / +17 */
-	bool vertexDynamic = false;
-	bool indexDynamic = false;
-	/** buffer +8 / +12: float and index counts the buffers were created with */
-	uint32_t vertexFloats = 0;
-	uint32_t indexCount = 0;
-	std::vector<char> vertices;
-	std::vector<char> indices;
-	/** bumped whenever applyData writes into the buffers */
-	uint64_t revision = 0;
-    };
+/** A mesh with its GPU buffer record: the 200 byte mesh (sub_1401C2F10) and the 32 byte buffer entry of WE's model
+ */
+struct Mesh {
+    std::string material;
+    uint32_t format = 0;
+    uint32_t stride = 0;
+    /** buffer +18 */
+    bool indexed = false;
+    /** mesh flag 1, 32 bit indices */
+    bool wideIndices = false;
+    /** buffer +16 / +17 */
+    bool vertexDynamic = false;
+    bool indexDynamic = false;
+    /** buffer +8 / +12: float and index counts the buffers were created with */
+    uint32_t vertexFloats = 0;
+    uint32_t indexCount = 0;
+    std::vector<char> vertices;
+    std::vector<char> indices;
+    /** bumped whenever applyData writes into the buffers */
+    uint64_t revision = 0;
+};
 
-    struct Model {
-	uint32_t token = 0;
-	/** +560: the script handle and every layer using it hold one */
-	int references = 1;
-	std::vector<Mesh> meshes;
-	glm::vec3 boundsMin = glm::vec3 (0.0f);
-	glm::vec3 boundsMax = glm::vec3 (0.0f);
-	/** bumped when replaceData changes meshes, the layers using it rebuild (the listeners sub_1401D6400 calls) */
-	uint64_t structure = 0;
-    };
+struct Model {
+    uint32_t token = 0;
+    /** +560: the script handle and every layer using it hold one */
+    int references = 1;
+    std::vector<Mesh> meshes;
+    glm::vec3 boundsMin = glm::vec3 (0.0f);
+    glm::vec3 boundsMax = glm::vec3 (0.0f);
+    /** bumped when replaceData changes meshes, the layers using it rebuild (the listeners sub_1401D6400 calls) */
+    uint64_t structure = 0;
+};
 
-    using MaterialCheck = std::function<Error (const std::string& material, uint32_t format)>;
+using MaterialCheck = std::function<Error (const std::string& material, uint32_t format)>;
 
-    class Store {
-    public:
-	/** sub_14018C720, 0 and error set on failure */
-	uint32_t create (const Config& config, const MaterialCheck& check, Error& error);
-	/** sub_1401D6400: applyData (replace false) or replaceData */
-	void apply (uint32_t token, const Config& config, bool replace, const MaterialCheck& check, Error& error);
-	/** sub_14018D8B0: drops one reference */
-	void release (uint32_t token);
-	/** A layer takes a reference (sub_14021AD10), nullptr for an unknown token */
-	std::shared_ptr<Model> acquire (int token);
+class Store {
+public:
+    /** sub_14018C720, 0 and error set on failure */
+    uint32_t create (const Config& config, const MaterialCheck& check, Error& error);
+    /** sub_1401D6400: applyData (replace false) or replaceData */
+    void apply (uint32_t token, const Config& config, bool replace, const MaterialCheck& check, Error& error);
+    /** sub_14018D8B0: drops one reference */
+    void release (uint32_t token);
+    /** A layer takes a reference (sub_14021AD10), nullptr for an unknown token */
+    std::shared_ptr<Model> acquire (int token);
 
-    private:
-	std::map<uint32_t, std::shared_ptr<Model>> m_models;
-	/** scene +7224, zeroed with the scene, the first token is 1 */
-	uint32_t m_counter = 0;
-    };
-}
+private:
+    std::map<uint32_t, std::shared_ptr<Model>> m_models;
+    /** scene +7224, zeroed with the scene, the first token is 1 */
+    uint32_t m_counter = 0;
+};
 }

+ 133 - 47
src/WallpaperEngine/Render/Objects/CImage.cpp

@@ -12,6 +12,7 @@
 #include <algorithm>
 #include <array>
 #include <bit>
+#include <chrono>
 #include <cmath>
 #include <cstdlib>
 #include <cstring>
@@ -103,7 +104,7 @@ std::optional<PuppetBlendMesh> readPuppetBlendMesh (const std::vector<char>& dat
     PuppetFileReader reader (data, 0);
     reader.string ();
 
-    const int version = std::atoi (data.data () + strlen ("MDLV"));
+    const int version = static_cast<int> (std::strtol (data.data () + strlen ("MDLV"), nullptr, 10));
 
     if (version < 4) {
 	return std::nullopt;
@@ -417,6 +418,15 @@ CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
 	height = 1.0f;
     }
 
+    this->m_lastUploadedCover = this->userTextureRect (size);
+
+    if (this->m_lastUploadedCover.has_value ()) {
+	x = this->m_lastUploadedCover->x;
+	y = this->m_lastUploadedCover->y;
+	width = this->m_lastUploadedCover->z;
+	height = this->m_lastUploadedCover->w;
+    }
+
     GLfloat realWidth = size.x;
     GLfloat realHeight = size.y;
     GLfloat realX = 0.0;
@@ -781,13 +791,15 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 	glGenBuffers (1, &this->m_puppetTexCoord);
 	glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetTexCoord);
 	glBufferData (
-	    GL_ARRAY_BUFFER, mesh->texcoords.size () * sizeof (GLfloat), mesh->texcoords.data (), GL_STATIC_DRAW
+	    GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (mesh->texcoords.size () * sizeof (GLfloat)),
+	    mesh->texcoords.data (), GL_STATIC_DRAW
 	);
 
 	glGenBuffers (1, &this->m_puppetIndices);
 	glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
 	glBufferData (
-	    GL_ELEMENT_ARRAY_BUFFER, mesh->indices.size () * sizeof (GLushort), mesh->indices.data (), GL_STATIC_DRAW
+	    GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr> (mesh->indices.size () * sizeof (GLushort)),
+	    mesh->indices.data (), GL_STATIC_DRAW
 	);
 
 	this->m_puppetIndexCount = static_cast<GLsizei> (mesh->indices.size ());
@@ -841,8 +853,8 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 		glGenBuffers (1, &this->m_puppetClipIndices);
 		glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipIndices);
 		glBufferData (
-		    GL_ELEMENT_ARRAY_BUFFER, clipping->indices.size () * sizeof (GLushort), clipping->indices.data (),
-		    GL_STATIC_DRAW
+		    GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr> (clipping->indices.size () * sizeof (GLushort)),
+		    clipping->indices.data (), GL_STATIC_DRAW
 		);
 		sLog.out (
 		    "Puppet ", *this->getImage ().model->puppet, " clipping: ", clipping->records.size (), " masks, ",
@@ -964,31 +976,12 @@ void CImage::updatePuppetPositionBuffer (const glm::vec2& size) {
 	glGenBuffers (1, &this->m_puppetSpacePosition);
     }
     glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetSpacePosition);
-    glBufferData (GL_ARRAY_BUFFER, positions.size () * sizeof (GLfloat), positions.data (), GL_DYNAMIC_DRAW);
-}
-
-PuppetActiveAnimation* CImage::findPuppetAnimationLayer (size_t serial) { return this->m_rig.findLayer (serial); }
-
-size_t CImage::getPuppetAnimationLayerCount () const { return this->m_rig.getLayerCount (); }
-
-std::optional<size_t> CImage::getPuppetAnimationLayerAt (int64_t index) const { return this->m_rig.getLayerAt (index); }
-
-std::optional<size_t> CImage::findPuppetAnimationLayerByName (const std::string& name) const {
-    return this->m_rig.findLayerByName (name);
-}
-
-std::optional<size_t> CImage::createPuppetAnimationLayer (
-    const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove
-) {
-    return this->m_rig.createLayer (animation, config, autoRemove, this->getScene ().getScene ().project);
-}
-
-bool CImage::destroyPuppetAnimationLayersByName (const std::string& name) {
-    return this->m_rig.destroyLayersByName (name);
+    glBufferData (
+	GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (positions.size () * sizeof (GLfloat)), positions.data (),
+	GL_DYNAMIC_DRAW
+    );
 }
 
-bool CImage::destroyPuppetAnimationLayer (size_t serial) { return this->m_rig.destroyLayer (serial); }
-
 void CImage::updatePuppetPose () {
     if (!this->m_hasPuppetMesh || this->m_rig.bones.empty ()) {
 	return;
@@ -1037,7 +1030,8 @@ void CImage::updatePuppetDrawOrder () {
 	this->m_puppetClipping->build (this->m_puppetMeshIndices);
 	glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipIndices);
 	glBufferData (
-	    GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipping->indices.size () * sizeof (GLushort),
+	    GL_ELEMENT_ARRAY_BUFFER,
+	    static_cast<GLsizeiptr> (this->m_puppetClipping->indices.size () * sizeof (GLushort)),
 	    this->m_puppetClipping->indices.data (), GL_DYNAMIC_DRAW
 	);
 
@@ -1056,7 +1050,10 @@ void CImage::updatePuppetDrawOrder () {
     }
 
     glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
-    glBufferData (GL_ELEMENT_ARRAY_BUFFER, indices.size () * sizeof (GLushort), indices.data (), GL_DYNAMIC_DRAW);
+    glBufferData (
+	GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr> (indices.size () * sizeof (GLushort)), indices.data (),
+	GL_DYNAMIC_DRAW
+    );
     this->m_puppetIndexCount = static_cast<GLsizei> (indices.size ());
     this->m_puppetDrawCount = this->m_puppetIndexCount;
 }
@@ -1217,8 +1214,8 @@ void CImage::updatePuppetSkinning () {
 	if (prelightMorphs) {
 	    glBindBuffer (GL_ARRAY_BUFFER, prelight.morphedPositions);
 	    glBufferData (
-		GL_ARRAY_BUFFER, prelight.morphedData.size () * sizeof (GLfloat), prelight.morphedData.data (),
-		GL_DYNAMIC_DRAW
+		GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (prelight.morphedData.size () * sizeof (GLfloat)),
+		prelight.morphedData.data (), GL_DYNAMIC_DRAW
 	    );
 	}
     }
@@ -1260,7 +1257,7 @@ void CImage::updatePuppetVertexAlpha (const std::vector<float>& morphAlpha) {
 
     glBindBuffer (GL_ARRAY_BUFFER, this->m_puppetVertexAlphaWeights);
     glBufferData (
-	GL_ARRAY_BUFFER, this->m_puppetVertexAlphaData.size () * sizeof (GLfloat),
+	GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (this->m_puppetVertexAlphaData.size () * sizeof (GLfloat)),
 	this->m_puppetVertexAlphaData.data (), GL_DYNAMIC_DRAW
     );
 }
@@ -3174,9 +3171,9 @@ const glm::vec3& CImage::getColor () const {
     return m_colorCache;
 }
 
-bool CImage::showsUserTextureOnSolidLayer () const {
+const std::string* CImage::userTextureValue () const {
     if (!this->m_image.model->solidlayer || this->m_image.model->material->passes.empty ()) {
-	return false;
+	return nullptr;
     }
 
     const auto& properties = this->getScene ().getScene ().project.properties;
@@ -3187,13 +3184,15 @@ bool CImage::showsUserTextureOnSolidLayer () const {
 	}
 	if (it != properties.end () && !it->second->is<Data::Model::PropertyUserShortcut> ()
 	    && !it->second->getString ().empty ()) {
-	    return true;
+	    return &it->second->getString ();
 	}
     }
 
-    return false;
+    return nullptr;
 }
 
+bool CImage::showsUserTextureOnSolidLayer () const { return this->userTextureValue () != nullptr; }
+
 const glm::vec4& CImage::getColor4 () const {
     // "version" 2 materials take color and alpha together through g_Color4
     m_color4Cache = glm::vec4 (this->getColor (), this->getAlpha ());
@@ -3215,20 +3214,87 @@ void CImage::fillMissingSize (glm::vec2& size) const {
     }
 }
 
-glm::vec2 CImage::textureUvScale () const {
-    const auto& texture = this->getTexture ();
+std::optional<glm::vec4> CImage::userTextureRect (const glm::vec2& layer) const {
+    const std::string* value = this->userTextureValue ();
+
+    if (value == nullptr) {
+	return std::nullopt;
+    }
+
+    // the answer only changes with the pick, the layer's size and the image's size (a video or a media cover brings
+    // its own later); a failed load is tried again now and then, not every frame
+    auto& cache = this->m_coverCache;
+
+    if (cache.settled && cache.value == *value && cache.layer == layer) {
+	if (cache.texture != nullptr) {
+	    if (cache.texture->getRealWidth () == cache.width && cache.texture->getRealHeight () == cache.height) {
+		return cache.rect;
+	    }
+	} else if (std::chrono::steady_clock::now () < cache.retryAt) {
+	    return std::nullopt;
+	}
+    }
+
+    cache = {};
+    cache.value = *value;
+    cache.layer = layer;
+    cache.settled = true;
+
+    try {
+	cache.texture = this->getContext ().resolveTexture (*value, this->getScene ().getScene ().project);
+    } catch (const std::runtime_error&) {
+	cache.retryAt = std::chrono::steady_clock::now () + std::chrono::seconds (2);
+	return std::nullopt;
+    }
+
+    const auto& texture = cache.texture;
+
+    // a video has no size before its first frame, the next frame asks again
+    if (texture == nullptr || texture->getRealWidth () == 0 || texture->getRealHeight () == 0) {
+	cache.settled = false;
+	return std::nullopt;
+    }
+
+    cache.width = texture->getRealWidth ();
+    cache.height = texture->getRealHeight ();
+
+    if (layer.x <= 0.0f || layer.y <= 0.0f) {
+	return std::nullopt;
+    }
 
-    if (texture == nullptr || texture->isAnimated ()) {
+    // WE scales the image to cover the layer, keeping its aspect, the part that sticks out is cut off evenly
+    const float textureAspect = static_cast<float> (cache.width) / static_cast<float> (cache.height);
+    const float layerAspect = layer.x / layer.y;
+    const glm::vec2 cover = textureAspect > layerAspect ? glm::vec2 (layerAspect / textureAspect, 1.0f)
+							: glm::vec2 (1.0f, textureAspect / layerAspect);
+    const glm::vec2 uvScale = uvScaleOf (*texture);
+
+    cache.rect = glm::vec4 (
+	0.5f * (1.0f - cover.x) * uvScale.x, 0.5f * (1.0f - cover.y) * uvScale.y, 0.5f * (1.0f + cover.x) * uvScale.x,
+	0.5f * (1.0f + cover.y) * uvScale.y
+    );
+
+    return cache.rect;
+}
+
+glm::vec2 CImage::uvScaleOf (const TextureProvider& texture) {
+    if (texture.isAnimated ()) {
 	return { 1.0f, 1.0f };
     }
 
-    if (texture->getTextureWidth (0) == texture->getRealWidth ()
-	&& texture->getTextureHeight (0) == texture->getRealHeight ()) {
+    if (texture.getTextureWidth (0) == texture.getRealWidth ()
+	&& texture.getTextureHeight (0) == texture.getRealHeight ()) {
 	return { 1.0f, 1.0f };
     }
 
-    return { static_cast<float> (texture->getRealWidth ()) / static_cast<float> (texture->getTextureWidth (0)),
-	     static_cast<float> (texture->getRealHeight ()) / static_cast<float> (texture->getTextureHeight (0)) };
+    return { static_cast<float> (texture.getRealWidth ()) / static_cast<float> (texture.getTextureWidth (0)),
+	     static_cast<float> (texture.getRealHeight ()) / static_cast<float> (texture.getTextureHeight (0)) };
+}
+
+glm::vec2 CImage::textureUvScale () const {
+    const auto& texture = this->getTexture ();
+
+    return texture == nullptr ? glm::vec2 (1.0f) : uvScaleOf (*texture);
 }
 
 glm::vec2 CImage::resolveGeometrySize () const {
@@ -3269,12 +3335,24 @@ void CImage::uploadGeometryBuffers (const glm::vec2& size) {
 
     float x = 0.0f;
     float y = 0.0f;
+
+    this->m_lastUploadedCover = this->userTextureRect (size);
+
+    if (this->m_lastUploadedCover.has_value ()) {
+	x = this->m_lastUploadedCover->x;
+	y = this->m_lastUploadedCover->y;
+	width = this->m_lastUploadedCover->z;
+	height = this->m_lastUploadedCover->w;
+    }
+
     GLfloat realWidth = size.x;
     GLfloat realHeight = size.y;
     GLfloat realX = 0.0f;
     GLfloat realY = 0.0f;
 
     if (this->getImage ().model->passthrough) {
+	x = 0.0f;
+	y = 0.0f;
 	width = 1.0f;
 	height = 1.0f;
 	realX = this->m_pos.x;
@@ -3372,7 +3450,11 @@ void CImage::updateGeometryBuffers () {
     this->m_size = size;
     this->updateScenePosition (size);
 
-    if (this->m_pos != this->m_lastUploadedPos || size != this->m_lastUploadedGeometrySize) {
+    // the crop follows the picked image and the layer's size, not only the quad
+    const auto cover = this->userTextureRect (size);
+
+    if (this->m_pos != this->m_lastUploadedPos || size != this->m_lastUploadedGeometrySize
+	|| cover != this->m_lastUploadedCover) {
 	this->uploadGeometryBuffers (size);
 	if (this->m_hasPuppetMesh) {
 	    this->updatePuppetPositionBuffer (size);
@@ -3389,7 +3471,11 @@ void CImage::updateScreenSpacePosition () {
     const auto& scene = this->getScene ();
     const glm::mat4 flipY = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f));
     const glm::mat4 toScene = flipY
-	* glm::translate (glm::mat4 (1.0f), glm::vec3 (-scene.getWidth () / 2.0f, -scene.getHeight () / 2.0f, 0.0f));
+	* glm::translate (glm::mat4 (1.0f),
+			  glm::vec3 (
+			      static_cast<float> (-scene.getWidth ()) / 2.0f,
+			      static_cast<float> (-scene.getHeight ()) / 2.0f, 0.0f
+			  ));
     const glm::mat4 objectModel = this->worldMatrix () * flipY;
     glm::mat4 rotModel = toScene * objectModel;
 
@@ -3497,7 +3583,7 @@ void CImage::updateLightingTransform (
 
     // WE's normal matrix: model rows at unit length (sub_1400D8300)
     const auto inverseLength = [] (const float squared) {
-	const float estimate = std::bit_cast<float> (0x5F375A86u - (std::bit_cast<uint32_t> (squared) >> 1));
+	const auto estimate = std::bit_cast<float> (0x5F375A86u - (std::bit_cast<uint32_t> (squared) >> 1));
 	return (1.5f - squared * 0.5f * estimate * estimate) * estimate;
     };
     const glm::mat3 normal

+ 19 - 14
src/WallpaperEngine/Render/Objects/CImage.h

@@ -13,6 +13,7 @@
 #include "PuppetRig.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
 
+#include <chrono>
 #include <glm/gtc/quaternion.hpp>
 #include <glm/mat4x4.hpp>
 #include <glm/vec3.hpp>
@@ -138,20 +139,6 @@ public:
     void setPuppetLocalBoneTransform (int bone, const glm::mat4& transform);
     void applyPuppetBonePhysicsImpulse (int bone, const glm::vec3& directional, const glm::vec3& angularDegrees);
     void resetPuppetBonePhysics (int bone);
-    /** The animation layer with this serial for IAnimationLayer scripts, null once destroyed or when a scene layer
-     *  plays no clip (WE never creates such a layer) */
-    [[nodiscard]] PuppetActiveAnimation* findPuppetAnimationLayer (size_t serial);
-    /**
-     * IImageLayer animation layer calls (wallpaper64 2.8.42 sub_14020E910..sub_14020EF80), on the layer list in blend
-     * order. Serials identify layers, nullopt when there is none
-     */
-    [[nodiscard]] size_t getPuppetAnimationLayerCount () const;
-    [[nodiscard]] std::optional<size_t> getPuppetAnimationLayerAt (int64_t index) const;
-    [[nodiscard]] std::optional<size_t> findPuppetAnimationLayerByName (const std::string& name) const;
-    std::optional<size_t>
-    createPuppetAnimationLayer (const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove);
-    bool destroyPuppetAnimationLayersByName (const std::string& name);
-    bool destroyPuppetAnimationLayer (size_t serial);
 
     // ITextureAnimation (2.8.42 sub_14020E670): a layer's own clock for its animated texture; pause, stop, setFrame and
     // rate != 1 detach it from the shared clock, join reattaches
@@ -224,6 +211,12 @@ private:
     [[nodiscard]] glm::vec2 resolveGeometrySize () const;
     void fillMissingSize (glm::vec2& size) const;
     [[nodiscard]] glm::vec2 textureUvScale () const;
+    [[nodiscard]] static glm::vec2 uvScaleOf (const TextureProvider& texture);
+    /** uv corners (u0, v0, u1, v1) of the user image a solid layer shows, cropped to cover the layer; none when it
+     * shows no (usable) image */
+    [[nodiscard]] std::optional<glm::vec4> userTextureRect (const glm::vec2& layer) const;
+    /** the user image a solid layer shows, null when it shows none; points into the property */
+    [[nodiscard]] const std::string* userTextureValue () const;
     void updateScenePosition (const glm::vec2& size);
     void uploadGeometryBuffers (const glm::vec2& size);
     void uploadShapePointMesh (const glm::vec2& size);
@@ -400,6 +393,18 @@ private:
     // last m_pos/size uploaded to the GL geometry buffers; NaN forces the first upload
     glm::vec4 m_lastUploadedPos = glm::vec4 (std::numeric_limits<float>::quiet_NaN ());
     glm::vec2 m_lastUploadedGeometrySize = glm::vec2 (std::numeric_limits<float>::quiet_NaN ());
+    std::optional<glm::vec4> m_lastUploadedCover;
+    struct CoverCache {
+	std::string value;
+	glm::vec2 layer { 0.0f };
+	bool settled = false;
+	std::shared_ptr<const TextureProvider> texture;
+	uint32_t width = 0;
+	uint32_t height = 0;
+	std::optional<glm::vec4> rect;
+	std::chrono::steady_clock::time_point retryAt;
+    };
+    mutable CoverCache m_coverCache;
 
     bool m_initialized = false;
     bool m_isDependency = false;

+ 25 - 6
src/WallpaperEngine/Render/Objects/CMesh.cpp

@@ -114,7 +114,8 @@ public:
 	}
 
 	std::vector<char> value (
-	    this->m_data.begin () + this->m_offset, this->m_data.begin () + this->m_offset + count
+	    this->m_data.begin () + static_cast<long> (this->m_offset),
+	    this->m_data.begin () + static_cast<long> (this->m_offset) + static_cast<long> (count)
 	);
 	this->m_offset += count;
 	return value;
@@ -171,7 +172,7 @@ public:
     [[nodiscard]] const std::vector<FrameSharedPtr>& getFrames () const override { return this->m_frames; }
     [[nodiscard]] const glm::vec4* getResolution () const override { return &this->m_resolution; }
     [[nodiscard]] bool isAnimated () const override { return false; }
-    bool isReady () const override { return true; }
+    [[nodiscard]] bool isReady () const override { return true; }
     void incrementUsageCount () const override { }
     void decrementUsageCount () const override { }
     void update () const override { }
@@ -220,10 +221,12 @@ std::vector<MdlMesh> readMdlMeshes (
 
 	meshFlags.push_back (mesh.flags);
 	mesh.vertices.assign (
-	    data.begin () + record.vertices.first, data.begin () + record.vertices.first + record.vertices.second
+	    data.begin () + static_cast<long> (record.vertices.first),
+	    data.begin () + static_cast<long> (record.vertices.first) + record.vertices.second
 	);
 	mesh.indices.assign (
-	    data.begin () + record.indices.first, data.begin () + record.indices.first + record.indices.second
+	    data.begin () + static_cast<long> (record.indices.first),
+	    data.begin () + static_cast<long> (record.indices.first) + record.indices.second
 	);
 
 	if (mesh.stride == 0 || mesh.vertices.size () % mesh.stride != 0) {
@@ -361,7 +364,12 @@ public:
 	m_owner (owner), m_mesh (std::move (mesh)), m_source (source),
 	m_sourceRevision (source != nullptr ? source->revision : 0) { }
 
+    /** the material the registered values live in goes away with the part, scripts and animations must let go first */
     ~Part () override {
+	for (const auto& name : this->m_scriptProperties) {
+	    this->m_owner.unregisterProperty (name);
+	}
+
 	for (const auto* pass : this->m_passes) {
 	    delete pass;
 	}
@@ -424,6 +432,8 @@ public:
 	    this->m_skinning.combos["MORPHING_NORMALS"] = 1;
 	}
 
+	const int partSerial = this->m_owner.m_partSerial++;
+
 	for (const auto& materialPass : this->m_material.passes) {
 	    std::optional<std::reference_wrapper<const ImageEffectPassOverride>> skinning = std::nullopt;
 
@@ -434,6 +444,14 @@ public:
 	    auto* pass
 		= new Effects::CPass (*this, this->m_fboProvider, *materialPass, skinning, std::nullopt, std::nullopt);
 
+	    // a material constant with a keyframe animation or a script (block_flash on a ? block's yellow material)
+	    // runs like an effect constant of an image
+	    const std::string passPrefix
+		= "material" + std::to_string (partSerial) + ".p" + std::to_string (this->m_passes.size ()) + ".";
+	    for (auto& property : this->m_owner.registerPassConstants (passPrefix, materialPass->constants)) {
+		this->m_scriptProperties.push_back (std::move (property));
+	    }
+
 	    pass->setDestination (this->getScene ().getFBO ());
 	    pass->setInput (this->getTexture ());
 
@@ -652,7 +670,7 @@ private:
 	    }
 
 	    const char* name = nullptr;
-	    GLint elements = static_cast<GLint> (component.size / sizeof (float));
+	    auto elements = static_cast<GLint> (component.size / sizeof (float));
 
 	    switch (component.bit) {
 		case FORMAT_POSITION:
@@ -714,6 +732,7 @@ private:
     GLsizei m_vertexCount = 0;
     std::shared_ptr<FBOProvider> m_fboProvider = nullptr;
     std::vector<Effects::CPass*> m_passes = {};
+    std::vector<std::string> m_scriptProperties;
     std::vector<GLuint> m_vaos = {};
     GLuint m_casterVAO = GL_NONE;
     GLuint m_vbo = GL_NONE;
@@ -1036,7 +1055,7 @@ void CMesh::updateMatrices () {
     // WE scales each axis of the model matrix to unit length with a fast inverse square root (uniform setter
     // sub_1400D8300 case 0xE), so non-uniform scale doesn't stretch the normals and tangents (3734636606's floor)
     const auto inverseLength = [] (const float squared) {
-	const float estimate = std::bit_cast<float> (0x5F375A86u - (std::bit_cast<uint32_t> (squared) >> 1));
+	const auto estimate = std::bit_cast<float> (0x5F375A86u - (std::bit_cast<uint32_t> (squared) >> 1));
 	return (1.5f - squared * 0.5f * estimate * estimate) * estimate;
     };
 

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

@@ -88,6 +88,7 @@ private:
     const Mesh& m_mesh;
     std::vector<MaterialUniquePtr> m_materials;
     std::vector<std::unique_ptr<Part>> m_parts;
+    int m_partSerial = 0;
 
     glm::mat4 m_modelMatrix = glm::mat4 (1.0f);
     glm::mat3 m_normalMatrix = glm::mat3 (1.0f);

+ 180 - 80
src/WallpaperEngine/Render/Objects/CParticle.cpp

@@ -76,6 +76,29 @@ CParticle::CParticle (Wallpapers::CScene& scene, const Particle& particle) :
     this->registerProperty ("visible", *particle.visible->value);
     this->registerProperty ("parallaxDepth", *particle.parallaxDepth->value);
 
+    // scripts on the instance override keys run like on any other property (property table sub_14024D940), the
+    // particle reads the values live
+    const auto bindOverride = [this] (const std::string& name, const UserSettingUniquePtr& setting) {
+	if (setting != nullptr) {
+	    this->registerProperty ("instanceoverride." + name, *setting->value);
+	}
+    };
+    const auto& instanceOverride = particle.instanceOverride;
+
+    bindOverride ("alpha", instanceOverride.alpha);
+    bindOverride ("size", instanceOverride.size);
+    bindOverride ("lifetime", instanceOverride.lifetime);
+    bindOverride ("rate", instanceOverride.rate);
+    bindOverride ("speed", instanceOverride.speed);
+    bindOverride ("count", instanceOverride.count);
+    bindOverride ("brightness", instanceOverride.brightness);
+    bindOverride ("colorn", instanceOverride.colorn);
+
+    for (size_t i = 0; i < instanceOverride.controlPoints.size (); i++) {
+	bindOverride ("controlpoint" + std::to_string (i), instanceOverride.controlPoints[i]);
+	bindOverride ("controlpointangle" + std::to_string (i), instanceOverride.controlPointAngles[i]);
+    }
+
     this->detectTexture ();
     m_worldSpace = (particle.flags & 1) != 0;
     if (std::getenv ("LWE_FIXED_TIMESTEP") != nullptr) {
@@ -107,6 +130,16 @@ CParticle::CParticle (Wallpapers::CScene& scene, const Particle& particle) :
 	    m_trailLength = renderer.length;
 	    m_trailMaxLength = renderer.maxLength;
 	    m_trailMinLength = renderer.minLength;
+	} else {
+	    for (size_t i = 1; i < m_particle.renderers.size (); i++) {
+		if (const auto& extra = m_particle.renderers[i]; extra.name == "spritetrail") {
+		    m_hasTrailPass = true;
+		    m_extraTrailLength = extra.length;
+		    m_extraTrailMaxLength = extra.maxLength;
+		    m_extraTrailMinLength = extra.minLength;
+		    break;
+		}
+	    }
 	}
     }
 
@@ -159,6 +192,11 @@ CParticle::CParticle (CParticle& parent, const ParticleChild& child) : CParticle
 
 CParticle::~CParticle () {
     delete m_pass;
+    delete m_trailPass;
+
+    if (m_trailVao != 0) {
+	glDeleteVertexArrays (1, &m_trailVao);
+    }
 
     if (m_vao != 0) {
 	glDeleteVertexArrays (1, &m_vao);
@@ -440,7 +478,7 @@ void CParticle::registerNewParticles (uint32_t firstNew) {
 	// sub_14023B340 end: a new particle's whole trail history starts where it spawned
 	if (!m_trailHistory.empty ()) {
 	    std::fill_n (
-		m_trailHistory.begin () + static_cast<size_t> (i) * m_ropeSegments, m_ropeSegments, p.position
+		m_trailHistory.begin () + static_cast<std::ptrdiff_t> (i) * m_ropeSegments, m_ropeSegments, p.position
 	    );
 	    m_trailCount[i] = 1;
 	    m_trailScroll[i] = 0;
@@ -487,8 +525,9 @@ void CParticle::update (float dt) {
 		m_particles[writeIdx] = m_particles[readIdx];
 		if (!m_trailHistory.empty ()) {
 		    std::copy_n (
-			m_trailHistory.begin () + static_cast<size_t> (readIdx) * m_ropeSegments, m_ropeSegments,
-			m_trailHistory.begin () + static_cast<size_t> (writeIdx) * m_ropeSegments
+			m_trailHistory.begin () + static_cast<std::ptrdiff_t> (readIdx) * m_ropeSegments,
+			m_ropeSegments,
+			m_trailHistory.begin () + static_cast<std::ptrdiff_t> (writeIdx) * m_ropeSegments
 		    );
 		    m_trailCount[writeIdx] = m_trailCount[readIdx];
 		    m_trailScroll[writeIdx] = m_trailScroll[readIdx];
@@ -571,7 +610,8 @@ void CParticle::update (float dt) {
 		    p.frame = static_cast<float> (dist (particleRng));
 		}
 	    } else {
-		p.frame = p.getLifetimePos () * m_particle.sequenceMultiplier * m_spritesheetFrames;
+		p.frame
+		    = p.getLifetimePos () * m_particle.sequenceMultiplier * static_cast<float> (m_spritesheetFrames);
 	    }
 	}
     }
@@ -583,7 +623,7 @@ void CParticle::update (float dt) {
 	if (m_trailTimer <= 0.0f) {
 	    m_trailTimer = m_trailInterval;
 	    for (uint32_t i = 0; i < m_particleCount; i++) {
-		const auto history = m_trailHistory.begin () + static_cast<size_t> (i) * m_ropeSegments;
+		const auto history = m_trailHistory.begin () + static_cast<std::ptrdiff_t> (i) * m_ropeSegments;
 		std::copy_backward (history, history + m_ropeSegments - 1, history + m_ropeSegments);
 		*history = m_particles[i].position;
 		m_trailCount[i] = static_cast<uint16_t> (std::min<int> (m_trailCount[i] + 1, m_ropeSegments));
@@ -687,7 +727,11 @@ glm::mat4 CParticle::sceneMatrix () const {
 
     return glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
 	* glm::translate (
-	       glm::mat4 (1.0f), glm::vec3 (-getScene ().getWidth () / 2.0f, -getScene ().getHeight () / 2.0f, 0.0f)
+	       glm::mat4 (1.0f),
+	       glm::vec3 (
+		   static_cast<float> (-getScene ().getWidth ()) / 2.0f,
+		   static_cast<float> (-getScene ().getHeight ()) / 2.0f, 0.0f
+	       )
 	);
 }
 
@@ -830,9 +874,10 @@ void CParticle::passControlPoints (CParticle& child, const ParticleChild& defini
     std::vector<uint32_t> order (m_particleCount);
     std::iota (order.begin (), order.end (), 0u);
     const size_t wanted = std::min<size_t> (order.size (), points.size () - index);
-    std::partial_sort (order.begin (), order.begin () + wanted, order.end (), [this] (uint32_t a, uint32_t b) {
-	return m_particles[a].slot < m_particles[b].slot;
-    });
+    std::partial_sort (
+	order.begin (), order.begin () + static_cast<long> (wanted), order.end (),
+	[this] (uint32_t a, uint32_t b) { return m_particles[a].slot < m_particles[b].slot; }
+    );
 
     for (size_t n = 0; n < wanted; n++) {
 	auto& cp = points[index];
@@ -1365,7 +1410,10 @@ void CParticle::downsampleLayerBuffer (ImageEmitter& state, const CFBO& buffer)
 
     for (int x = 0; x < columns; x++) {
 	for (int y = 0; y < rows; y++) {
-	    const glm::vec2 uv ((x + 0.5f) / columns, (y + 0.5f) / rows);
+	    const glm::vec2 uv (
+		(static_cast<float> (x) + 0.5f) / static_cast<float> (columns),
+		(static_cast<float> (y) + 0.5f) / static_cast<float> (rows)
+	    );
 	    glm::vec4 albedo = (source.sample (uv - step) + source.sample (uv + step)
 				+ source.sample (uv + glm::vec2 (-step.x, step.y))
 				+ source.sample (uv + glm::vec2 (step.x, -step.y)))
@@ -1380,8 +1428,12 @@ void CParticle::downsampleLayerBuffer (ImageEmitter& state, const CFBO& buffer)
 		{ .r = unorm (albedo.r),
 		  .g = unorm (albedo.g),
 		  .b = unorm (albedo.b),
-		  .x = static_cast<int16_t> (static_cast<int> (scale * x - (width >> 1) + scale * 0.5f)),
-		  .y = static_cast<int16_t> (static_cast<int> (scale * y - (height >> 1) + scale * 0.5f)) }
+		  .x = static_cast<int16_t> (static_cast<int> (
+		      scale * static_cast<float> (x) - static_cast<float> ((width >> 1)) + scale * 0.5f
+		  )),
+		  .y = static_cast<int16_t> (static_cast<int> (
+		      scale * static_cast<float> (y) - static_cast<float> ((height >> 1)) + scale * 0.5f
+		  )) }
 	    );
 	}
     }
@@ -1418,7 +1470,7 @@ bool CParticle::readImagePixels (ImageEmitter& state, const CObject& layer) {
     }
 
     if (state.stage == 0) {
-	this->downsampleLayerBuffer (state, *buffer);
+	WallpaperEngine::Render::Objects::CParticle::downsampleLayerBuffer (state, *buffer);
 	state.stage = 1;
 	return !state.pixels.empty ();
     }
@@ -1619,7 +1671,9 @@ EmitterFunc CParticle::createImageEmitter (const ParticleEmitter& emitter) {
 			= WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * offsetRange[axis] + offsetMin[axis];
 		}
 	    }
-	    const glm::vec4 local (pixel.x + offset.x, -pixel.y + offset.y, offset.z, 1.0f);
+	    const glm::vec4 local (
+		static_cast<float> (pixel.x) + offset.x, static_cast<float> (-pixel.y) + offset.y, offset.z, 1.0f
+	    );
 	    const bool moving = (emitter.flags & 0x40000) != 0 && m_frameDelta > 0.0f;
 	    const auto [pixelCurrent, pixelPrevious] = pixelFrames (pixel, moving);
 	    p.position = glm::vec3 (pixelCurrent * local);
@@ -3232,6 +3286,7 @@ InitializerFunc CParticle::createHsvColorRandomInitializer (const HsvColorRandom
 InitializerFunc CParticle::createColorListInitializer (const ColorListInitializer& init) {
     // sub_1401C5490 keeps the colors as HSV, an empty list is one pure red
     std::vector<glm::vec3> colors;
+    colors.reserve (init.colors.size ());
     for (const auto& color : init.colors) {
 	colors.push_back (WallpaperEngine::Maths::rgbToHsv (color));
     }
@@ -3608,41 +3663,38 @@ glm::vec3 CParticle::remapOperatorInput (const ParticleRemap& remap, const Parti
     // sub_14023FBC0 case 19, scalars in x
     switch (remap.input) {
 	case ParticleRemapValue::LifetimeFraction:
-	    return glm::vec3 (p.age / p.lifetime, 0.0f, 0.0f);
+	    return { p.age / p.lifetime, 0.0f, 0.0f };
 	case ParticleRemapValue::MaxLifetime:
-	    return glm::vec3 (p.lifetime, 0.0f, 0.0f);
+	    return { p.lifetime, 0.0f, 0.0f };
 	case ParticleRemapValue::Size:
-	    return glm::vec3 (p.size, 0.0f, 0.0f);
+	    return { p.size, 0.0f, 0.0f };
 	case ParticleRemapValue::Opacity:
-	    return glm::vec3 (p.alpha, 0.0f, 0.0f);
+	    return { p.alpha, 0.0f, 0.0f };
 	case ParticleRemapValue::Speed:
-	    return glm::vec3 (glm::length (p.velocity), 0.0f, 0.0f);
+	    return { glm::length (p.velocity), 0.0f, 0.0f };
 	case ParticleRemapValue::Rotation:
-	    return glm::vec3 (p.rotation.z, 0.0f, 0.0f);
+	    return { p.rotation.z, 0.0f, 0.0f };
 	case ParticleRemapValue::AngularSpeed:
-	    return glm::vec3 (m_hasAngularVelocity ? p.angularVelocity.z : 0.0f, 0.0f, 0.0f);
+	    return { m_hasAngularVelocity ? p.angularVelocity.z : 0.0f, 0.0f, 0.0f };
 	case ParticleRemapValue::DistanceToControlPoint:
-	    return glm::vec3 (
-		glm::length (p.position - m_controlPoints[remap.inputControlPoint0].position), 0.0f, 0.0f
-	    );
+	    return { glm::length (p.position - m_controlPoints[remap.inputControlPoint0].position), 0.0f, 0.0f };
 	case ParticleRemapValue::PositionBetweenTwoControlPoints:
 	    {
 		// the engine reads the output control points here, not the input ones
 		const glm::vec3 first = m_controlPoints[remap.outputControlPoint0].position;
 		const glm::vec3 line = m_controlPoints[remap.outputControlPoint1].position - first;
 		const float lengthSquared = glm::dot (line, line);
-		return glm::vec3 (
-		    lengthSquared > 0.0f ? glm::dot (p.position - first, line) / lengthSquared : 0.0f, 0.0f, 0.0f
-		);
+		return { lengthSquared > 0.0f ? glm::dot (p.position - first, line) / lengthSquared : 0.0f, 0.0f,
+			 0.0f };
 	    }
 	// runtime and particlesystemtime both read the renderer's scene clock here (+304)
 	case ParticleRemapValue::Runtime:
 	case ParticleRemapValue::ParticleSystemTime:
-	    return glm::vec3 (getScene ().getSceneClock (), 0.0f, 0.0f);
+	    return { getScene ().getSceneClock (), 0.0f, 0.0f };
 	case ParticleRemapValue::TimeOfDay:
-	    return glm::vec3 (dayFraction (), 0.0f, 0.0f);
+	    return { dayFraction (), 0.0f, 0.0f };
 	case ParticleRemapValue::LayerTime:
-	    return glm::vec3 (layerTime (), 0.0f, 0.0f);
+	    return { layerTime (), 0.0f, 0.0f };
 	case ParticleRemapValue::Color:
 	    return p.color;
 	case ParticleRemapValue::Position:
@@ -4497,8 +4549,8 @@ void CParticle::setupPass () {
     // registered under that name and blitted before each render
     if (m_hasRefract) {
 	auto sceneFBO = getScene ().getFBO ();
-	float w = static_cast<float> (sceneFBO->getRealWidth ());
-	float h = static_cast<float> (sceneFBO->getRealHeight ());
+	auto w = static_cast<float> (sceneFBO->getRealWidth ());
+	auto h = static_cast<float> (sceneFBO->getRealHeight ());
 	m_refractFBO = m_passFBOProvider->create (
 	    "_rt_FullFrameBuffer", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0f, { w, h }, { w, h }
 	);
@@ -4570,42 +4622,82 @@ void CParticle::setupPass () {
 	    glVertexAttribPointer (loc6, 4, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 22));
 	}
     } else {
-	// sprite vertex: a_Position (3), a_TexCoordVec4 (4), a_Color (4), a_TexCoordVec4C1 (4), a_TexCoordC2 (2) = 17
-	// floats
-	const GLsizei stride = sizeof (float) * SPRITE_FLOATS_PER_VERTEX;
+	this->setupSpriteAttributes (program);
+    }
 
-	const GLint loc0 = glGetAttribLocation (program, "a_Position");
-	const GLint loc1 = glGetAttribLocation (program, "a_TexCoordVec4");
-	const GLint loc2 = glGetAttribLocation (program, "a_Color");
-	const GLint loc3 = glGetAttribLocation (program, "a_TexCoordVec4C1");
-	const GLint loc4 = glGetAttribLocation (program, "a_TexCoordC2");
+    glBindVertexArray (prevVAO);
 
-	if (loc0 >= 0) {
-	    glEnableVertexAttribArray (loc0);
-	    glVertexAttribPointer (loc0, 3, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 0));
-	}
-	if (loc1 >= 0) {
-	    glEnableVertexAttribArray (loc1);
-	    glVertexAttribPointer (loc1, 4, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 3));
-	}
-	if (loc2 >= 0) {
-	    glEnableVertexAttribArray (loc2);
-	    glVertexAttribPointer (loc2, 4, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 7));
-	}
-	if (loc3 >= 0) {
-	    glEnableVertexAttribArray (loc3);
-	    glVertexAttribPointer (loc3, 4, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 11));
-	}
-	if (loc4 >= 0) {
-	    glEnableVertexAttribArray (loc4);
-	    glVertexAttribPointer (loc4, 2, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * 15));
+    setupGeometryCallbacks ();
+    setupParticleUniforms ();
+
+    if (m_hasTrailPass) {
+	this->setupTrailPass (firstPass);
+    }
+}
+
+void CParticle::setupSpriteAttributes (GLuint program) const {
+    // sprite vertex: a_Position (3), a_TexCoordVec4 (4), a_Color (4), a_TexCoordVec4C1 (4), a_TexCoordC2 (2)
+    const GLsizei stride = sizeof (float) * SPRITE_FLOATS_PER_VERTEX;
+    const struct {
+	const char* name;
+	GLint size;
+	size_t offset;
+    } attributes[] = { { "a_Position", 3, 0 },
+		       { "a_TexCoordVec4", 4, 3 },
+		       { "a_Color", 4, 7 },
+		       { "a_TexCoordVec4C1", 4, 11 },
+		       { "a_TexCoordC2", 2, 15 } };
+
+    for (const auto& attribute : attributes) {
+	if (const GLint location = glGetAttribLocation (program, attribute.name); location >= 0) {
+	    glEnableVertexAttribArray (location);
+	    glVertexAttribPointer (
+		location, attribute.size, GL_FLOAT, GL_FALSE, stride, (void*)(sizeof (float) * attribute.offset)
+	    );
 	}
     }
+}
+
+void CParticle::setupTrailPass (const MaterialPass& firstPass) {
+    // the particle's override only ever carries combos and a shader name
+    m_trailPassOverride = std::make_unique<ImageEffectPassOverride> ();
+    m_trailPassOverride->combos = m_passOverride->combos;
+    m_trailPassOverride->shaderOverride = m_passOverride->shaderOverride;
+    m_trailPassOverride->combos["TRAILRENDERER"] = 1;
 
+    m_trailPass
+	= new Effects::CPass (*this, m_passFBOProvider, firstPass, *m_trailPassOverride, m_passBinds, std::nullopt);
+    m_trailPass->setDestination (getScene ().getFBO ());
+    m_trailPass->setInput (getTexture ());
+    m_trailPass->setModelViewProjectionMatrix (&m_mvpMatrix);
+    m_trailPass->setModelViewProjectionMatrixInverse (&m_mvpMatrixInverse);
+    m_trailPass->setModelMatrix (&m_worldModelMatrix);
+    m_trailPass->setViewProjectionMatrix (&m_viewProjectionMatrix);
+
+    GLint prevVAO = 0;
+    glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &prevVAO);
+
+    glGenVertexArrays (1, &m_trailVao);
+    glBindVertexArray (m_trailVao);
+    glBindBuffer (GL_ARRAY_BUFFER, m_vbo);
+    glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, m_ebo);
+    this->setupSpriteAttributes (m_trailPass->getProgramID ());
     glBindVertexArray (prevVAO);
 
-    setupGeometryCallbacks ();
-    setupParticleUniforms ();
+    m_trailPass->setGeometryCallback (
+	[this] () {
+	    glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &m_trailPrevVAO);
+	    glBindVertexArray (m_trailVao);
+	    glFrontFace (GL_CW);
+	},
+	[this] () { glDrawElements (GL_TRIANGLES, m_activeIndexCount, GL_UNSIGNED_INT, nullptr); },
+	[this] () {
+	    glFrontFace (GL_CCW);
+	    glBindVertexArray (m_trailPrevVAO);
+	}
+    );
+
+    this->addParticleUniforms (*m_trailPass, &m_trailRenderVar0);
 }
 
 void CParticle::setupGeometryCallbacks () {
@@ -4630,20 +4722,22 @@ void CParticle::setupGeometryCallbacks () {
     );
 }
 
-void CParticle::setupParticleUniforms () {
+void CParticle::setupParticleUniforms () { this->addParticleUniforms (*m_pass, &m_renderVar0); }
+
+void CParticle::addParticleUniforms (Effects::CPass& pass, const glm::vec4* renderVar0) {
     // common_particles.h uniforms CPass doesn't provide, read every frame
-    m_pass->addUniform ("g_ModelMatrixInverse", &m_modelMatrixInverse);
-    m_pass->addUniform ("g_OrientationUp", &m_orientationUp);
-    m_pass->addUniform ("g_OrientationRight", &m_orientationRight);
-    m_pass->addUniform ("g_OrientationForward", &m_orientationForward);
-    m_pass->addUniform ("g_ViewUp", &m_viewUp);
-    m_pass->addUniform ("g_ViewRight", &m_viewRight);
-    m_pass->addUniform ("g_EyePosition", &m_eyePosition);
-    m_pass->addUniform ("g_RenderVar0", &m_renderVar0);
-    m_pass->addUniform ("g_RenderVar1", &m_renderVar1);
+    pass.addUniform ("g_ModelMatrixInverse", &m_modelMatrixInverse);
+    pass.addUniform ("g_OrientationUp", &m_orientationUp);
+    pass.addUniform ("g_OrientationRight", &m_orientationRight);
+    pass.addUniform ("g_OrientationForward", &m_orientationForward);
+    pass.addUniform ("g_ViewUp", &m_viewUp);
+    pass.addUniform ("g_ViewRight", &m_viewRight);
+    pass.addUniform ("g_EyePosition", &m_eyePosition);
+    pass.addUniform ("g_RenderVar0", renderVar0);
+    pass.addUniform ("g_RenderVar1", &m_renderVar1);
 
     if (m_hasRefract) {
-	m_pass->addUniform ("g_RefractAmount", &m_refractAmount);
+	pass.addUniform ("g_RefractAmount", &m_refractAmount);
     }
 }
 
@@ -4743,7 +4837,7 @@ void CParticle::updateParticleViewProjection () {
 void CParticle::updateParticleRenderVars () {
     if (m_useRopeRenderer && m_useTrailRenderer) {
 	// sub_1402366F0 renderer type 4: z is how far the history timer got, w the segment count the UVs span
-	const float segments = static_cast<float> (m_ropeSegments);
+	const auto segments = static_cast<float> (m_ropeSegments);
 	const float timeOffset = 1.0f - std::max (m_trailTimer, 0.0f) / m_trailInterval;
 	m_renderVar0 = m_ropeUVScrolling
 	    ? glm::vec4 (segments - 1.0f, 0.0f, timeOffset, (segments - 1.0f) / this->ropeUVScale ())
@@ -4752,6 +4846,8 @@ void CParticle::updateParticleRenderVars () {
 	m_renderVar0 = glm::vec4 (m_trailLength, m_trailMaxLength, m_trailMinLength, 0.0f);
     }
 
+    m_trailRenderVar0 = glm::vec4 (m_extraTrailLength, m_extraTrailMaxLength, m_extraTrailMinLength, 0.0f);
+
     if (m_spritesheetFrames > 0) {
 	const auto texture = getTexture ();
 	const auto& frame = *texture->getFrames ().front ();
@@ -4765,8 +4861,8 @@ void CParticle::updateParticleRenderVars () {
     } else {
 	float textureRatio = 1.0f;
 	if (const auto texture = getTexture ()) {
-	    float w = static_cast<float> (texture->getRealWidth ());
-	    float h = static_cast<float> (texture->getRealHeight ());
+	    auto w = static_cast<float> (texture->getRealWidth ());
+	    auto h = static_cast<float> (texture->getRealHeight ());
 	    if (w > 0.0f) {
 		textureRatio = h / w;
 	    }
@@ -4892,6 +4988,10 @@ void CParticle::renderSprites () {
 
     m_pass->render ();
 
+    if (m_trailPass != nullptr) {
+	m_trailPass->render ();
+    }
+
     glDisable (GL_DEPTH_CLAMP);
 
 #if !NDEBUG
@@ -4925,10 +5025,10 @@ void CParticle::copyRefractSource () const {
 	getScene ().resolveMultisample ();
     }
 
-    const GLint sw = static_cast<GLint> (source->getRealWidth ());
-    const GLint sh = static_cast<GLint> (source->getRealHeight ());
-    const GLint dw = static_cast<GLint> (m_refractFBO->getRealWidth ());
-    const GLint dh = static_cast<GLint> (m_refractFBO->getRealHeight ());
+    const auto sw = static_cast<GLint> (source->getRealWidth ());
+    const auto sh = static_cast<GLint> (source->getRealHeight ());
+    const auto dw = static_cast<GLint> (m_refractFBO->getRealWidth ());
+    const auto dh = static_cast<GLint> (m_refractFBO->getRealHeight ());
 
     // our copy is scene sized, the shader samples it with normalized coordinates only
     glBindFramebuffer (GL_READ_FRAMEBUFFER, source->getFramebuffer ());
@@ -4948,7 +5048,7 @@ void CParticle::buildRopeTrail (uint32_t& vertexIndex, uint32_t& indexOffset) {
 	const auto point = [&] (int index) -> const glm::vec3& { return index == 0 ? p.position : history[index - 1]; };
 	const glm::vec4 color (p.color, p.alpha);
 	const float trailLength = static_cast<float> (m_trailCount[i]) * uvScaleInverse;
-	const float scroll = static_cast<float> (m_trailScroll[i]);
+	const auto scroll = static_cast<float> (m_trailScroll[i]);
 
 	for (int k = 0; k < segments; k++) {
 	    const glm::vec3& start = point (k);

+ 21 - 4
src/WallpaperEngine/Render/Objects/CParticle.h

@@ -68,10 +68,12 @@ struct ParticleInstance {
 
     bool alive { false };
 
-    float getLifetimePos () const { return lifetime > 0.0f ? (age / lifetime) : 1.0f; }
+    [[nodiscard]] float getLifetimePos () const { return lifetime > 0.0f ? (age / lifetime) : 1.0f; }
 
     // sub_140236CD0 kills a particle once lifetime < age, so it is still drawn on the frame it reaches its lifetime
-    bool isAlive () const { return alive && WallpaperEngine::Data::Utils::isNonZero (lifetime) && !(lifetime < age); }
+    [[nodiscard]] bool isAlive () const {
+	return alive && WallpaperEngine::Data::Utils::isNonZero (lifetime) && !(lifetime < age);
+    }
 };
 
 struct ControlPointData {
@@ -204,7 +206,7 @@ protected:
     OperatorFunc createBoidsOperator (const BoidsOperator& op);
     OperatorFunc createRemapValueOperator (const RemapValueOperator& op);
     OperatorFunc createMaintainDistanceToControlPointOperator (const MaintainDistanceToControlPointOperator& op);
-    OperatorFunc
+    static OperatorFunc
     createMaintainDistanceBetweenControlPointsOperator (const MaintainDistanceBetweenControlPointsOperator& op);
     OperatorFunc createReduceMovementNearControlPointOperator (const ReduceMovementNearControlPointOperator& op);
     OperatorFunc createCollisionOperator (const CollisionOperator& op);
@@ -267,7 +269,7 @@ protected:
     std::vector<ImageEmitter> m_imageEmitters;
     EmitterFunc createImageEmitter (const ParticleEmitter& emitter);
     bool readImagePixels (ImageEmitter& state, const CObject& layer);
-    void downsampleLayerBuffer (ImageEmitter& state, const CFBO& buffer);
+    static void downsampleLayerBuffer (ImageEmitter& state, const CFBO& buffer);
     static void assignImagePixelBones (ImageEmitter& state, const PuppetRig& rig);
     OperatorFunc createCollisionModelOperator (const CollisionOperator& op);
     /** collisionmodel components set up so far, each one reads the dependency record with its index */
@@ -275,7 +277,10 @@ protected:
     [[nodiscard]] float ropeUVScale () const;
     void setupPass ();
     void setupGeometryCallbacks ();
+    void setupTrailPass (const MaterialPass& firstPass);
+    void setupSpriteAttributes (GLuint program) const;
     void setupParticleUniforms ();
+    void addParticleUniforms (Effects::CPass& pass, const glm::vec4* renderVar0);
     void updateMatrices ();
     void updateParticleViewProjection ();
     /** g_OrientationForward/Right/Up from the renderer's orientation (sub_1402298B0) */
@@ -354,6 +359,18 @@ private:
     GLuint m_ebo { 0 };
     GLint m_prevVAO { 0 };
 
+    // a sprite system that lists a spritetrail renderer as well draws its particles twice, the second time stretched
+    // along their velocity; same vertices, own pass and vertex array
+    bool m_hasTrailPass { false };
+    Effects::CPass* m_trailPass { nullptr };
+    std::unique_ptr<ImageEffectPassOverride> m_trailPassOverride;
+    GLuint m_trailVao { 0 };
+    GLint m_trailPrevVAO { 0 };
+    glm::vec4 m_trailRenderVar0 { 0.0f };
+    float m_extraTrailLength { 0.05f };
+    float m_extraTrailMaxLength { 10.0f };
+    float m_extraTrailMinLength { 0.0f };
+
     // m_worldModelMatrix in sceneMatrix () space, CPass points at these
     glm::mat4 m_modelMatrix { 1.0f };
     glm::mat4 m_worldModelMatrix { 1.0f };

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

@@ -38,7 +38,7 @@ public:
     void registerEffectBuffers (const ImageEffect& effect, EffectBuffers buffers);
     // IEffect.executeMaterialFunction (2.8.42 sub_1401EE3A0): "clear" clears as many buffers as it names, always the
     // first ones, each to its clear color; false when the effect isn't ours
-    bool executeEffectFunction (const ImageEffect& effect, const std::string& name) const;
+    [[nodiscard]] bool executeEffectFunction (const ImageEffect& effect, const std::string& name) const;
     /** WE only keeps a material's first pass (sub_1401515B0), what IEffect.getMaterial hands out */
     void registerEffectMaterial (const ImageEffect& effect, size_t passIndex, Effects::CPass* pass);
     [[nodiscard]] Effects::CPass* getEffectMaterial (const ImageEffect& effect, size_t passIndex) const;

+ 14 - 0
src/WallpaperEngine/Render/Objects/CSound.cpp

@@ -404,6 +404,20 @@ void CSound::update (float dt) {
 
 void CSound::setVolumeOverride (std::optional<int> volume) { this->m_screenVolumeOverride = volume; }
 
+void CSound::setHushed (const bool hushed) {
+    if (hushed == this->m_hushed) {
+	return;
+    }
+
+    this->m_hushed = hushed;
+
+    for (const auto& voice : this->m_voices) {
+	if (voice.state == VoiceState::Playing && voice.streamId >= 0) {
+	    this->getScene ().getAudioContext ().setStreamPaused (voice.streamId, hushed);
+	}
+    }
+}
+
 float CSound::masterVolume () const {
     const int base
 	= this->m_screenVolumeOverride.value_or (this->getContext ().getApp ().getContext ().state.audio.volume);

+ 3 - 0
src/WallpaperEngine/Render/Objects/CSound.h

@@ -32,6 +32,8 @@ public:
 
     /** Overrides the volume (0-128) this sound's streams mix at instead of the global volume; nullopt = global */
     void setVolumeOverride (std::optional<int> volume);
+    /** Pauses the playing voices in the driver and leaves the sound's state alone, the scene isn't updating */
+    void setHushed (bool hushed);
 
     void play ();
     void stop ();
@@ -91,6 +93,7 @@ private:
 
     const Sound& m_sound;
     std::optional<int> m_screenVolumeOverride;
+    bool m_hushed = false;
 
     /** +764: countdown to the next play () (next file in loop mode, next play after the random delay) */
     float m_timer = 0.0f;

+ 14 - 4
src/WallpaperEngine/Render/Objects/CText.cpp

@@ -260,6 +260,14 @@ std::vector<std::function<void ()>> CText::fontLookups (const std::vector<std::s
 CText::CText (Wallpapers::CScene& scene, const Text& text) :
     CObject (scene, text), CRenderable (scene, text, compositeMaterial ()), ScriptableObject (scene, text),
     m_text (text), m_font (text.font), m_loadedFont (text.font) {
+    // the Steam depot's assets can predate the MSDF font materials (they come with Wallpaper Engine's own updates)
+    try {
+	(void)this->getScene ().getScene ().project.assetLocator->readString ("materials/fonts/basefont_msdf.json");
+    } catch (const std::exception&) {
+	m_msdfAssets = false;
+	sLog.out ("The assets have no MSDF font materials, texts draw without outline, blur and shadow");
+    }
+
     this->registerProperty ("color", *text.color->value);
     this->registerProperty ("alpha", *text.alpha->value);
     this->registerProperty ("origin", *text.origin->value);
@@ -491,8 +499,9 @@ void CText::initScriptLayer () {
 
 TextLayoutParams CText::currentParams () const {
     // sub_140256F20: any of the glyph effects switches the whole text to MSDF glyphs
-    const bool msdf = m_text.msdf->value->getBool () || m_text.outline->value->getBool ()
-	|| m_text.blur->value->getBool () || m_text.dropShadow->value->getBool ();
+    const bool msdf = m_msdfAssets
+	&& (m_text.msdf->value->getBool () || m_text.outline->value->getBool () || m_text.blur->value->getBool ()
+	    || m_text.dropShadow->value->getBool ());
 
     return {
 	.size = std::clamp (m_text.pointSize->value->getFloat (), 1.0f, 256.0f),
@@ -1079,8 +1088,9 @@ void CText::render () {
     if (m_layerHandle != Scripting::kInvalidLayerHandle) {
 	auto& se = this->getScene ().getScriptEngine ();
 	se.tickLayer (
-	    m_layerHandle, static_cast<double> (getScene ().getTime ()),
-	    static_cast<double> (getScene ().getDeltaTime ()), static_cast<double> (getScene ().getFps ())
+	    m_layerHandle, static_cast<double> (WallpaperEngine::Render::Wallpapers::CScene::getTime ()),
+	    static_cast<double> (WallpaperEngine::Render::Wallpapers::CScene::getDeltaTime ()),
+	    static_cast<double> (WallpaperEngine::Render::Wallpapers::CScene::getFps ())
 	);
 	const std::string current = se.layerText (m_layerHandle);
 	renderedText = current.empty () ? std::string (" ") : current;

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

@@ -132,6 +132,7 @@ private:
     size_t m_compositePassCount = 0;
     /** another object lists this text in its dependencies: it renders through its buffer, even while hidden */
     bool m_isDependency = false;
+    bool m_msdfAssets = true;
 
     std::shared_ptr<const CFBO> m_mainFBO = nullptr;
     std::shared_ptr<const CFBO> m_subFBO = nullptr;

+ 11 - 26
src/WallpaperEngine/Render/Objects/Effects/CPass.cpp

@@ -125,7 +125,7 @@ CPass::CPass (
     std::optional<std::reference_wrapper<const TextureMap>> binds,
     std::optional<std::reference_wrapper<std::string>> target
 ) :
-    Helpers::ContextAware (renderable), m_renderable (renderable), m_fboProvider (std::move (fboProvider)),
+    Helpers::ContextAware (&renderable), m_renderable (renderable), m_fboProvider (std::move (fboProvider)),
     m_pass (pass), m_binds (binds.has_value () ? binds.value ().get () : DEFAULT_BINDS),
     m_override (override.has_value () ? override.value ().get () : DEFAULT_OVERRIDE), m_target (target),
     m_blendingmode (pass.blending), m_vao (GL_NONE) {
@@ -189,7 +189,7 @@ CPass::~CPass () {
 }
 
 std::shared_ptr<const TextureProvider> CPass::resolveTexture (
-    std::shared_ptr<const TextureProvider> expected, int index, std::shared_ptr<const TextureProvider> previous
+    std::shared_ptr<const TextureProvider> expected, int index, const std::shared_ptr<const TextureProvider>& previous
 ) {
     if (expected == nullptr) {
 	if (const auto it = this->m_fbos.find (index); it != this->m_fbos.end ()) {
@@ -362,7 +362,7 @@ void CPass::setupRenderFramebuffer () const {
 	glClearColor (previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]);
     }
 
-    glViewport (0, 0, target->getRealWidth (), target->getRealHeight ());
+    glViewport (0, 0, static_cast<GLsizei> (target->getRealWidth ()), static_cast<GLsizei> (target->getRealHeight ()));
 
     // D3D11 unbinds a resource that is also the render target, WE reads 0 there (pooled buffer shared with the target).
     // Not for the scene buffer, WE samples a copy
@@ -871,7 +871,10 @@ void CPass::clearDestination () const {
     GLfloat previousClearColor[4] = {};
     glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_drawTo->getFramebuffer ());
-    glViewport (0, 0, this->m_drawTo->getRealWidth (), this->m_drawTo->getRealHeight ());
+    glViewport (
+	0, 0, static_cast<GLsizei> (this->m_drawTo->getRealWidth ()),
+	static_cast<GLsizei> (this->m_drawTo->getRealHeight ())
+    );
     glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
     glColorMask (true, true, true, true);
     glClear (GL_COLOR_BUFFER_BIT);
@@ -1248,7 +1251,9 @@ void CPass::setupShaders () {
 	    this->m_programID = cached->second.program;
 	    cached->second.users++;
 	} else {
-	    this->m_programID = this->linkProgram (vertex, fragment, this->m_compiled->geometry, shaderName);
+	    this->m_programID = WallpaperEngine::Render::Objects::Effects::CPass::linkProgram (
+		vertex, fragment, this->m_compiled->geometry, shaderName
+	    );
 	    sharedPrograms ().emplace (this->m_programKey, SharedProgram { this->m_programID, 1 });
 	}
 
@@ -1354,7 +1359,7 @@ std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
     }
 
     LWE_ZONE_TEXT ("shader translate", shaderName);
-    auto sources = Shaders::GLSLContext::get ().toGlsl (
+    auto sources = WallpaperEngine::Render::Shaders::GLSLContext::toGlsl (
 	compiled->shader->vertex (), compiled->shader->fragment (), shaderName, compiled->shader->geometry ()
     );
     compiled->vertex = std::move (sources.vertex);
@@ -2136,18 +2141,10 @@ void CPass::addUniform (const std::string& name, const float* value, int count)
     this->addUniform (name, UniformType::Float, value, count);
 }
 
-void CPass::addUniform (const std::string& name, glm::vec2 value) {
-    this->addUniform (name, UniformType::Vector2, value);
-}
-
 void CPass::addUniform (const std::string& name, const glm::vec2* value) {
     this->addUniform (name, UniformType::Vector2, value, 1);
 }
 
-void CPass::addUniform (const std::string& name, const glm::vec2** value) {
-    this->addUniform (name, UniformType::Vector2, value, 1);
-}
-
 void CPass::addUniform (const std::string& name, glm::vec3 value) {
     this->addUniform (name, UniformType::Vector3, value);
 }
@@ -2156,10 +2153,6 @@ void CPass::addUniform (const std::string& name, const glm::vec3* value) {
     this->addUniform (name, UniformType::Vector3, value, 1);
 }
 
-void CPass::addUniform (const std::string& name, const glm::vec3** value) {
-    this->addUniform (name, UniformType::Vector3, value);
-}
-
 void CPass::addUniform (const std::string& name, const glm::vec4 value) {
     this->addUniform (name, UniformType::Vector4, value);
 }
@@ -2201,10 +2194,6 @@ void CPass::addUniform (const std::string& name, const glm::vec4* value) {
     this->addUniform (name, UniformType::Vector4, value, 1);
 }
 
-void CPass::addUniform (const std::string& name, const glm::vec4** value) {
-    this->addUniform (name, UniformType::Vector4, value);
-}
-
 void CPass::addUniform (const std::string& name, const glm::mat3& value) {
     this->addUniform (name, UniformType::Matrix3, value);
 }
@@ -2217,10 +2206,6 @@ void CPass::addUniform (const std::string& name, const glm::mat3** value) {
     this->addUniform (name, UniformType::Matrix3, value);
 }
 
-void CPass::addUniform (const std::string& name, const glm::mat4 value) {
-    this->addUniform (name, UniformType::Matrix4, value);
-}
-
 void CPass::addUniform (const std::string& name, const glm::mat4* value) {
     this->addUniform (name, UniformType::Matrix4, value, 1);
 }

+ 5 - 10
src/WallpaperEngine/Render/Objects/Effects/CPass.h

@@ -36,7 +36,7 @@ public:
 	std::optional<std::reference_wrapper<const TextureMap>> binds,
 	std::optional<std::reference_wrapper<std::string>> target
     );
-    ~CPass ();
+    ~CPass () override;
 
     void render ();
     void clearDestination () const;
@@ -232,16 +232,11 @@ private:
     void addUniform (const ShaderVariable* value, const DynamicValue* setting);
     void addUniform (const std::string& name, int value);
     void addUniform (const std::string& name, float value);
-    void addUniform (const std::string& name, glm::vec2 value);
     void addUniform (const std::string& name, glm::vec3 value);
     void addUniform (const std::string& name, glm::vec4 value);
     void addUniform (const std::string& name, const glm::mat3& value);
-    void addUniform (const std::string& name, glm::mat4 value);
     void addUniform (const std::string& name, const int* value, int count = 1);
     void addUniform (const std::string& name, const glm::vec2* value);
-    void addUniform (const std::string& name, const glm::vec2** value);
-    void addUniform (const std::string& name, const glm::vec3** value);
-    void addUniform (const std::string& name, const glm::vec4** value);
     void addUniform (const std::string& name, const glm::mat3** value);
     void addUniform (const std::string& name, const glm::mat4** value);
     template <typename T> void addUniform (const std::string& name, UniformType type, T value);
@@ -263,7 +258,7 @@ private:
 
     std::shared_ptr<const TextureProvider> resolveTexture (
 	std::shared_ptr<const TextureProvider> expected, int index,
-	std::shared_ptr<const TextureProvider> previous = nullptr
+	const std::shared_ptr<const TextureProvider>& previous = nullptr
     );
 
     // usertextures entries name a "scenetexture" property, the texture is what the user set it to; nullopt when the
@@ -333,11 +328,11 @@ private:
     std::map<int, glm::vec4> m_texels = {};
     std::map<int, const glm::vec4*> m_texelSources = {};
 
-    GLuint m_programID;
+    GLuint m_programID {};
     std::string m_programKey;
 
-    GLint g_Texture0Rotation;
-    GLint g_Texture0Translation;
+    GLint g_Texture0Rotation {};
+    GLint g_Texture0Translation {};
     GLuint a_TexCoord = 0;
     GLuint a_Position = 0;
     GLuint m_vao;

Some files were not shown because too many files changed in this diff