Kaynağa Gözat

Faster scene loading, DPMS pause on KWin, playlist and mpv fixes, test coverage 85%, CI hardening

Scene loading: textures, materials and shaders of a scene are read and translated ahead by worker threads (TextureCache, CScene prefetch), the package reader holds files in memory, shader translation memos are filled before the first pass is built. Pausing: SessionMonitor and the KWin DPMS protocol (protocols/kwin-dpms.xml) pause on a blanked display and lock, GNOME Shell and KDE cursor reconnect handling, session bus hardening. Fixes: playlist reload loop when the next item ended (GLPlayer takes the position of the ended player), mpv no longer resets SIGINT/SIGTERM handlers on destroy, particle start values and collisionquad start match the original, text objects with particle None, script module refusal message, _FORTIFY_SOURCE collision with the CEF flags, PulseAudio capture leaks and detector reconnect (upstream). Tests: 365 unit tests, hotswap, playlist, script, shortcut and audio coverage scripts (tools/analysis), AFL, thread safety and gcc analyzer helpers. CI: workflow actions pinned by hash, read-only permissions, CodeQL, dependabot, SECURITY.md. Linux VM harness: Hyprland 0.56 Lua dispatch for the DPMS check.
UwU 4 hafta önce
ebeveyn
işleme
c1630b0469
100 değiştirilmiş dosya ile 1737 ekleme ve 963 silme
  1. 13 0
      .github/dependabot.yml
  2. 4 1
      .github/workflows/aur.yml
  3. 28 25
      .github/workflows/cmake.yml
  4. 51 0
      .github/workflows/codeql.yml
  5. 1 0
      .gitignore
  6. 33 2
      CMakeLists.txt
  7. 15 0
      SECURITY.md
  8. 1 1
      docs/investigations/puppet-and-renderer-notes.md
  9. 87 0
      protocols/kwin-dpms.xml
  10. 13 13
      src/WallpaperEngine/Application/ApplicationContext.cpp
  11. 5 9
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  12. 2 1
      src/WallpaperEngine/Application/WallpaperApplication.h
  13. 2 3
      src/WallpaperEngine/Audio/AudioStream.cpp
  14. 1 1
      src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.cpp
  15. 3 3
      src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.cpp
  16. 4 3
      src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.h
  17. 5 6
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp
  18. 2 3
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp
  19. 4 3
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.h
  20. 0 1
      src/WallpaperEngine/Audio/SpectrumAnalyzer.cpp
  21. 3 0
      src/WallpaperEngine/Data/Assets/Texture.h
  22. 1 1
      src/WallpaperEngine/Data/Builders/ColorBuilder.cpp
  23. 15 21
      src/WallpaperEngine/Data/Model/DynamicValue.cpp
  24. 1 0
      src/WallpaperEngine/Data/Model/DynamicValue.h
  25. 1 1
      src/WallpaperEngine/Data/Model/Property.h
  26. 0 2
      src/WallpaperEngine/Data/Parsers/EffectParser.cpp
  27. 22 1
      src/WallpaperEngine/Data/Parsers/MaterialParser.cpp
  28. 3 0
      src/WallpaperEngine/Data/Parsers/MaterialParser.h
  29. 0 2
      src/WallpaperEngine/Data/Parsers/ModelParser.cpp
  30. 62 93
      src/WallpaperEngine/Data/Parsers/ObjectParser.cpp
  31. 0 1
      src/WallpaperEngine/Data/Parsers/ProjectParser.cpp
  32. 0 2
      src/WallpaperEngine/Data/Parsers/TextureParser.cpp
  33. 5 1
      src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp
  34. 1 11
      src/WallpaperEngine/Data/Utils/BinaryReader.cpp
  35. 0 1
      src/WallpaperEngine/Debugging/CallStack.cpp
  36. 74 0
      src/WallpaperEngine/Debugging/ThreadSafety.h
  37. 6 58
      src/WallpaperEngine/Desktop/GnomeShell.cpp
  38. 3 19
      src/WallpaperEngine/Desktop/HostWayland.cpp
  39. 4 28
      src/WallpaperEngine/Desktop/HyprlandIPC.cpp
  40. 0 1
      src/WallpaperEngine/Desktop/KWinScript.cpp
  41. 3 32
      src/WallpaperEngine/Desktop/PantheonShell.cpp
  42. 4 0
      src/WallpaperEngine/Desktop/PowerMonitor.cpp
  43. 100 0
      src/WallpaperEngine/Desktop/SessionBus.cpp
  44. 9 0
      src/WallpaperEngine/Desktop/SessionBus.h
  45. 392 3
      src/WallpaperEngine/Desktop/SessionMonitor.cpp
  46. 0 2
      src/WallpaperEngine/FileSystem/Adapters/Directory.cpp
  47. 0 1
      src/WallpaperEngine/FileSystem/Adapters/MediaCover.cpp
  48. 67 7
      src/WallpaperEngine/FileSystem/Adapters/Package.cpp
  49. 8 0
      src/WallpaperEngine/FileSystem/Adapters/Package.h
  50. 0 2
      src/WallpaperEngine/FileSystem/Adapters/Virtual.cpp
  51. 1 3
      src/WallpaperEngine/FileSystem/Container.cpp
  52. 0 1
      src/WallpaperEngine/Input/Drivers/GLFWMouseInput.cpp
  53. 72 23
      src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp
  54. 5 0
      src/WallpaperEngine/Input/Drivers/KDECursorInput.h
  55. 0 1
      src/WallpaperEngine/Led/LedLayout.cpp
  56. 7 7
      src/WallpaperEngine/Led/LedOutput.cpp
  57. 5 4
      src/WallpaperEngine/Led/LedOutput.h
  58. 2 2
      src/WallpaperEngine/Logging/Log.cpp
  59. 9 8
      src/WallpaperEngine/Logging/Log.h
  60. 3 3
      src/WallpaperEngine/Media/CoverDownloader.cpp
  61. 1 1
      src/WallpaperEngine/Media/DBusMediaSource.cpp
  62. 1 2
      src/WallpaperEngine/Render/AlbumTexture.cpp
  63. 0 2
      src/WallpaperEngine/Render/CObject.cpp
  64. 27 3
      src/WallpaperEngine/Render/CTexture.cpp
  65. 4 0
      src/WallpaperEngine/Render/CTexture.h
  66. 1 2
      src/WallpaperEngine/Render/CWallpaper.cpp
  67. 0 1
      src/WallpaperEngine/Render/Camera.cpp
  68. 1 1
      src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp
  69. 8 32
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp
  70. 0 1
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.h
  71. 68 0
      src/WallpaperEngine/Render/Drivers/EglSharedContext.h
  72. 5 21
      src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.cpp
  73. 10 1
      src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.cpp
  74. 1 0
      src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.h
  75. 0 11
      src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.cpp
  76. 24 0
      src/WallpaperEngine/Render/Drivers/Output/Output.cpp
  77. 2 0
      src/WallpaperEngine/Render/Drivers/Output/Output.h
  78. 2 4
      src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.cpp
  79. 5 28
      src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
  80. 0 1
      src/WallpaperEngine/Render/Drivers/Output/X11Output.h
  81. 9 0
      src/WallpaperEngine/Render/Drivers/VideoDriver.h
  82. 18 1
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
  83. 2 1
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h
  84. 31 0
      src/WallpaperEngine/Render/Drivers/X11WindowType.h
  85. 45 22
      src/WallpaperEngine/Render/Fonts/SystemFonts.cpp
  86. 63 100
      src/WallpaperEngine/Render/Objects/CImage.cpp
  87. 2 0
      src/WallpaperEngine/Render/Objects/CImage.h
  88. 42 19
      src/WallpaperEngine/Render/Objects/CMesh.cpp
  89. 6 0
      src/WallpaperEngine/Render/Objects/CMesh.h
  90. 86 143
      src/WallpaperEngine/Render/Objects/CParticle.cpp
  91. 4 1
      src/WallpaperEngine/Render/Objects/CParticle.h
  92. 2 1
      src/WallpaperEngine/Render/Objects/CRenderable.cpp
  93. 0 3
      src/WallpaperEngine/Render/Objects/CSound.cpp
  94. 37 36
      src/WallpaperEngine/Render/Objects/CText.cpp
  95. 6 0
      src/WallpaperEngine/Render/Objects/CText.h
  96. 26 91
      src/WallpaperEngine/Render/Objects/Effects/CPass.cpp
  97. 2 5
      src/WallpaperEngine/Render/Objects/Effects/CPass.h
  98. 23 0
      src/WallpaperEngine/Render/Objects/ParallaxClamp.h
  99. 9 9
      src/WallpaperEngine/Render/Objects/PuppetClipping.cpp
  100. 2 3
      src/WallpaperEngine/Render/Objects/PuppetIK.cpp

+ 13 - 0
.github/dependabot.yml

@@ -0,0 +1,13 @@
+version: 2
+updates:
+  - package-ecosystem: github-actions
+    directory: /
+    schedule:
+      interval: weekly
+    groups:
+      actions:
+        patterns: ['*']
+  - package-ecosystem: pip
+    directory: /tools
+    schedule:
+      interval: monthly

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

@@ -9,13 +9,16 @@ on:
     paths:
       - 'packaging/aur/linux-wallpaperengine-kde-git/**'
 
+permissions:
+  contents: read
+
 jobs:
   publish:
     runs-on: ubuntu-latest
     env:
       HAS_AUR_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY != '' }}
     steps:
-      - uses: actions/checkout@v7
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
 
       - name: Publish linux-wallpaperengine-kde-git to the AUR
         if: env.HAS_AUR_KEY == 'true'

+ 28 - 25
.github/workflows/cmake.yml

@@ -5,14 +5,17 @@ on:
     types: [ published ]
   workflow_dispatch:
 
+permissions:
+  contents: read
+
 jobs:
   formatting:
     name: Formatting check
     runs-on: ubuntu-latest
     steps:
-      - uses: actions/checkout@v7
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
       - name: Run clang-format style check for C/C++ programs.
-        uses: jidicula/clang-format-action@v4.18.0
+        uses: jidicula/clang-format-action@654a770daa28443dd111d133e4083e21c1075674 # v4.18.0
         with:
           check-path: "src"
           exclude-regex: "(src/External)"
@@ -32,13 +35,13 @@ jobs:
     runs-on: ${{ matrix.os }}
 
     steps:
-      - uses: actions/checkout@v7
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
         with:
           submodules: true
 
       # cache some build information
       - name: ccache
-        uses: hendrikmuhs/ccache-action@v1.2.24
+        uses: hendrikmuhs/ccache-action@f09c25b45002a07be2955cbe52e8cee55643f89d # v1.2.24
         with:
           key: ${{ github.job }}-${{ matrix.os }}
 
@@ -80,18 +83,18 @@ jobs:
     runs-on: ubuntu-24.04
 
     steps:
-      - uses: actions/checkout@v7
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
         with:
           submodules: true
 
       - name: ccache
-        uses: hendrikmuhs/ccache-action@v1.2.24
+        uses: hendrikmuhs/ccache-action@f09c25b45002a07be2955cbe52e8cee55643f89d # v1.2.24
         with:
           key: ${{ github.job }}-ubuntu-24.04-${{ matrix.build_type }}-${{ matrix.variant }}
 
       - name: Initialize CodeQL
         # Initializes the CodeQL tools for scanning.
-        uses: github/codeql-action/init@v4
+        uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4
         if: ${{ matrix.build_type == 'Debug' }}
         with:
           languages: 'cpp'
@@ -107,13 +110,13 @@ jobs:
 
       - name: Perform CodeQL Analysis
         if: ${{ matrix.build_type == 'Debug' }}
-        uses: github/codeql-action/analyze@v4
+        uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4
 
       - name: Package
         if: ${{ matrix.build_type == 'Release' }}
         run: tools/package_release.sh build linux-wallpaperengine-${{ matrix.variant }}-ubuntu-24.04-x86_64 "$RUNNER_TEMP"
 
-      - uses: actions/upload-artifact@v7
+      - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
         if: ${{ matrix.build_type == 'Release' }}
         with:
           name: linux-wallpaperengine-${{ matrix.variant }}
@@ -164,7 +167,7 @@ jobs:
 
       - name: Restore ccache
         if: steps.prebuilt.outputs.hit != 'true'
-        uses: actions/cache/restore@v6
+        uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
         with:
           path: /tmp/libnode-ccache
           key: libnode-ccache-${{ steps.libnode.outputs.version }}
@@ -183,7 +186,7 @@ jobs:
       # saved right away, a later failure in this run must not throw the build away
       - name: Save ccache
         if: steps.prebuilt.outputs.hit != 'true'
-        uses: actions/cache/save@v6
+        uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
         with:
           path: /tmp/libnode-ccache
           key: libnode-ccache-${{ steps.libnode.outputs.version }}
@@ -206,7 +209,7 @@ jobs:
             "https://uploads.github.com/repos/$GITHUB_REPOSITORY/releases/$id/assets?name=$asset" > /dev/null
 
       # for the Arch distribution builds and the smoke test's fresh Arch container
-      - uses: actions/upload-artifact@v7
+      - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
         with:
           name: libnode-arch
           path: /tmp/libnode-pkg/libnode-[0-9]*.pkg.tar.zst
@@ -246,7 +249,7 @@ jobs:
       - name: Install dependencies
         run: ${{ matrix.install }}
 
-      - uses: actions/download-artifact@v8
+      - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
         if: matrix.distro == 'arch'
         with:
           name: libnode-arch
@@ -256,7 +259,7 @@ jobs:
         if: matrix.distro == 'arch'
         run: pacman -U --noconfirm /tmp/libnode-pkg/libnode-[0-9]*.pkg.tar.zst
 
-      - uses: actions/checkout@v7
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
         with:
           submodules: true
 
@@ -269,7 +272,7 @@ jobs:
       - name: Package
         run: tools/package_release.sh build linux-wallpaperengine-${{ matrix.variant }}-${{ matrix.distro }}-x86_64 "$RUNNER_TEMP"
 
-      - uses: actions/upload-artifact@v7
+      - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
         with:
           name: linux-wallpaperengine-${{ matrix.variant }}-${{ matrix.distro }}
           path: ${{ runner.temp }}/linux-wallpaperengine-${{ matrix.variant }}-${{ matrix.distro }}-x86_64.tar.gz
@@ -300,7 +303,7 @@ jobs:
           libxdamage1 libgbm1 libxkbcommon0 libasound2 libpango-1.0-0 libcairo2 libdrm2 libxshmfence1
           libatspi2.0-0
 
-      - uses: actions/checkout@v7
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
         with:
           submodules: true
 
@@ -313,7 +316,7 @@ jobs:
       - name: Package
         run: tools/package_release.sh --portable build linux-wallpaperengine-${{ matrix.variant }}-portable-x86_64 "$RUNNER_TEMP"
 
-      - uses: actions/upload-artifact@v7
+      - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
         with:
           name: linux-wallpaperengine-${{ matrix.variant }}-portable
           path: ${{ runner.temp }}/linux-wallpaperengine-${{ matrix.variant }}-portable-x86_64.tar.gz
@@ -347,15 +350,15 @@ jobs:
     container: ${{ matrix.image }}
 
     steps:
-      - uses: actions/checkout@v7
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
 
-      - uses: actions/download-artifact@v8
+      - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
         with:
           # the Ubuntu build's artifact has no distribution in its name
           name: linux-wallpaperengine-${{ matrix.tarball == 'kde-ubuntu-24.04' && 'kde' || matrix.tarball }}
           path: tarball
 
-      - uses: actions/download-artifact@v8
+      - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
         if: matrix.tarball == 'kde-arch'
         with:
           name: libnode-arch
@@ -375,9 +378,9 @@ jobs:
     permissions:
       contents: write
     steps:
-      - uses: actions/checkout@v7
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
 
-      - uses: actions/download-artifact@v8
+      - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
         with:
           path: release
           merge-multiple: true
@@ -402,7 +405,7 @@ jobs:
     env:
       HAS_AUR_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY != '' }}
     steps:
-      - uses: actions/checkout@v7
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
 
       - name: Set the version
         run: sed -i -e "s/^pkgver=.*/pkgver=${GITHUB_REF_NAME#v}/" -e "s/^pkgrel=.*/pkgrel=1/"
@@ -436,12 +439,12 @@ jobs:
     runs-on: ubuntu-24.04
 
     steps:
-      - uses: actions/checkout@v7
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
         with:
           submodules: true
 
       - name: ccache
-        uses: hendrikmuhs/ccache-action@v1.2.24
+        uses: hendrikmuhs/ccache-action@f09c25b45002a07be2955cbe52e8cee55643f89d # v1.2.24
         with:
           key: ${{ github.job }}-ubuntu-24.04-${{ matrix.build_type }}
 

+ 51 - 0
.github/workflows/codeql.yml

@@ -0,0 +1,51 @@
+name: CodeQL
+
+on:
+  schedule:
+    - cron: '23 3 * * 1'
+  workflow_dispatch:
+
+permissions:
+  contents: read
+
+jobs:
+  analyze:
+    name: Analyze C++
+    runs-on: ubuntu-24.04
+    permissions:
+      actions: read
+      contents: read
+      security-events: write
+
+    steps:
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+        with:
+          submodules: true
+
+      - name: ccache
+        uses: hendrikmuhs/ccache-action@f09c25b45002a07be2955cbe52e8cee55643f89d # v1.2.24
+        with:
+          key: ${{ github.job }}
+
+      - name: Install dependencies
+        run: sudo apt-get update && sudo apt-get -y install libxrandr-dev libxinerama-dev libxcomposite-dev libxdamage-dev libxcursor-dev libxi-dev libgl-dev libglew-dev freeglut3-dev libsdl2-dev liblz4-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libxxf86vm-dev libglm-dev libglfw3-dev libmpv-dev mpv libmpv2 libpulse-dev libpulse0 libfftw3-dev libfreetype-dev libdbus-1-dev libnode-dev wayland-scanner++ wayland-protocols libwayland-dev
+
+      - name: Initialize CodeQL
+        uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4
+        with:
+          languages: c-cpp
+          build-mode: manual
+          queries: security-extended
+          config: |
+            paths-ignore:
+              - src/External
+
+      - name: Build
+        run: |
+          cmake -B build -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=1 -D CMAKE_C_COMPILER_LAUNCHER=ccache -D CMAKE_CXX_COMPILER_LAUNCHER=ccache
+          cmake --build build --target linux-wallpaperengine -j"$(nproc)"
+
+      - name: Perform CodeQL analysis
+        uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4
+        with:
+          category: /language:c-cpp

+ 1 - 0
.gitignore

@@ -20,3 +20,4 @@ linux-wallpaperengine-*-x86_64.tar.gz
 AGENTS.md
 __pycache__/
 *.pyc
+*.profraw

+ 33 - 2
CMakeLists.txt

@@ -154,8 +154,13 @@ find_package(CEF REQUIRED)
 list(REMOVE_ITEM CEF_CXX_COMPILER_FLAGS -fno-exceptions)
 list(REMOVE_ITEM CEF_CXX_COMPILER_FLAGS -fno-rtti)
 list(REMOVE_ITEM CEF_CXX_COMPILER_FLAGS -std=c++17)
+# function-local statics (the shaders' regexes, memos, singletons) are first used from worker threads
+list(REMOVE_ITEM CEF_CXX_COMPILER_FLAGS -fno-threadsafe-statics)
 list(REMOVE_ITEM CEF_COMPILER_FLAGS -fvisibility=hidden)
 list(REMOVE_ITEM CEF_COMPILER_FLAGS -fvisibility-inlines-hidden)
+# CEF's release flags set _FORTIFY_SOURCE=2 with a -U in front; CMake drops that repeated -U when our own target options
+# carry one, which leaves two -D with different values and -Werror turns the redefinition into an error
+list(REMOVE_ITEM CEF_COMPILER_FLAGS_RELEASE -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2)
 list(APPEND CEF_CXX_COMPILER_FLAGS -std=c++20)
 list(APPEND CEF_EXE_LINKER_FLAGS -rdynamic)
 # remove the vulkan library from the files to copy so it doesn't fail after removing it
@@ -307,7 +312,13 @@ if(WAYLAND_SUPPORT_FOUND)
             COMMAND ${WaylandScanner} client-header ${CMAKE_CURRENT_SOURCE_DIR}/protocols/plasma-shell.xml ${WAYLAND_OUTPUT_DIR}/plasma-shell-protocol.h)
         add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/plasma-shell-protocol.c
             COMMAND ${WaylandScanner} private-code ${CMAKE_CURRENT_SOURCE_DIR}/protocols/plasma-shell.xml ${WAYLAND_OUTPUT_DIR}/plasma-shell-protocol.c)
+        add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/kwin-dpms-protocol.h
+            COMMAND ${WaylandScanner} client-header ${CMAKE_CURRENT_SOURCE_DIR}/protocols/kwin-dpms.xml ${WAYLAND_OUTPUT_DIR}/kwin-dpms-protocol.h)
+        add_custom_command(OUTPUT ${WAYLAND_OUTPUT_DIR}/kwin-dpms-protocol.c
+            COMMAND ${WaylandScanner} private-code ${CMAKE_CURRENT_SOURCE_DIR}/protocols/kwin-dpms.xml ${WAYLAND_OUTPUT_DIR}/kwin-dpms-protocol.c)
         list(APPEND WAYLAND_SOURCES
+            ${WAYLAND_OUTPUT_DIR}/kwin-dpms-protocol.c
+            ${WAYLAND_OUTPUT_DIR}/kwin-dpms-protocol.h
             src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.cpp
             src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.h
             src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp
@@ -795,6 +806,8 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/Example.cpp
         src/WallpaperEngine/Testing/Cases/Leds.cpp
         src/WallpaperEngine/Testing/Cases/FramePacer.cpp
+        src/WallpaperEngine/Testing/Cases/AudioStream.cpp
+        src/WallpaperEngine/Testing/Cases/Hrtf.cpp
         src/WallpaperEngine/Testing/Render/TestingOpenGLDriver.cpp
         src/WallpaperEngine/Testing/Render/TestingOpenGLDriver.h
         src/WallpaperEngine/Testing/Input/TestingMouseInput.cpp
@@ -847,7 +860,11 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/WebFrameSlots.cpp
         src/WallpaperEngine/Testing/Cases/AlbumArtworkUpload.cpp
         src/WallpaperEngine/Testing/Cases/SplitLayout.cpp
-        src/WallpaperEngine/Testing/Cases/AutomuteDetector.cpp)
+        src/WallpaperEngine/Testing/Cases/AutomuteDetector.cpp
+        src/WallpaperEngine/Testing/Cases/IconTheme.cpp
+        src/WallpaperEngine/Testing/Cases/ApplicationArguments.cpp
+        src/WallpaperEngine/Testing/Cases/PuppetIK.cpp
+        src/WallpaperEngine/Testing/Cases/ProjectScenes.cpp)
 endif()
 
 # the one file that derives from a V8 class: libnode is built without RTTI and exports no typeinfo of V8's classes
@@ -994,16 +1011,30 @@ file(REMOVE "${CEF_BINARY_DIR}/libvulkan.so.1")
 set_target_properties(linux-wallpaperengine-lib PROPERTIES
     LIBRARY_OUTPUT_DIRECTORY ${TARGET_OUTPUT_DIRECTORY})
 
+# hardening for our own code only (the CEF wrapper builds with -Werror and its own flags)
+# packagers set their own level (Fedora, Arch: 3) through CXXFLAGS, glibc before 2.33 treats 3 as 2
+if(NOT CMAKE_CXX_FLAGS MATCHES "_FORTIFY_SOURCE")
+    target_compile_options(linux-wallpaperengine-lib PRIVATE
+        $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:Release,RelWithDebInfo>>:-U_FORTIFY_SOURCE>
+        $<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CONFIG:Release,RelWithDebInfo>>:-D_FORTIFY_SOURCE=3>)
+endif()
+target_link_options(linux-wallpaperengine-lib PRIVATE -Wl,-z,relro,-z,now)
+# Debugging/ThreadSafety.h carries the lock annotations, only clang checks them
+target_compile_options(linux-wallpaperengine-lib PRIVATE $<$<CXX_COMPILER_ID:Clang>:-Wthread-safety>)
+
 add_dependencies(linux-wallpaperengine-lib libcef_dll_wrapper glslang spirv-cross-core spirv-cross-glsl)
 # CEF's SET_EXECUTABLE_TARGET_PROPERTIES without C++ flags on C files
 REPLACED_SET_EXECUTABLE_TARGET_PROPERTIES(linux-wallpaperengine-lib)
+# after CEF's options, the compilers keep the last of -fstack-protector and -fstack-protector-strong
+target_compile_options(linux-wallpaperengine-lib PRIVATE
+    $<$<COMPILE_LANGUAGE:CXX>:-fstack-protector-strong>)
 
 add_executable(linux-wallpaperengine
     src/main.cpp)
 
 target_link_libraries (linux-wallpaperengine PUBLIC linux-wallpaperengine-lib)
 # libcef has to load before libc (Chromium finds close() via RTLD_NEXT), --as-needed distros dropped the dependency
-target_link_options (linux-wallpaperengine PRIVATE -Wl,--no-as-needed)
+target_link_options (linux-wallpaperengine PRIVATE -Wl,--no-as-needed -pie -Wl,-z,relro,-z,now)
 
 add_executable(linux-wallpaperengine-web-helper
     src/web_helper.cpp

+ 15 - 0
SECURITY.md

@@ -0,0 +1,15 @@
+# Security policy
+
+## Supported versions
+
+Only the latest release of linux-wallpaperengine-kde (engine) and WE Manager gets security fixes.
+
+## Reporting a vulnerability
+
+Please do not open a public issue. Use GitHub's private reporting instead:
+https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde/security/advisories/new
+(for WE Manager: https://github.com/WallpaperEngineLover/we_manager/security/advisories/new).
+
+Say which version you ran, what you did and what happened. Wallpapers are untrusted input, so a crafted wallpaper
+that crashes the engine, reads files outside its folder or runs a command is in scope. Reports are answered as
+soon as possible, fixes ship with the next release and the report is credited unless you prefer otherwise.

+ 1 - 1
docs/investigations/puppet-and-renderer-notes.md

@@ -1,7 +1,7 @@
 # Puppet and renderer findings
 
 The long dated write-ups that used to be here followed bugs that are closed now. What they found, and still matters when
-touching puppet rendering (the matching code is described under "Puppets" and "Scene, layout and offsets" in `CLAUDE.md`):
+touching puppet rendering (the matching code is described under "Puppets" and "Scene, layout and offsets" in the developer notes):
 
 - **Attachments**: a child's world transform is exactly `parent * attachment point * child local` (`CImage::getAttachmentMatrix`,
   `CScene::parentChainMatrix`). The attachment matrix's static rotation orients the point's frame only; no extra pivot

+ 87 - 0
protocols/kwin-dpms.xml

@@ -0,0 +1,87 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="dpms">
+  <copyright><![CDATA[
+    SPDX-FileCopyrightText: 2015 Martin Gräßlin
+
+    SPDX-License-Identifier: LGPL-2.1-or-later
+  ]]></copyright>
+  <interface name="org_kde_kwin_dpms_manager" version="1">
+      <description summary="Output dpms manager">
+          The Dpms manager allows to get a org_kde_kwin_dpms for a given wl_output.
+          The org_kde_kwin_dpms provides the currently used VESA Display Power Management
+          Signaling state (see https://en.wikipedia.org/wiki/VESA_Display_Power_Management_Signaling ).
+          In addition it allows to request a state change. A compositor is not obliged to honor it
+          and will normally automatically switch back to on state.
+
+          Warning! The protocol described in this file is a desktop environment
+          implementation detail. Regular clients must not use this protocol.
+          Backward incompatible changes may be added without bumping the major
+          version of the extension.
+      </description>
+      <request name="get">
+          <description summary="Get org_kde_kwin_dpms for wl_output">
+              Factory request to get the org_kde_kwin_dpms for a given wl_output.
+          </description>
+          <arg name="id" type="new_id" interface="org_kde_kwin_dpms"/>
+          <arg name="output" type="object" interface="wl_output"/>
+      </request>
+  </interface>
+  <interface name="org_kde_kwin_dpms" version="1">
+      <description summary="Dpms for a wl_output">
+          This interface provides information about the VESA DPMS state for a wl_output.
+          It gets created through the request get on the org_kde_kwin_dpms_manager interface.
+
+          On creating the resource the server will push whether DPSM is supported for the output,
+          the currently used DPMS state and notifies the client through the done event once all
+          states are pushed. Whenever a state changes the set of changes is committed with the
+          done event.
+      </description>
+      <event name="supported">
+          <description summary="Event indicating whether DPMS is supported on the wl_output">
+              This event gets pushed on binding the resource and indicates whether the wl_output
+              supports DPMS. There are operation modes of a Wayland server where DPMS might not
+              make sense (e.g. nested compositors).
+          </description>
+          <arg name="supported" type="uint" summary="Boolean value whether DPMS is supported (1) for the wl_output or not (0)"/>
+      </event>
+      <enum name="mode">
+            <entry name="On" value="0"/>
+            <entry name="Standby" value="1"/>
+            <entry name="Suspend" value="2"/>
+            <entry name="Off" value="3"/>
+      </enum>
+      <event name="mode">
+          <description summary="Event indicating used DPMS mode">
+              This mode gets pushed on binding the resource and provides the currently used
+              DPMS mode. It also gets pushed if DPMS is not supported for the wl_output, in that
+              case the value will be On.
+
+              The event is also pushed whenever the state changes.
+          </description>
+          <arg name="mode" type="uint" summary="The new currently used mode"/>
+      </event>
+      <event name="done">
+          <description summary="All changes are pushed">
+              This event gets pushed on binding the resource once all other states are pushed.
+
+              In addition it gets pushed whenever a state changes to tell the client that all
+              state changes have been pushed.
+          </description>
+      </event>
+      <request name="set">
+          <description summary="Request DPMS state change for the wl_output">
+              Requests that the compositor puts the wl_output into the passed mode. The compositor
+              is not obliged to change the state. In addition the compositor might leave the mode
+              whenever it seems suitable. E.g. the compositor might return to On state on user input.
+
+              The client should not assume that the mode changed after requesting a new mode.
+              Instead the client should listen for the mode event.
+          </description>
+          <arg name="mode" type="uint" summary="Requested mode"/>
+      </request>
+      <request name="release" type="destructor">
+        <description summary="release the dpms object"/>
+      </request>
+  </interface>
+</protocol>
+

+ 13 - 13
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -58,7 +58,7 @@ std::filesystem::path ApplicationContext::resolvePlaylistItemPath (const std::st
 
     constexpr std::string_view windowsPrefix = "\\\\?\\";
 
-    if (cleaned.rfind (windowsPrefix, 0) == 0) {
+    if (cleaned.starts_with (windowsPrefix)) {
 	cleaned = cleaned.substr (windowsPrefix.length ());
     }
 
@@ -660,7 +660,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 
 	    this->settings.general.screenBackgrounds[lastScreen] = background;
 	    this->settings.general.defaultBackground = background;
-	    if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+	    if (lastScreen.starts_with ("span:") && !this->settings.general.spanGroups.empty ()) {
 		this->settings.general.spanGroups.back ().background = background;
 	    }
 	})
@@ -707,7 +707,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 
 	    if (this->settings.render.mode == DESKTOP_BACKGROUND) {
 		this->settings.general.screenScalings[lastScreen] = mode;
-		if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+		if (lastScreen.starts_with ("span:") && !this->settings.general.spanGroups.empty ()) {
 		    this->settings.general.spanGroups.back ().scaling = mode;
 		}
 	    } else {
@@ -736,7 +736,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 
 	    if (this->settings.render.mode == DESKTOP_BACKGROUND) {
 		this->settings.general.screenClamps[lastScreen] = flags;
-		if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+		if (lastScreen.starts_with ("span:") && !this->settings.general.spanGroups.empty ()) {
 		    this->settings.general.spanGroups.back ().clamp = flags;
 		}
 	    } else {
@@ -762,7 +762,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 
 	    if (this->settings.render.mode == DESKTOP_BACKGROUND) {
 		this->settings.general.screenZooms[lastScreen] = zoom;
-		if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+		if (lastScreen.starts_with ("span:") && !this->settings.general.spanGroups.empty ()) {
 		    this->settings.general.spanGroups.back ().zoom = zoom;
 		}
 	    } else {
@@ -796,7 +796,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 		return;
 	    }
 
-	    if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+	    if (lastScreen.starts_with ("span:") && !this->settings.general.spanGroups.empty ()) {
 		for (const auto& screen : this->settings.general.spanGroups.back ().screens) {
 		    this->settings.general.screenRenderScales[screen] = scale;
 		}
@@ -836,7 +836,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 
 	    if (this->settings.render.mode == DESKTOP_BACKGROUND) {
 		this->settings.general.screenOffsets[lastScreen] = offset;
-		if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+		if (lastScreen.starts_with ("span:") && !this->settings.general.spanGroups.empty ()) {
 		    this->settings.general.spanGroups.back ().offset = offset;
 		}
 	    } else {
@@ -873,7 +873,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 					  .first->second;
 		    alignment.*field = parsed;
 
-		    if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+		    if (lastScreen.starts_with ("span:") && !this->settings.general.spanGroups.empty ()) {
 			this->settings.general.spanGroups.back ().alignment.*field = parsed;
 		    }
 		} else {
@@ -925,7 +925,7 @@ void ApplicationContext::loadSettingsFromArgv () {
 
 	    if (this->settings.render.mode == DESKTOP_BACKGROUND) {
 		this->settings.general.screenCornerColors[lastScreen] = *color;
-		if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+		if (lastScreen.starts_with ("span:") && !this->settings.general.spanGroups.empty ()) {
 		    this->settings.general.spanGroups.back ().cornerColor = *color;
 		}
 	    } else {
@@ -937,7 +937,7 @@ void ApplicationContext::loadSettingsFromArgv () {
     const auto updateImageAdjustments = [this, &lastScreen] (const std::function<void (ImageAdjustments&)>& update) {
 	if (this->settings.render.mode == DESKTOP_BACKGROUND) {
 	    update (this->settings.general.screenImageAdjustments[lastScreen]);
-	    if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+	    if (lastScreen.starts_with ("span:") && !this->settings.general.spanGroups.empty ()) {
 		update (this->settings.general.spanGroups.back ().imageAdjustments);
 	    }
 	} else {
@@ -1831,13 +1831,13 @@ void ApplicationContext::loadSettingsFromArgv () {
 		this->settings.render.debug.brightnessLog = true;
 	    } else if (value == "no-puppet-animation") {
 		this->settings.render.debug.noPuppetAnimation = true;
-	    } else if (value.rfind ("object=", 0) == 0) {
+	    } else if (value.starts_with ("object=")) {
 		this->settings.render.debug.objectFilter = parseDebugId ("object=");
-	    } else if (value.rfind ("skip-object=", 0) == 0) {
+	    } else if (value.starts_with ("skip-object=")) {
 		if (const auto id = parseDebugId ("skip-object="); id.has_value ()) {
 		    this->settings.render.debug.skipObjects.emplace_back (*id);
 		}
-	    } else if (value.rfind ("skip-effect=", 0) == 0) {
+	    } else if (value.starts_with ("skip-effect=")) {
 		if (const auto id = parseDebugId ("skip-effect="); id.has_value ()) {
 		    this->settings.render.debug.skipEffects.emplace_back (*id);
 		}

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

@@ -6,9 +6,7 @@
 
 #include <cstdlib>
 
-#include "Steam/FileSystem/FileSystem.h"
 #include "WallpaperEngine/Application/ApplicationState.h"
-#include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h"
 #include "WallpaperEngine/Data/Utils/FiniteFloat.h"
 #ifdef ENABLE_WAYLAND
@@ -57,8 +55,6 @@
 #include <fstream>
 #include <numeric>
 #include <ranges>
-#include <string_view>
-#include <sys/stat.h>
 #include <unistd.h>
 #define STB_IMAGE_WRITE_IMPLEMENTATION
 #include <stb_image_write.h>
@@ -80,7 +76,7 @@ using namespace WallpaperEngine::Application;
 using namespace WallpaperEngine::Data::Model;
 using namespace WallpaperEngine::FileSystem;
 
-void CustomGLDebugCallback (
+static void CustomGLDebugCallback (
     GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam
 ) {
     if (severity == GL_DEBUG_SEVERITY_NOTIFICATION) {
@@ -198,7 +194,7 @@ void WallpaperApplication::loadBackgrounds () {
     }
 
     for (const auto& [screen, path] : this->m_context.settings.general.screenBackgrounds) {
-	if (screen.rfind ("span:", 0) == 0) {
+	if (screen.starts_with ("span:")) {
 	    continue;
 	}
 	if (path.empty ()) {
@@ -1257,11 +1253,11 @@ void WallpaperApplication::checkHotswapRequest () {
     }
 
     if (request.audioSensitivityProvided) {
-	for (const auto& [target, value] : request.audioSensitivity) {
+	for (const auto& [object, text] : request.audioSensitivity) {
 	    try {
-		this->m_context.settings.general.audioSensitivity[target] = parseFiniteFloat (value);
+		this->m_context.settings.general.audioSensitivity[object] = parseFiniteFloat (text);
 	    } catch (const std::exception&) {
-		sLog.error ("Hotswap: ignoring invalid audio-sensitivity value: ", value);
+		sLog.error ("Hotswap: ignoring invalid audio-sensitivity value: ", text);
 	    }
 	}
     }

+ 2 - 1
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -204,8 +204,9 @@ private:
     // the recorder replaced by ensureAudioCapture(), the outgoing wallpaper's passes still point into it
     std::unique_ptr<WallpaperEngine::Audio::Drivers::Recorders::PlaybackRecorder> m_previousAudioRecorder = nullptr;
     bool m_audioCapturing = false;
-    std::unique_ptr<WallpaperEngine::Render::RenderContext> m_renderContext = nullptr;
+    // the driver goes last: the render context's upload threads hold GL contexts of its display
     std::unique_ptr<WallpaperEngine::Render::Drivers::VideoDriver> m_videoDriver = nullptr;
+    std::unique_ptr<WallpaperEngine::Render::RenderContext> m_renderContext = nullptr;
     std::unique_ptr<WallpaperEngine::Render::Drivers::Detectors::FullScreenDetector> m_fullScreenDetector = nullptr;
     std::unique_ptr<WallpaperEngine::WebBrowser::WebBrowserContext> m_browserContext = nullptr;
     std::unique_ptr<WallpaperEngine::Media::MediaSource> m_mediaSource = nullptr;

+ 2 - 3
src/WallpaperEngine/Audio/AudioStream.cpp

@@ -2,7 +2,6 @@
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Logging/ThreadGuard.h"
 #include <algorithm>
-#include <cassert>
 #include <cmath>
 #include <iostream>
 
@@ -17,7 +16,7 @@ constexpr uint32_t MaxPitch = 10;
 constexpr size_t MaxResamplerPadding = 48;
 }
 
-int audio_read_thread (void* arg) {
+static int audio_read_thread (void* arg) {
     SDL_mutex* waitMutex = SDL_CreateMutex ();
     auto* stream = static_cast<AudioStream*> (arg);
     AVPacket* packet = av_packet_alloc ();
@@ -82,7 +81,7 @@ static int audio_read_data_callback (void* streamarg, uint8_t* buffer, int buffe
     return stream->getBuffer ()->gcount ();
 }
 
-int64_t audio_seek_data_callback (void* streamarg, int64_t offset, int whence) {
+static int64_t audio_seek_data_callback (void* streamarg, int64_t offset, int whence) {
     const auto stream = static_cast<AudioStream*> (streamarg);
 
     stream->getBuffer ()->clear ();

+ 1 - 1
src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.cpp

@@ -4,7 +4,7 @@
 #include <unistd.h>
 
 namespace WallpaperEngine::Audio::Drivers::Detectors {
-void sinkInputInfoCallback (pa_context* context, const pa_sink_input_info* info, int eol, void* userdata) {
+static void sinkInputInfoCallback (pa_context* context, const pa_sink_input_info* info, int eol, void* userdata) {
     auto* detector = static_cast<PulseAudioPlayingDetector*> (userdata);
 
     if (eol != 0 || info == nullptr) {

+ 3 - 3
src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.cpp

@@ -15,7 +15,7 @@ void PlaybackRecorder::update (float dt) {
 }
 
 int PlaybackRecorder::addSpectrumListener (SpectrumListener listener) {
-    std::lock_guard guard (this->m_listenersMutex);
+    Debugging::LockGuard guard (this->m_listenersMutex);
 
     const int id = ++this->m_nextListenerId;
     this->m_listeners.emplace (id, std::move (listener));
@@ -24,13 +24,13 @@ int PlaybackRecorder::addSpectrumListener (SpectrumListener listener) {
 }
 
 void PlaybackRecorder::removeSpectrumListener (int id) {
-    std::lock_guard guard (this->m_listenersMutex);
+    Debugging::LockGuard guard (this->m_listenersMutex);
 
     this->m_listeners.erase (id);
 }
 
 void PlaybackRecorder::notifySpectrumListeners (const float* bands) {
-    std::lock_guard guard (this->m_listenersMutex);
+    Debugging::LockGuard guard (this->m_listenersMutex);
 
     for (const auto& listener : this->m_listeners | std::views::values) {
 	listener (bands);

+ 4 - 3
src/WallpaperEngine/Audio/Drivers/Recorders/PlaybackRecorder.h

@@ -5,6 +5,7 @@
 #include <mutex>
 
 #include "WallpaperEngine/Audio/SpectrumProcessor.h"
+#include "WallpaperEngine/Debugging/ThreadSafety.h"
 
 namespace WallpaperEngine::Audio::Drivers::Recorders {
 class PlaybackRecorder {
@@ -38,8 +39,8 @@ protected:
     float m_captured[128] = { 0 };
 
 private:
-    std::mutex m_listenersMutex;
-    std::map<int, SpectrumListener> m_listeners;
-    int m_nextListenerId = 0;
+    Debugging::Mutex m_listenersMutex;
+    std::map<int, SpectrumListener> m_listeners LWE_GUARDED_BY (m_listenersMutex);
+    int m_nextListenerId LWE_GUARDED_BY (m_listenersMutex) = 0;
 };
 }

+ 5 - 6
src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp

@@ -6,7 +6,6 @@
 #include <chrono>
 #include <cmath>
 #include <cstdlib>
-#include <cstring>
 #include <ctime>
 #include <iomanip>
 #include <pulse/rtclock.h>
@@ -34,7 +33,7 @@ namespace {
 
 void pa_server_info_cb (pa_context* ctx, const pa_server_info* info, void* userdata);
 
-void pa_retry_capture_cb (pa_mainloop_api* api, pa_time_event* event, const struct timeval*, void* userdata) {
+static void pa_retry_capture_cb (pa_mainloop_api* api, pa_time_event* event, const struct timeval*, void* userdata) {
     auto* recorder = static_cast<PulseAudioPlaybackRecorder::PulseAudioData*> (userdata);
 
     api->time_free (event);
@@ -55,7 +54,7 @@ void pa_retry_capture_cb (pa_mainloop_api* api, pa_time_event* event, const stru
     }
 }
 
-void pa_stream_notify_cb (pa_stream* stream, void* userdata) {
+static void pa_stream_notify_cb (pa_stream* stream, void* userdata) {
     auto* recorder = static_cast<PulseAudioPlaybackRecorder::PulseAudioData*> (userdata);
 
     switch (pa_stream_get_state (stream)) {
@@ -91,7 +90,7 @@ void pa_stream_notify_cb (pa_stream* stream, void* userdata) {
     }
 }
 
-void pa_stream_read_cb (pa_stream* stream, const size_t, void* userdata) {
+static void pa_stream_read_cb (pa_stream* stream, const size_t, void* userdata) {
     auto* recorder = static_cast<PulseAudioPlaybackRecorder::PulseAudioData*> (userdata);
 
     const void* data = nullptr;
@@ -181,14 +180,14 @@ void pa_server_info_cb (pa_context* ctx, const pa_server_info* info, void* userd
     }
 }
 
-void pa_context_subscribe_cb (pa_context* ctx, pa_subscription_event_type_t t, uint32_t idx, void* userdata) {
+static void pa_context_subscribe_cb (pa_context* ctx, pa_subscription_event_type_t t, uint32_t idx, void* userdata) {
     pa_operation* o = pa_context_get_server_info (ctx, &pa_server_info_cb, userdata);
     if (o) {
 	pa_operation_unref (o);
     }
 }
 
-void pa_context_notify_cb (pa_context* ctx, void* userdata) {
+static void pa_context_notify_cb (pa_context* ctx, void* userdata) {
     switch (pa_context_get_state (ctx)) {
 	case PA_CONTEXT_READY:
 	    {

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

@@ -2,7 +2,6 @@
 #include "WallpaperEngine/Logging/Log.h"
 
 #include <algorithm>
-#include <cfloat>
 #include <cstring>
 
 #define SDL_AUDIO_BUFFER_SIZE 1024
@@ -133,7 +132,7 @@ void SDLAudioDriver::mixUpdate (float* out, int frames) {
 	bool viaHrtf = false;
 
 	if (hrtf != nullptr) {
-	    std::lock_guard lock (buffer->hrtfMutex);
+	    Debugging::LockGuard lock (buffer->hrtfMutex);
 
 	    if (buffer->hrtfSet) {
 		buffer->hrtfMixing = buffer->hrtf;
@@ -425,7 +424,7 @@ void SDLAudioDriver::setStreamPaused (int streamId, bool paused) {
 void SDLAudioDriver::setStreamHrtf (int streamId, const StreamHrtf* hrtf) {
     // same reasoning as setStreamVolume for the lookup, the filters themselves are copied under the stream's lock
     if (const auto it = this->m_streams.find (streamId); it != this->m_streams.end ()) {
-	std::lock_guard lock (it->second->hrtfMutex);
+	Debugging::LockGuard lock (it->second->hrtfMutex);
 
 	it->second->hrtfSet = hrtf != nullptr;
 

+ 4 - 3
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.h

@@ -11,6 +11,7 @@
 #include "WallpaperEngine/Audio/Drivers/Detectors/HeadphonesDetector.h"
 #include "WallpaperEngine/Audio/Hrtf.h"
 
+#include "WallpaperEngine/Debugging/ThreadSafety.h"
 #include <SDL.h>
 
 namespace WallpaperEngine::Audio::Drivers {
@@ -36,9 +37,9 @@ struct SDLAudioBuffer {
     bool pauseFaded = false;
     std::vector<float> replay;
 
-    std::mutex hrtfMutex;
-    bool hrtfSet = false;
-    StreamHrtf hrtf {};
+    Debugging::Mutex hrtfMutex;
+    bool hrtfSet LWE_GUARDED_BY (hrtfMutex) = false;
+    StreamHrtf hrtf LWE_GUARDED_BY (hrtfMutex) {};
 
     /** audio callback only: the filters of this callback, OpenAL's voice state and the decoded input */
     StreamHrtf hrtfMixing {};

+ 0 - 1
src/WallpaperEngine/Audio/SpectrumAnalyzer.cpp

@@ -2,7 +2,6 @@
 
 #include <algorithm>
 #include <cmath>
-#include <cstdlib>
 
 using namespace WallpaperEngine::Audio;
 

+ 3 - 0
src/WallpaperEngine/Data/Assets/Texture.h

@@ -120,6 +120,9 @@ struct Mipmap {
     std::unique_ptr<char[]> uncompressedData = nullptr;
     std::vector<MipmapPatch> patches {};
     std::vector<unsigned char> composedPixels {};
+    std::shared_ptr<unsigned char> decodedPixels = nullptr;
+    int decodedWidth = 0;
+    int decodedHeight = 0;
 };
 
 struct TextureCondition {

+ 1 - 1
src/WallpaperEngine/Data/Builders/ColorBuilder.cpp

@@ -19,7 +19,7 @@ WallpaperEngine::Data::Builders::ColorBuilder::parse (const std::string& value,
 	std::ranges::replace (copy, ',', ' ');
     }
 
-    if (copy.find ('#') == 0) {
+    if (copy.starts_with ('#')) {
 	auto number = copy.substr (1);
 
 	if (number.size () == 3) {

+ 15 - 21
src/WallpaperEngine/Data/Model/DynamicValue.cpp

@@ -1,9 +1,7 @@
 #include "DynamicValue.h"
 #include "UserSetting.h"
 
-#include "WallpaperEngine/Data/Utils/ScopeGuard.h"
 #include "WallpaperEngine/Logging/Log.h"
-#include "WallpaperEngine/Scripting/ScriptEngine.h"
 
 #include <climits>
 
@@ -173,6 +171,16 @@ void DynamicValue::update (const glm::vec4& newValue, UpdateSource source) {
     this->propagate (source);
 }
 
+void DynamicValue::setBoolean (bool value) {
+    this->m_vec2 = glm::vec2 (value ? 1.0f : 0.0f);
+    this->m_vec3 = glm::vec3 (value ? 1.0f : 0.0f);
+    this->m_vec4 = glm::vec4 (value ? 1.0f : 0.0f);
+    this->m_float = value ? 1.0f : 0.0f;
+    this->m_int = value ? 1 : 0;
+    this->m_bool = value;
+    this->m_type = UnderlyingType::Boolean;
+}
+
 void DynamicValue::update (const std::string& newValue, UpdateSource source) {
     this->m_vec2 = glm::vec2 (0.0f);
     this->m_vec3 = glm::vec3 (0.0f);
@@ -184,14 +192,7 @@ void DynamicValue::update (const std::string& newValue, UpdateSource source) {
     this->m_type = UnderlyingType::String;
 
     if (this->m_condition.has_value ()) {
-	const bool boolValue = this->m_condition.value ().condition == newValue;
-	this->m_vec2 = glm::vec2 (boolValue ? 1.0f : 0.0f);
-	this->m_vec3 = glm::vec3 (boolValue ? 1.0f : 0.0f);
-	this->m_vec4 = glm::vec4 (boolValue ? 1.0f : 0.0f);
-	this->m_float = boolValue ? 1.0f : 0.0f;
-	this->m_int = boolValue ? 1 : 0;
-	this->m_bool = boolValue;
-	this->m_type = UnderlyingType::Boolean;
+	this->setBoolean (this->m_condition.value ().condition == newValue);
     }
 
     this->propagate (source);
@@ -234,14 +235,7 @@ void DynamicValue::update (const DynamicValue& other, UpdateSource source) {
     this->m_type = isVector && isScalar ? keptType : other.getType ();
 
     if (this->m_condition.has_value () && other.getType () == UnderlyingType::String) {
-	const bool boolValue = this->m_condition.value ().condition == other.getString ();
-	this->m_vec2 = glm::vec2 (boolValue ? 1.0f : 0.0f);
-	this->m_vec3 = glm::vec3 (boolValue ? 1.0f : 0.0f);
-	this->m_vec4 = glm::vec4 (boolValue ? 1.0f : 0.0f);
-	this->m_float = boolValue ? 1.0f : 0.0f;
-	this->m_int = boolValue ? 1 : 0;
-	this->m_bool = boolValue;
-	this->m_type = UnderlyingType::Boolean;
+	this->setBoolean (this->m_condition.value ().condition == other.getString ());
     }
 
     this->propagate (source);
@@ -279,12 +273,12 @@ std::function<void ()> DynamicValue::listen (const std::function<void (const Dyn
 }
 
 void DynamicValue::connect (DynamicValue* other) {
-    const auto lambda = [this] (const DynamicValue& other, UpdateSource source) {
+    const auto lambda = [this] (const DynamicValue& from, UpdateSource source) {
 	// null needs the no-arg update() - copying everything to 0 is a different meaning
-	if (other.getType () == UnderlyingType::Null) {
+	if (from.getType () == UnderlyingType::Null) {
 	    this->update (source);
 	} else {
-	    this->update (other, source);
+	    this->update (from, source);
 	}
     };
 

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

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

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

@@ -36,7 +36,7 @@ public:
     explicit Property (PropertyData data) : DynamicValue (), TypeCaster (), PropertyData (std::move (data)) { }
 
     using DynamicValue::update;
-    virtual void update (const std::string& value, UpdateSource source) = 0;
+    void update (const std::string& value, UpdateSource source) override = 0;
     [[nodiscard]] virtual std::string dump () const = 0;
 
     void pin () const { this->m_pinned = true; }

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

@@ -6,11 +6,9 @@
 #include <cmath>
 #include <cstdlib>
 
-#include "WallpaperEngine/Data/Model/DynamicValue.h"
 #include "WallpaperEngine/Data/Model/Effect.h"
 #include "WallpaperEngine/Data/Model/Material.h"
 #include "WallpaperEngine/Data/Model/Project.h"
-#include "WallpaperEngine/FileSystem/Container.h"
 
 using namespace WallpaperEngine::Data::Parsers;
 using namespace WallpaperEngine::Data::Model;

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

@@ -1,11 +1,12 @@
 #include "MaterialParser.h"
 
+#include <ranges>
+
 #include "ComboValue.h"
 #include "TextureParser.h"
 #include "WallpaperEngine/Data/Model/Material.h"
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Data/Parsers/ShaderConstantParser.h"
-#include "WallpaperEngine/FileSystem/Container.h"
 
 using namespace WallpaperEngine::Data::Parsers;
 using namespace WallpaperEngine::Data::Model;
@@ -25,6 +26,26 @@ MaterialUniquePtr MaterialParser::load (const Project& project, const std::strin
     return parse (materialJson, filename, project);
 }
 
+std::vector<std::string> MaterialParser::textureNames (const Project& project, const std::string& filename) {
+    std::vector<std::string> names;
+
+    try {
+	const auto json = JSON::parseAsset (project.assetLocator->readString (filename));
+	const auto passes = json.find ("passes");
+	const bool hasPasses = passes != json.end () && passes->is_array () && !passes->empty ();
+	const auto textures = (hasPasses ? passes->front () : json).optional ("textures");
+
+	if (textures.has_value ()) {
+	    for (const auto& texture : TextureParser::parseTextureMap (*textures) | std::views::values) {
+		names.push_back (texture);
+	    }
+	}
+    } catch (const std::exception&) {
+    }
+
+    return names;
+}
+
 MaterialUniquePtr MaterialParser::parse (const JSON& it, const std::string& filename, const Project& project) {
     const auto passes = it.find ("passes");
     // WE only reads the first entry of "passes", without one the material's root is the pass

+ 3 - 0
src/WallpaperEngine/Data/Parsers/MaterialParser.h

@@ -11,6 +11,9 @@ using namespace WallpaperEngine::Data::Model;
 class MaterialParser {
 public:
     static MaterialUniquePtr load (const Project& project, const std::string& filename);
+    /** The textures the first pass names, without building the material: safe off the main thread, nothing is connected
+     * to the project's properties */
+    static std::vector<std::string> textureNames (const Project& project, const std::string& filename);
     static MaterialUniquePtr parse (const JSON& it, const std::string& filename, const Project& project);
     static MaterialPassUniquePtr parsePass (const JSON& it, const Project& project);
     static std::map<std::string, int> parseCombos (const JSON& it);

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

@@ -1,11 +1,9 @@
 #include "ModelParser.h"
 #include "MaterialParser.h"
 
-#include "WallpaperEngine/Data/Model/DynamicValue.h"
 #include "WallpaperEngine/Data/Model/Material.h"
 #include "WallpaperEngine/Data/Model/Model.h"
 #include "WallpaperEngine/Data/Model/Project.h"
-#include "WallpaperEngine/FileSystem/Container.h"
 
 using namespace WallpaperEngine::Data::Parsers;
 using namespace WallpaperEngine::Data::Model;

+ 62 - 93
src/WallpaperEngine/Data/Parsers/ObjectParser.cpp

@@ -7,17 +7,14 @@
 
 #include "ShaderConstantParser.h"
 #include "TextureParser.h"
-#include "UserSettingParser.h"
 #include "WallpaperEngine/Data/Builders/ColorBuilder.h"
 #include "WallpaperEngine/Data/Builders/UserSettingBuilder.h"
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Model/Project.h"
-#include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Maths.h"
 
 #include <cmath>
-#include <glm/gtc/constants.hpp>
 #include <glm/gtc/matrix_transform.hpp>
 #include <sstream>
 
@@ -25,6 +22,47 @@ using namespace WallpaperEngine::Data::Parsers;
 using namespace WallpaperEngine::Data::Model;
 
 namespace {
+ParticleInstanceOverride defaultInstanceOverride () {
+    return ParticleInstanceOverride {
+	.enabled = WallpaperEngine::Data::Builders::UserSettingBuilder::fromValue (false),
+	.alpha = WallpaperEngine::Data::Builders::UserSettingBuilder::fromValue (1.0f),
+	.size = WallpaperEngine::Data::Builders::UserSettingBuilder::fromValue (1.0f),
+	.lifetime = WallpaperEngine::Data::Builders::UserSettingBuilder::fromValue (1.0f),
+	.rate = WallpaperEngine::Data::Builders::UserSettingBuilder::fromValue (1.0f),
+	.speed = WallpaperEngine::Data::Builders::UserSettingBuilder::fromValue (1.0f),
+	.count = WallpaperEngine::Data::Builders::UserSettingBuilder::fromValue (1.0f),
+	.brightness = WallpaperEngine::Data::Builders::UserSettingBuilder::fromValue (1.0f),
+	.color = WallpaperEngine::Data::Builders::UserSettingBuilder::fromValue (1.0f),
+	.colorn = WallpaperEngine::Data::Builders::UserSettingBuilder::fromValue (1.0f),
+    };
+}
+
+std::string stringField (const JSON& it, const char* key, std::string fallback) {
+    const auto valueIt = it.find (key);
+    if (valueIt != it.end () && valueIt->is_string ()) {
+	return valueIt->get<std::string> ();
+    }
+    return fallback;
+}
+
+glm::vec3 vec3Field (const JSON& it, const char* fieldName, const glm::vec3& defaultValue) {
+    const auto fieldIt = it.find (fieldName);
+    if (fieldIt == it.end ()) {
+	return defaultValue;
+    }
+    if (fieldIt->is_string ()) {
+	return it.optional (fieldName, defaultValue);
+    }
+    if (fieldIt->is_number ()) {
+	float val = fieldIt->get<float> ();
+	return glm::vec3 (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 defaultValue;
+}
+
 /** For settings whose default depends on the scene (wallpaper64.exe picks 2D or 3D defaults), null if not set */
 UserSettingUniquePtr userIfSet (const JSON& it, const std::string& key, const Properties& properties) {
     return it.optional (key).has_value () ? it.user (key, properties) : nullptr;
@@ -293,11 +331,10 @@ ObjectUniquePtr ObjectParser::parseObject (const JSON& it, const Project& projec
     const bool reflected = reflectedIt == it.end () || !reflectedIt->is_boolean () || reflectedIt->get<bool> ();
 
     // some particle objects have numeric 'name' fields, so handle type mismatches gracefully
-    ObjectData basedata;
-    try {
-	basedata = ObjectData {
-	    .id = it.require<int> ("id", "Object must have an id"),
-	    .name = it.require<std::string> ("name", "Object must have a name"),
+    auto makeBaseData = [&] (int id, std::string name) {
+	return ObjectData {
+	    .id = id,
+	    .name = std::move (name),
 	    .dependencies = parseDependencies (it),
 	    .componentDependencies = parseComponentDependencies (it),
 	    .parent = it.optional<int> ("parent"),
@@ -314,6 +351,14 @@ ObjectUniquePtr ObjectParser::parseObject (const JSON& it, const Project& projec
 	    .perspective = it.user ("perspective", project.properties, false),
 	    .reflected = reflected,
 	};
+    };
+
+    ObjectData basedata;
+    try {
+	basedata = makeBaseData (
+	    it.require<int> ("id", "Object must have an id"),
+	    it.require<std::string> ("name", "Object must have a name")
+	);
     } catch (const std::exception& e) {
 	sLog.error ("Error parsing object base data: ", e.what ());
 	const auto idIt = it.find ("id");
@@ -327,25 +372,7 @@ ObjectUniquePtr ObjectParser::parseObject (const JSON& it, const Project& projec
 		name = std::to_string (nameIt->get<int> ());
 	    }
 	}
-	basedata = ObjectData {
-	    .id = id,
-	    .name = name,
-	    .dependencies = parseDependencies (it),
-	    .componentDependencies = parseComponentDependencies (it),
-	    .parent = it.optional<int> ("parent"),
-	    .attachment = it.optional<std::string> ("attachment"),
-	    .sortOrder = it.optional<int> ("sortorder"),
-	    .sortOrderValue = it.user ("sortorder", project.properties, 0),
-	    .origin = it.user ("origin", project.properties, glm::vec3 (0.0f)),
-	    .groupScale = it.user ("scale", project.properties, glm::vec3 (1.0f)),
-	    .groupAngles = it.user ("angles", project.properties, glm::vec3 (0.0f)),
-	    .groupVisible = it.user ("visible", project.properties, true),
-	    .groupParallaxDepth = it.user ("parallaxDepth", project.properties, glm::vec2 (1.0f)),
-	    .solid = it.user ("solid", project.properties, true),
-	    .disablePropagation = it.user ("disablepropagation", project.properties, false),
-	    .perspective = it.user ("perspective", project.properties, false),
-	    .reflected = reflected,
-	};
+	basedata = makeBaseData (id, std::move (name));
     }
 
     if (imageIt != it.end () && imageIt->is_string ()) {
@@ -987,18 +1014,7 @@ ParticleUniquePtr ObjectParser::parseParticle (const JSON& it, const Project& pr
 		    .renderers = {},
 		    .controlPoints = {},
 		    .children = {},
-		    .instanceOverride = {
-		        .enabled = Builders::UserSettingBuilder::fromValue(false),
-			.alpha = Builders::UserSettingBuilder::fromValue(1.0f),
-			.size = Builders::UserSettingBuilder::fromValue(1.0f),
-			.lifetime = Builders::UserSettingBuilder::fromValue(1.0f),
-			.rate = Builders::UserSettingBuilder::fromValue(1.0f),
-			.speed = Builders::UserSettingBuilder::fromValue(1.0f),
-			.count = Builders::UserSettingBuilder::fromValue(1.0f),
-			.brightness = Builders::UserSettingBuilder::fromValue(1.0f),
-			.color = Builders::UserSettingBuilder::fromValue(1.0f),
-			.colorn = Builders::UserSettingBuilder::fromValue(1.0f),
-		    },
+		    .instanceOverride = defaultInstanceOverride (),
 		}
 	    );
 	}
@@ -1122,18 +1138,7 @@ ParticleUniquePtr ObjectParser::parseParticle (const JSON& it, const Project& pr
 	    }
 	}
 
-	ParticleInstanceOverride instanceOverride = {
-	    .enabled = Builders::UserSettingBuilder::fromValue (false),
-	    .alpha = Builders::UserSettingBuilder::fromValue (1.0f),
-	    .size = Builders::UserSettingBuilder::fromValue (1.0f),
-	    .lifetime = Builders::UserSettingBuilder::fromValue (1.0f),
-	    .rate = Builders::UserSettingBuilder::fromValue (1.0f),
-	    .speed = Builders::UserSettingBuilder::fromValue (1.0f),
-	    .count = Builders::UserSettingBuilder::fromValue (1.0f),
-	    .brightness = Builders::UserSettingBuilder::fromValue (1.0f),
-	    .color = Builders::UserSettingBuilder::fromValue (1.0f),
-	    .colorn = Builders::UserSettingBuilder::fromValue (1.0f),
-	};
+	ParticleInstanceOverride instanceOverride = defaultInstanceOverride ();
 	const auto instanceOverrideIt = it.optional ("instanceoverride");
 	if (instanceOverrideIt.has_value ()) {
 	    instanceOverride = parseParticleInstanceOverride (*instanceOverrideIt, project.properties);
@@ -1234,28 +1239,10 @@ ParticleUniquePtr ObjectParser::parseParticle (const JSON& it, const Project& pr
 }
 
 ParticleEmitter ObjectParser::parseParticleEmitter (const JSON& it) {
-    std::string name;
-    const auto nameIt = it.find ("name");
-    if (nameIt != it.end () && nameIt->is_string ()) {
-	name = nameIt->get<std::string> ();
-    }
+    std::string name = stringField (it, "name", "");
 
-    auto parseVec3 = [&] (const char* fieldName, const glm::vec3& defaultValue) -> glm::vec3 {
-	const auto fieldIt = it.find (fieldName);
-	if (fieldIt == it.end ()) {
-	    return defaultValue;
-	}
-	if (fieldIt->is_string ()) {
-	    return it.optional (fieldName, defaultValue);
-	}
-	if (fieldIt->is_number ()) {
-	    float val = fieldIt->get<float> ();
-	    return glm::vec3 (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 defaultValue;
+    auto parseVec3 = [&] (const char* fieldName, const glm::vec3& defaultValue) {
+	return vec3Field (it, fieldName, defaultValue);
     };
 
     auto parseVec2 = [&] (const char* fieldName, const glm::vec2& defaultValue) -> glm::vec2 {
@@ -1710,28 +1697,10 @@ ParticleChild ObjectParser::parseParticleChild (
 	sLog.error ("Unknown particle child type ", typeName, ", treating it as static");
     }
 
-    std::string name = "";
-    const auto nameIt = it.find ("name");
-    if (nameIt != it.end () && nameIt->is_string ()) {
-	name = nameIt->get<std::string> ();
-    }
+    std::string name = stringField (it, "name", "");
 
-    auto parseVec3 = [&] (const char* fieldName, const glm::vec3& defaultValue) -> glm::vec3 {
-	const auto fieldIt = it.find (fieldName);
-	if (fieldIt == it.end ()) {
-	    return defaultValue;
-	}
-	if (fieldIt->is_string ()) {
-	    return it.optional (fieldName, defaultValue);
-	}
-	if (fieldIt->is_number ()) {
-	    float val = fieldIt->get<float> ();
-	    return glm::vec3 (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 defaultValue;
+    auto parseVec3 = [&] (const char* fieldName, const glm::vec3& defaultValue) {
+	return vec3Field (it, fieldName, defaultValue);
     };
 
     const glm::vec3 angles = parseVec3 ("angles", glm::vec3 (0.0f));

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

@@ -10,7 +10,6 @@
 #include "PropertyParser.h"
 #include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
-#include "WallpaperEngine/FileSystem/Container.h"
 
 using namespace WallpaperEngine::Data::Parsers;
 

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

@@ -1,7 +1,5 @@
 #include <algorithm>
-#include <cmath>
 #include <cstdlib>
-#include <cstring>
 
 #include <lz4.h>
 #include <nlohmann/json.hpp>

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

@@ -5,7 +5,6 @@
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
-#include "WallpaperEngine/FileSystem/Container.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 #include <algorithm>
@@ -316,6 +315,11 @@ WallpaperUniquePtr WallpaperParser::parse (const JSON& file, Project& project) {
 
 SceneUniquePtr WallpaperParser::parseScene (const JSON& file, Project& project) {
     const auto scene = JSON::parseAsset (project.assetLocator->readString (file));
+
+    if (scene.is_object () && !scene.contains ("camera") && !scene.contains ("objects") && scene.contains ("script")) {
+	sLog.exception ("This is a script module, not a wallpaper");
+    }
+
     const auto camera = scene.require ("camera", "Scenes must have a camera section");
     const auto general = scene.require ("general", "Scenes must have a general section");
     // sub_140186C90: the scene is orthographic only when the member is an object that says "auto": true or has a

+ 1 - 11
src/WallpaperEngine/Data/Utils/BinaryReader.cpp

@@ -23,17 +23,7 @@ uint32_t BinaryReader::nextUInt32 () const {
     }
 }
 
-int BinaryReader::nextInt () const {
-    char buffer[4] = {};
-
-    this->m_input->read (buffer, 4);
-
-    if constexpr (std::endian::native == std::endian::little) {
-	return (buffer[3] & 0xFF) << 24 | (buffer[2] & 0xFF) << 16 | (buffer[1] & 0xFF) << 8 | (buffer[0] & 0xFF);
-    } else {
-	return (buffer[0] & 0xFF) << 24 | (buffer[1] & 0xFF) << 16 | (buffer[2] & 0xFF) << 8 | (buffer[3] & 0xFF);
-    }
-}
+int BinaryReader::nextInt () const { return static_cast<int> (this->nextUInt32 ()); }
 
 float BinaryReader::nextFloat () const {
     float result = 0.0f;

+ 0 - 1
src/WallpaperEngine/Debugging/CallStack.cpp

@@ -38,7 +38,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 //
 
 #include "CallStack.h"
-#include <cassert>
 #include <cstdio>
 #include <cstdlib>
 #include <string>

+ 74 - 0
src/WallpaperEngine/Debugging/ThreadSafety.h

@@ -0,0 +1,74 @@
+#pragma once
+
+#include <mutex>
+
+// libstdc++'s std::mutex has no capability attributes, so clang's -Wthread-safety can't see which data a lock guards.
+// Mutex, LockGuard and UniqueLock carry them; the attributes expand to nothing elsewhere
+#if defined(__clang__)
+#define LWE_TSA(attribute) __attribute__ ((attribute))
+#else
+#define LWE_TSA(attribute)
+#endif
+
+#define LWE_CAPABILITY(name) LWE_TSA (capability (name))
+#define LWE_SCOPED_CAPABILITY LWE_TSA (scoped_lockable)
+#define LWE_GUARDED_BY(mutex) LWE_TSA (guarded_by (mutex))
+#define LWE_REQUIRES(mutex) LWE_TSA (requires_capability (mutex))
+#define LWE_ACQUIRE(...) LWE_TSA (acquire_capability (__VA_ARGS__))
+#define LWE_RELEASE(...) LWE_TSA (release_capability (__VA_ARGS__))
+#define LWE_TRY_ACQUIRE(...) LWE_TSA (try_acquire_capability (__VA_ARGS__))
+#define LWE_EXCLUDES(...) LWE_TSA (locks_excluded (__VA_ARGS__))
+#define LWE_NO_THREAD_SAFETY_ANALYSIS LWE_TSA (no_thread_safety_analysis)
+
+namespace WallpaperEngine::Debugging {
+class LWE_CAPABILITY ("mutex") Mutex {
+public:
+    void lock () LWE_ACQUIRE () { this->m_mutex.lock (); }
+    void unlock () LWE_RELEASE () { this->m_mutex.unlock (); }
+    bool try_lock () LWE_TRY_ACQUIRE (true) { return this->m_mutex.try_lock (); }
+
+private:
+    std::mutex m_mutex;
+};
+
+class LWE_SCOPED_CAPABILITY LockGuard {
+public:
+    explicit LockGuard (Mutex& mutex) LWE_ACQUIRE (mutex) : m_mutex (mutex) { this->m_mutex.lock (); }
+    ~LockGuard () LWE_RELEASE () { this->m_mutex.unlock (); }
+
+    LockGuard (const LockGuard&) = delete;
+    LockGuard& operator= (const LockGuard&) = delete;
+
+private:
+    Mutex& m_mutex;
+};
+
+class LWE_SCOPED_CAPABILITY UniqueLock {
+public:
+    explicit UniqueLock (Mutex& mutex) LWE_ACQUIRE (mutex) : m_mutex (mutex) {
+	this->m_mutex.lock ();
+	this->m_locked = true;
+    }
+    ~UniqueLock () LWE_RELEASE () {
+	if (this->m_locked) {
+	    this->m_mutex.unlock ();
+	}
+    }
+
+    void lock () LWE_ACQUIRE () {
+	this->m_mutex.lock ();
+	this->m_locked = true;
+    }
+    void unlock () LWE_RELEASE () {
+	this->m_locked = false;
+	this->m_mutex.unlock ();
+    }
+
+    UniqueLock (const UniqueLock&) = delete;
+    UniqueLock& operator= (const UniqueLock&) = delete;
+
+private:
+    Mutex& m_mutex;
+    bool m_locked = false;
+};
+}

+ 6 - 58
src/WallpaperEngine/Desktop/GnomeShell.cpp

@@ -3,15 +3,10 @@
 
 #include "WallpaperEngine/Logging/Log.h"
 
-#include <cstdlib>
 #include <cstring>
 #include <optional>
 #include <poll.h>
-#include <string_view>
 #include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/un.h>
-#include <system_error>
 #include <unistd.h>
 
 using namespace WallpaperEngine::Desktop;
@@ -132,29 +127,9 @@ int GnomeShell::openWaylandSocket () {
     }
 
     const std::string path = directory + "/lwe-gnome-" + processTag () + ".sock";
-    sockaddr_un address = {};
-    address.sun_family = AF_UNIX;
+    const int listener = listenOnSocket (path, this->m_reason);
 
-    if (path.size () >= sizeof (address.sun_path)) {
-	this->m_reason = "the runtime folder's path is too long for a socket";
-	return -1;
-    }
-
-    std::strncpy (address.sun_path, path.c_str (), sizeof (address.sun_path) - 1);
-    unlink (path.c_str ());
-
-    const int listener = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
-    const mode_t mask = umask (0077);
-    const bool bound = listener >= 0 && bind (listener, reinterpret_cast<sockaddr*> (&address), sizeof (address)) == 0
-	&& listen (listener, 1) == 0;
-    umask (mask);
-
-    if (!bound) {
-	this->m_reason
-	    = "cannot listen on " + path + ": " + std::error_code (errno, std::generic_category ()).message ();
-	if (listener >= 0) {
-	    close (listener);
-	}
+    if (listener < 0) {
 	return -1;
     }
 
@@ -205,40 +180,13 @@ GnomeShell::~GnomeShell () {
 }
 
 bool GnomeShell::connect () {
-    DBusError error;
-    dbus_error_init (&error);
-
-    // private, so we never eat messages meant for the shared connection
-    this->m_connection = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
-
-    if (dbus_error_is_set (&error)) {
-	this->m_reason = std::string ("no session bus: ") + error.message;
-	dbus_error_free (&error);
-	this->m_connection = nullptr;
-	return false;
-    }
-
-    dbus_connection_set_exit_on_disconnect (this->m_connection, false);
-
-    DBusMessage* message = dbus_message_new_method_call (
-	"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetNameOwner"
-    );
-    const char* name = BUS_NAME;
-    dbus_message_append_args (message, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
-
-    std::string callError;
-    DBusMessage* reply = callBlocking (this->m_connection, message, callError);
-
-    if (reply == nullptr) {
-	this->m_reason = "the linux-wallpaperengine GNOME Shell extension is not running (" + callError + ")";
+    if (!connectToService (
+	    this->m_connection, BUS_NAME, this->m_owner, this->m_reason,
+	    "the linux-wallpaperengine GNOME Shell extension is not running"
+	)) {
 	return false;
     }
 
-    const char* owner = nullptr;
-    dbus_message_get_args (reply, nullptr, DBUS_TYPE_STRING, &owner, DBUS_TYPE_INVALID);
-    this->m_owner = owner != nullptr ? owner : "";
-    dbus_message_unref (reply);
-
     // subscribe before querying so nothing is lost
     const std::string signals = std::string ("type='signal',sender='") + BUS_NAME + "',interface='" + INTERFACE
 	+ "',path='" + OBJECT_PATH + "'";

+ 3 - 19
src/WallpaperEngine/Desktop/HostWayland.cpp

@@ -5,13 +5,10 @@
 #include "WallpaperEngine/Logging/Log.h"
 
 #include <atomic>
-#include <cstring>
 #include <filesystem>
 #include <poll.h>
 #include <string_view>
 #include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/un.h>
 #include <sys/wait.h>
 #include <unistd.h>
 #include <vector>
@@ -104,25 +101,12 @@ int hostConnection () {
     // the app's runtime folder is the same path on the host
     const std::string path = directory + "/lwe-wayland-" + WallpaperEngine::Desktop::processTag () + "-"
 	+ std::to_string (g_helperCounter.fetch_add (1)) + ".sock";
-    sockaddr_un address = {};
-    address.sun_family = AF_UNIX;
-
-    if (path.size () >= sizeof (address.sun_path)) {
-	return -1;
-    }
-
-    std::strncpy (address.sun_path, path.c_str (), sizeof (address.sun_path) - 1);
-    unlink (path.c_str ());
-
-    const int listener = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
-    const mode_t mask = umask (0077);
-    const bool bound = listener >= 0 && bind (listener, reinterpret_cast<sockaddr*> (&address), sizeof (address)) == 0
-	&& listen (listener, 1) == 0;
-    umask (mask);
+    std::string reason;
+    const int listener = WallpaperEngine::Desktop::listenOnSocket (path, reason);
 
     int fd = -1;
 
-    if (bound) {
+    if (listener >= 0) {
 	// the sandbox's socket keeps the host's name unless that is a path or not "wayland-*", then it's wayland-0,
 	// left to the host's own WAYLAND_DISPLAY
 	const std::string name = std::filesystem::path (display != nullptr ? display : "wayland-0").filename ();

+ 4 - 28
src/WallpaperEngine/Desktop/HyprlandIPC.cpp

@@ -1,5 +1,7 @@
 #include "HyprlandIPC.h"
 
+#include "SessionBus.h"
+
 #include <algorithm>
 #include <cctype>
 #include <cstring>
@@ -11,35 +13,9 @@
 #include <unistd.h>
 
 namespace {
-int connectTo (const std::string& socketPath) {
-    sockaddr_un addr {};
-    if (socketPath.size () >= sizeof (addr.sun_path)) {
-	return -1;
-    }
-
-    const int fd = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
-    if (fd < 0) {
-	return -1;
-    }
-
-    timeval timeout {};
-    timeout.tv_usec = 50000;
-    addr.sun_family = AF_UNIX;
-    std::strncpy (addr.sun_path, socketPath.c_str (), sizeof (addr.sun_path) - 1);
-
-    if (setsockopt (fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof (timeout)) != 0
-	|| setsockopt (fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof (timeout)) != 0
-	|| connect (fd, reinterpret_cast<sockaddr*> (&addr), sizeof (addr)) != 0) {
-	close (fd);
-	return -1;
-    }
-
-    return fd;
-}
-
 /** the leftover socket of a crashed Hyprland refuses connections */
 bool isLive (const std::string& socketPath) {
-    const int fd = connectTo (socketPath);
+    const int fd = WallpaperEngine::Desktop::connectUnixSocket (socketPath, 50000);
     if (fd < 0) {
 	return false;
     }
@@ -112,7 +88,7 @@ std::string WallpaperEngine::Desktop::findHyprlandSocket (
 
 std::optional<std::string>
 WallpaperEngine::Desktop::hyprlandRequest (const std::string& socketPath, const std::string& request) {
-    const int fd = connectTo (socketPath);
+    const int fd = WallpaperEngine::Desktop::connectUnixSocket (socketPath, 50000);
     if (fd < 0) {
 	return std::nullopt;
     }

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

@@ -9,7 +9,6 @@
 #include <csignal>
 #include <cstdio>
 #include <cstdlib>
-#include <cstring>
 #include <fcntl.h>
 #include <mutex>
 #include <set>

+ 3 - 32
src/WallpaperEngine/Desktop/PantheonShell.cpp

@@ -3,9 +3,7 @@
 
 #include "WallpaperEngine/Logging/Log.h"
 
-#include <cstdlib>
 #include <cstring>
-#include <string_view>
 
 using namespace WallpaperEngine::Desktop;
 
@@ -128,39 +126,12 @@ PantheonShell::~PantheonShell () {
 }
 
 bool PantheonShell::connect () {
-    DBusError error;
-    dbus_error_init (&error);
-
-    this->m_connection = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
-
-    if (dbus_error_is_set (&error)) {
-	this->m_reason = std::string ("no session bus: ") + error.message;
-	dbus_error_free (&error);
-	this->m_connection = nullptr;
-	return false;
-    }
-
-    dbus_connection_set_exit_on_disconnect (this->m_connection, false);
-
-    DBusMessage* message = dbus_message_new_method_call (
-	"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetNameOwner"
-    );
-    const char* name = BUS_NAME;
-    dbus_message_append_args (message, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
-
-    std::string callError;
-    DBusMessage* reply = callBlocking (this->m_connection, message, callError);
-
-    if (reply == nullptr) {
-	this->m_reason = "Gala is not on the session bus (" + callError + ")";
+    if (!connectToService (
+	    this->m_connection, BUS_NAME, this->m_owner, this->m_reason, "Gala is not on the session bus"
+	)) {
 	return false;
     }
 
-    const char* owner = nullptr;
-    dbus_message_get_args (reply, nullptr, DBUS_TYPE_STRING, &owner, DBUS_TYPE_INVALID);
-    this->m_owner = owner != nullptr ? owner : "";
-    dbus_message_unref (reply);
-
     const std::string signals = std::string ("type='signal',sender='") + BUS_NAME + "',interface='" + INTERFACE
 	+ "',path='" + OBJECT_PATH + "'";
 

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

@@ -368,7 +368,9 @@ void PowerMonitor::run () {
 #endif
 
     auto nextBatteryCheck = Clock::now () + BATTERY_INTERVAL;
+#ifdef ENABLE_WAYLAND
     int appliedMinutes = 0;
+#endif
 
     while (!this->m_stop) {
 	const auto now = Clock::now ();
@@ -463,7 +465,9 @@ void PowerMonitor::run () {
 	    this->m_idle = false;
 	}
 
+#ifdef ENABLE_WAYLAND
 	appliedMinutes = minutes;
+#endif
 
 	pollfd fds[2] = {
 	    { .fd = this->m_wakeFd, .events = POLLIN, .revents = 0 },

+ 100 - 0
src/WallpaperEngine/Desktop/SessionBus.cpp

@@ -5,6 +5,10 @@
 #include <filesystem>
 #include <fstream>
 #include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/un.h>
+#include <system_error>
 #include <unistd.h>
 
 namespace {
@@ -194,3 +198,99 @@ int WallpaperEngine::Desktop::receiveDescriptor (int connection) {
     std::memcpy (&fd, CMSG_DATA (header), sizeof (int));
     return fd;
 }
+
+bool WallpaperEngine::Desktop::connectToService (
+    DBusConnection*& connection, const char* busName, std::string& owner, std::string& reason,
+    const std::string& notRunning
+) {
+    DBusError error;
+    dbus_error_init (&error);
+
+    // private, so we never eat messages meant for the shared connection
+    connection = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
+
+    if (dbus_error_is_set (&error)) {
+	reason = std::string ("no session bus: ") + error.message;
+	dbus_error_free (&error);
+	connection = nullptr;
+	return false;
+    }
+
+    dbus_connection_set_exit_on_disconnect (connection, false);
+
+    DBusMessage* message = dbus_message_new_method_call (
+	"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetNameOwner"
+    );
+    dbus_message_append_args (message, DBUS_TYPE_STRING, &busName, DBUS_TYPE_INVALID);
+
+    std::string callError;
+    DBusMessage* reply = callBlocking (connection, message, callError);
+
+    if (reply == nullptr) {
+	reason = notRunning + " (" + callError + ")";
+	return false;
+    }
+
+    const char* name = nullptr;
+    dbus_message_get_args (reply, nullptr, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
+    owner = name != nullptr ? name : "";
+    dbus_message_unref (reply);
+    return true;
+}
+
+int WallpaperEngine::Desktop::listenOnSocket (const std::string& path, std::string& reason) {
+    sockaddr_un address = {};
+    address.sun_family = AF_UNIX;
+
+    if (path.size () >= sizeof (address.sun_path)) {
+	reason = "the runtime folder's path is too long for a socket";
+	return -1;
+    }
+
+    std::strncpy (address.sun_path, path.c_str (), sizeof (address.sun_path) - 1);
+    unlink (path.c_str ());
+
+    const int listener = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+    const mode_t mask = umask (0077);
+    const bool bound = listener >= 0 && bind (listener, reinterpret_cast<sockaddr*> (&address), sizeof (address)) == 0
+	&& listen (listener, 1) == 0;
+    umask (mask);
+
+    if (!bound) {
+	reason = "cannot listen on " + path + ": " + std::error_code (errno, std::generic_category ()).message ();
+	if (listener >= 0) {
+	    close (listener);
+	}
+	unlink (path.c_str ());
+	return -1;
+    }
+
+    return listener;
+}
+
+int WallpaperEngine::Desktop::connectUnixSocket (const std::string& socketPath, const long timeoutMicros) {
+    sockaddr_un addr {};
+    if (socketPath.size () >= sizeof (addr.sun_path)) {
+	return -1;
+    }
+
+    const int fd = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+    if (fd < 0) {
+	return -1;
+    }
+
+    timeval timeout {};
+    timeout.tv_sec = timeoutMicros / 1000000;
+    timeout.tv_usec = timeoutMicros % 1000000;
+    addr.sun_family = AF_UNIX;
+    std::strncpy (addr.sun_path, socketPath.c_str (), sizeof (addr.sun_path) - 1);
+
+    if (setsockopt (fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof (timeout)) != 0
+	|| setsockopt (fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof (timeout)) != 0
+	|| connect (fd, reinterpret_cast<sockaddr*> (&addr), sizeof (addr)) != 0) {
+	close (fd);
+	return -1;
+    }
+
+    return fd;
+}

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

@@ -35,4 +35,13 @@ bool propertyValue (DBusMessage* reply, DBusMessageIter& value);
 DBusConnection* privateBus (DBusBusType type);
 
 void closeBus (DBusConnection* bus);
+
+bool connectToService (
+    DBusConnection*& connection, const char* busName, std::string& owner, std::string& reason,
+    const std::string& notRunning
+);
+
+int listenOnSocket (const std::string& path, std::string& reason);
+
+int connectUnixSocket (const std::string& socketPath, long timeoutMicros);
 }

+ 392 - 3
src/WallpaperEngine/Desktop/SessionMonitor.cpp

@@ -5,6 +5,7 @@
 #include <chrono>
 #include <cstdint>
 #include <cstdlib>
+#include <cstring>
 #include <dlfcn.h>
 #include <memory>
 #include <optional>
@@ -12,12 +13,25 @@
 #include <string>
 #include <string_view>
 #include <sys/eventfd.h>
+#include <sys/socket.h>
 #include <tuple>
 #include <unistd.h>
 
+#include "WallpaperEngine/Desktop/HyprlandIPC.h"
 #include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Logging/ThreadGuard.h"
+#include "nlohmann/json.hpp"
+
+#if defined(ENABLE_WAYLAND) && defined(ENABLE_KDE_FEATURES)
+#define LWE_KWIN_DPMS 1
+#include <vector>
+#include <wayland-client.h>
+
+#include "WallpaperEngine/Desktop/HostWayland.h"
+#include "WallpaperEngine/Desktop/KDESession.h"
+#include "kwin-dpms-protocol.h"
+#endif
 
 using namespace WallpaperEngine::Desktop;
 
@@ -111,6 +125,313 @@ private:
     int (*m_info) (void*, unsigned short*, unsigned char*) = nullptr;
 };
 
+#ifdef LWE_KWIN_DPMS
+// KWin's org_kde_kwin_dpms: the compositor tells the state of each output, nothing is ever requested (the protocol
+// has a set request). Other compositors don't offer the manager and the connection is dropped again
+class KWinDpms {
+public:
+    explicit KWinDpms (wl_display* display) : m_display (display) { }
+
+    ~KWinDpms () {
+	this->m_outputs.clear ();
+
+	if (this->m_manager != nullptr) {
+	    org_kde_kwin_dpms_manager_destroy (this->m_manager);
+	}
+
+	if (this->m_registry != nullptr) {
+	    wl_registry_destroy (this->m_registry);
+	}
+
+	wl_display_disconnect (this->m_display);
+    }
+
+    KWinDpms (const KWinDpms&) = delete;
+    KWinDpms& operator= (const KWinDpms&) = delete;
+
+    bool open () {
+	this->m_registry = wl_display_get_registry (this->m_display);
+	wl_registry_add_listener (this->m_registry, &registryListener, this);
+
+	if (!this->roundtrip () || this->m_manager == nullptr) {
+	    return false;
+	}
+
+	for (const auto& output : this->m_outputs) {
+	    this->attach (*output);
+	}
+
+	return this->roundtrip ();
+    }
+
+    [[nodiscard]] int fd () const { return wl_display_get_fd (this->m_display); }
+    [[nodiscard]] bool failed () const { return wl_display_get_error (this->m_display) != 0; }
+
+    void beforePoll () {
+	while (wl_display_prepare_read (this->m_display) != 0) {
+	    wl_display_dispatch_pending (this->m_display);
+	}
+
+	wl_display_flush (this->m_display);
+    }
+
+    void afterPoll (const bool readable) {
+	if (readable) {
+	    wl_display_read_events (this->m_display);
+	} else {
+	    wl_display_cancel_read (this->m_display);
+	}
+
+	wl_display_dispatch_pending (this->m_display);
+    }
+
+    [[nodiscard]] bool allOff () const {
+	return !this->m_outputs.empty () && std::ranges::all_of (this->m_outputs, [] (const auto& output) {
+	    return output->mode != ORG_KDE_KWIN_DPMS_MODE_ON;
+	});
+    }
+
+private:
+    static constexpr int ROUNDTRIP_MS = 2000;
+
+    bool roundtrip () {
+	bool done = false;
+	wl_callback* callback = wl_display_sync (this->m_display);
+
+	wl_callback_add_listener (callback, &syncListener, &done);
+
+	const auto deadline = std::chrono::steady_clock::now () + std::chrono::milliseconds (ROUNDTRIP_MS);
+
+	while (!done && !this->failed ()) {
+	    const auto left
+		= std::chrono::duration_cast<std::chrono::milliseconds> (deadline - std::chrono::steady_clock::now ());
+
+	    if (left.count () <= 0) {
+		break;
+	    }
+
+	    this->beforePoll ();
+
+	    pollfd pending = { .fd = this->fd (), .events = POLLIN, .revents = 0 };
+	    const int ready = poll (&pending, 1, static_cast<int> (left.count ()));
+
+	    this->afterPoll (ready > 0);
+	}
+
+	if (!done) {
+	    wl_callback_destroy (callback);
+	}
+
+	return done;
+    }
+
+    static void syncDone (void* data, wl_callback*, uint32_t) { *static_cast<bool*> (data) = true; }
+
+    static constexpr wl_callback_listener syncListener = { .done = syncDone };
+
+    struct Output {
+	uint32_t name = 0;
+	wl_output* output = nullptr;
+	org_kde_kwin_dpms* dpms = nullptr;
+	uint32_t mode = ORG_KDE_KWIN_DPMS_MODE_ON;
+
+	~Output () {
+	    if (this->dpms != nullptr) {
+		org_kde_kwin_dpms_release (this->dpms);
+	    }
+
+	    if (this->output != nullptr) {
+		wl_output_destroy (this->output);
+	    }
+	}
+    };
+
+    void attach (Output& output) const {
+	if (output.dpms == nullptr && this->m_manager != nullptr) {
+	    output.dpms = org_kde_kwin_dpms_manager_get (this->m_manager, output.output);
+	    org_kde_kwin_dpms_add_listener (output.dpms, &dpmsListener, &output);
+	}
+    }
+
+    static void registryGlobal (void* data, wl_registry* registry, uint32_t name, const char* interface, uint32_t) {
+	auto* self = static_cast<KWinDpms*> (data);
+
+	if (std::strcmp (interface, org_kde_kwin_dpms_manager_interface.name) == 0) {
+	    self->m_manager = static_cast<org_kde_kwin_dpms_manager*> (
+		wl_registry_bind (registry, name, &org_kde_kwin_dpms_manager_interface, 1)
+	    );
+	} else if (std::strcmp (interface, wl_output_interface.name) == 0) {
+	    auto& output = self->m_outputs.emplace_back (std::make_unique<Output> ());
+	    output->name = name;
+	    output->output = static_cast<wl_output*> (wl_registry_bind (registry, name, &wl_output_interface, 1));
+	    self->attach (*output);
+	}
+    }
+
+    static void registryGlobalRemove (void* data, wl_registry*, uint32_t name) {
+	std::erase_if (static_cast<KWinDpms*> (data)->m_outputs, [name] (const auto& output) {
+	    return output->name == name;
+	});
+    }
+
+    static void dpmsSupported (void*, org_kde_kwin_dpms*, uint32_t) { }
+
+    static void dpmsMode (void* data, org_kde_kwin_dpms*, uint32_t mode) { static_cast<Output*> (data)->mode = mode; }
+
+    static void dpmsDone (void*, org_kde_kwin_dpms*) { }
+
+    static constexpr wl_registry_listener registryListener = {
+	.global = registryGlobal,
+	.global_remove = registryGlobalRemove,
+    };
+
+    static constexpr org_kde_kwin_dpms_listener dpmsListener = {
+	.supported = dpmsSupported,
+	.mode = dpmsMode,
+	.done = dpmsDone,
+    };
+
+    wl_display* m_display;
+    wl_registry* m_registry = nullptr;
+    org_kde_kwin_dpms_manager* m_manager = nullptr;
+    std::vector<std::unique_ptr<Output>> m_outputs;
+};
+#endif
+
+// sway and Hyprland blank an output without telling its clients (wlr-output-management still says enabled, and sway
+// keeps sending frame callbacks), but both list the power state of their outputs on the IPC socket. Only read, asked
+// once a second like an X server's DPMS
+class OutputPower {
+public:
+    static std::unique_ptr<OutputPower> detect () {
+	const char* runtime = std::getenv ("XDG_RUNTIME_DIR");
+
+	if (const char* sway = std::getenv ("SWAYSOCK"); sway != nullptr && *sway != '\0') {
+	    return std::unique_ptr<OutputPower> (new OutputPower (Kind::Sway, sway));
+	}
+
+	if (auto hypr = findHyprlandSocket (
+		runtime != nullptr ? runtime : "", std::getenv ("HYPRLAND_INSTANCE_SIGNATURE"),
+		std::getenv ("WAYLAND_DISPLAY"), std::getenv ("XDG_CURRENT_DESKTOP")
+	    );
+	    !hypr.empty ()) {
+	    return std::unique_ptr<OutputPower> (new OutputPower (Kind::Hyprland, hypr));
+	}
+
+	return nullptr;
+    }
+
+    std::optional<bool> blanked () const {
+	const auto reply
+	    = this->m_kind == Kind::Sway ? this->swayOutputs () : hyprlandRequest (this->m_path, "j/monitors");
+
+	if (!reply.has_value ()) {
+	    return std::nullopt;
+	}
+
+	const auto outputs = nlohmann::json::parse (*reply, nullptr, false);
+
+	if (!outputs.is_array ()) {
+	    return std::nullopt;
+	}
+
+	const char* key = this->m_kind == Kind::Sway ? "power" : "dpmsStatus";
+	bool any = false;
+
+	for (const auto& output : outputs) {
+	    if (!output.is_object ()) {
+		return std::nullopt;
+	    }
+
+	    if (this->m_kind == Kind::Sway) {
+		const auto active = output.find ("active");
+
+		if (active != output.end () && !active->is_boolean ()) {
+		    return std::nullopt;
+		}
+
+		if (active == output.end () || !active->get<bool> ()) {
+		    continue;
+		}
+	    }
+
+	    const auto state = output.find (key);
+
+	    if (state == output.end () || !state->is_boolean ()) {
+		return std::nullopt;
+	    }
+
+	    if (state->get<bool> ()) {
+		return false;
+	    }
+
+	    any = true;
+	}
+
+	return any;
+    }
+
+private:
+    enum class Kind { Sway, Hyprland };
+
+    OutputPower (const Kind kind, std::string path) : m_kind (kind), m_path (std::move (path)) { }
+
+    std::optional<std::string> swayOutputs () const {
+	const int fd = connectUnixSocket (this->m_path, 100000);
+
+	if (fd < 0) {
+	    return std::nullopt;
+	}
+
+	std::optional<std::string> result;
+
+	constexpr std::string_view MAGIC = "i3-ipc";
+	char request[MAGIC.size () + 8] = {};
+	const uint32_t type = 3;
+	std::copy (MAGIC.begin (), MAGIC.end (), request);
+	std::memcpy (request + MAGIC.size () + 4, &type, sizeof (type));
+
+	char header[sizeof (request)];
+
+	if (send (fd, request, sizeof (request), MSG_NOSIGNAL) == static_cast<ssize_t> (sizeof (request))
+	    && recvAll (fd, header, sizeof (header))) {
+	    uint32_t length = 0;
+	    std::memcpy (&length, header + MAGIC.size (), sizeof (length));
+
+	    // a monitor list is a few KB, anything near a megabyte is not one
+	    if (length < (1u << 20)) {
+		std::string payload (length, '\0');
+
+		if (recvAll (fd, payload.data (), length)) {
+		    result = std::move (payload);
+		}
+	    }
+	}
+
+	close (fd);
+	return result;
+    }
+
+    static bool recvAll (const int fd, char* data, const size_t size) {
+	size_t done = 0;
+
+	while (done < size) {
+	    const ssize_t got = recv (fd, data + done, size - done, 0);
+
+	    if (got <= 0) {
+		return false;
+	    }
+
+	    done += static_cast<size_t> (got);
+	}
+
+	return true;
+    }
+
+    Kind m_kind;
+    std::string m_path;
+};
+
 DBusMessage* methodCall (const char* service, const char* path, const char* interface, const char* method) {
     DBusMessage* call = dbus_message_new_method_call (service, path, interface, method);
 
@@ -260,7 +581,14 @@ struct SessionMonitor::Sources {
     bool hint = false;
     bool screenSaver = false;
     std::unique_ptr<X11Dpms> dpms;
+    std::unique_ptr<OutputPower> outputPower;
+    bool outputsOff = false;
+    std::chrono::steady_clock::time_point outputsChecked {};
     bool mutterOff = false;
+#ifdef LWE_KWIN_DPMS
+    wl_display* kwinDisplay = nullptr;
+    std::unique_ptr<KWinDpms> kwin;
+#endif
 };
 
 namespace {
@@ -289,6 +617,14 @@ DBusHandlerResult noteSignal (DBusConnection*, DBusMessage* message, void* data)
 
 SessionMonitor::SessionMonitor () :
     m_wakeFd (eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK)), m_sources (std::make_unique<Sources> ()) {
+#ifdef LWE_KWIN_DPMS
+    // main thread: connectWayland picks the route to the compositor once (Flatpak helper)
+    if (const char* type = std::getenv ("XDG_SESSION_TYPE"); type != nullptr && std::string_view (type) == "wayland"
+	&& std::getenv ("WAYLAND_DISPLAY") != nullptr && isKDESession ()) {
+	this->m_sources->kwinDisplay = connectWayland ();
+    }
+#endif
+
     try {
 	this->m_thread = std::thread ([this] {
 	    WallpaperEngine::Logging::guardThread ("Session monitor", [this] { this->run (); });
@@ -298,6 +634,12 @@ SessionMonitor::SessionMonitor () :
 	    close (this->m_wakeFd);
 	}
 
+#ifdef LWE_KWIN_DPMS
+	if (this->m_sources->kwinDisplay != nullptr) {
+	    wl_display_disconnect (this->m_sources->kwinDisplay);
+	}
+#endif
+
 	throw;
     }
 }
@@ -375,6 +717,22 @@ void SessionMonitor::run () {
 	}
     }
 
+    if (const char* type = std::getenv ("XDG_SESSION_TYPE"); type != nullptr && std::string_view (type) == "wayland") {
+	sources.outputPower = OutputPower::detect ();
+    }
+
+#ifdef LWE_KWIN_DPMS
+    if (sources.kwinDisplay != nullptr) {
+	sources.kwin = std::make_unique<KWinDpms> (sources.kwinDisplay);
+	sources.kwinDisplay = nullptr;
+
+	if (!sources.kwin->open ()) {
+	    sLog.debug ("Display: no org_kde_kwin_dpms, relying on frame callbacks");
+	    sources.kwin.reset ();
+	}
+    }
+#endif
+
     auto nextRecheck = std::chrono::steady_clock::now ();
 
     while (!this->m_stop) {
@@ -429,10 +787,11 @@ void SessionMonitor::run () {
 	    }
 	}
 
-	pollfd fds[3] = {
+	pollfd fds[4] = {
 	    { .fd = this->m_wakeFd, .events = POLLIN, .revents = 0 },
 	    { .fd = -1, .events = POLLIN, .revents = 0 },
 	    { .fd = -1, .events = POLLIN, .revents = 0 },
+	    { .fd = -1, .events = POLLIN, .revents = 0 },
 	};
 
 	// the blocking calls above read the socket and queue whatever else arrived, poll never sees that again
@@ -455,6 +814,30 @@ void SessionMonitor::run () {
 	    displayOff = displayOff || sources.dpms->blanked ().value_or (false);
 	}
 
+	if (sources.outputPower != nullptr) {
+	    const auto now = std::chrono::steady_clock::now ();
+
+	    if (now - sources.outputsChecked >= std::chrono::milliseconds (DPMS_POLL_MS)) {
+		sources.outputsOff = sources.outputPower->blanked ().value_or (false);
+		sources.outputsChecked = now;
+	    }
+
+	    displayOff = displayOff || sources.outputsOff;
+	}
+
+#ifdef LWE_KWIN_DPMS
+	if (sources.kwin != nullptr) {
+	    if (sources.kwin->failed ()) {
+		sLog.debug ("Display: lost the Wayland connection used for KWin's DPMS state");
+		sources.kwin.reset ();
+	    } else {
+		displayOff = displayOff || sources.kwin->allOff ();
+		sources.kwin->beforePoll ();
+		fds[3].fd = sources.kwin->fd ();
+	    }
+	}
+#endif
+
 	if (displayOff != this->m_displayOff) {
 	    this->m_displayOff = displayOff;
 	    sLog.out ("Display: ", displayOff ? "blanked (DPMS)" : "on again");
@@ -463,11 +846,17 @@ void SessionMonitor::run () {
 	auto untilRecheck
 	    = std::chrono::duration_cast<std::chrono::milliseconds> (nextRecheck - std::chrono::steady_clock::now ());
 
-	if (sources.dpms != nullptr) {
+	if (sources.dpms != nullptr || sources.outputPower != nullptr) {
 	    untilRecheck = std::min (untilRecheck, std::chrono::milliseconds (DPMS_POLL_MS));
 	}
 
-	poll (fds, 3, queued ? 0 : static_cast<int> (std::max<int64_t> (1, untilRecheck.count ())));
+	poll (fds, 4, queued ? 0 : static_cast<int> (std::max<int64_t> (1, untilRecheck.count ())));
+
+#ifdef LWE_KWIN_DPMS
+	if (sources.kwin != nullptr) {
+	    sources.kwin->afterPoll ((fds[3].revents & POLLIN) != 0);
+	}
+#endif
 
 	if (fds[0].revents & POLLIN) {
 	    uint64_t value;

+ 0 - 2
src/WallpaperEngine/FileSystem/Adapters/Directory.cpp

@@ -6,8 +6,6 @@
 
 #include "Directory.h"
 
-#include "WallpaperEngine/Assets/AssetLoadException.h"
-
 using namespace WallpaperEngine::FileSystem;
 using namespace WallpaperEngine::FileSystem::Adapters;
 

+ 0 - 1
src/WallpaperEngine/FileSystem/Adapters/MediaCover.cpp

@@ -4,7 +4,6 @@
 
 #include "MediaCover.h"
 
-#include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Media/MediaSource.h"
 

+ 67 - 7
src/WallpaperEngine/FileSystem/Adapters/Package.cpp

@@ -3,13 +3,16 @@
 
 #include "Package.h"
 
-#include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Data/Parsers/PackageParser.h"
 #include "WallpaperEngine/Data/Utils/BinaryReader.h"
 #include "WallpaperEngine/Data/Utils/MemoryStream.h"
 
 #include <algorithm>
 #include <cctype>
+#include <cerrno>
+
+#include <fcntl.h>
+#include <unistd.h>
 
 using namespace WallpaperEngine::FileSystem;
 using namespace WallpaperEngine::FileSystem::Adapters;
@@ -34,6 +37,12 @@ template <typename Files> static auto findFile (const Files& files, const std::f
     });
 }
 
+PackageAdapter::~PackageAdapter () {
+    if (this->fd >= 0) {
+	close (this->fd);
+    }
+}
+
 ReadStreamSharedPtr PackageAdapter::open (const std::filesystem::path& path) const {
     const auto it = findFile (this->package->files, path);
 
@@ -43,9 +52,6 @@ ReadStreamSharedPtr PackageAdapter::open (const std::filesystem::path& path) con
 
     const uint64_t start = static_cast<uint64_t> (it->get ()->offset) + this->package->baseOffset;
 
-    // the stream is shared by every file of the package, nothing an earlier read left behind may carry over
-    this->package->file->base ().clear ();
-
     // an entry that runs past the end (corrupt or truncated package) must not allocate its claimed size
     if (start + it->get ()->length > this->package->file->size ()) {
 	throw std::filesystem::filesystem_error (
@@ -56,6 +62,33 @@ ReadStreamSharedPtr PackageAdapter::open (const std::filesystem::path& path) con
 
     auto buffer = std::make_unique<char[]> (it->get ()->length);
 
+    if (this->fd >= 0) {
+	uint64_t done = 0;
+
+	while (done < it->get ()->length) {
+	    const ssize_t got
+		= pread (this->fd, buffer.get () + done, it->get ()->length - done, static_cast<off_t> (start + done));
+
+	    if (got < 0 && errno == EINTR) {
+		continue;
+	    }
+
+	    if (got <= 0) {
+		throw std::filesystem::filesystem_error (
+		    "Cannot read the package entry", path, std::make_error_code (std::errc::io_error)
+		);
+	    }
+
+	    done += static_cast<uint64_t> (got);
+	}
+
+	return std::make_shared<MemoryStream> (std::move (buffer), it->get ()->length);
+    }
+
+    const Debugging::LockGuard lock (this->m_readMutex);
+
+    // the stream is shared by every file of the package, nothing an earlier read left behind may carry over
+    this->package->file->base ().clear ();
     this->package->file->base ().seekg (static_cast<std::streamoff> (start), std::ios::beg);
     this->package->file->next (buffer.get (), it->get ()->length);
 
@@ -117,8 +150,35 @@ bool PackageFactory::handlesMountpoint (const std::filesystem::path& path) const
 }
 
 AdapterSharedPtr PackageFactory::create (const std::filesystem::path& path) const {
-    const auto stream = std::make_shared<std::ifstream> (path, std::ios::binary);
-    auto package = Data::Parsers::PackageParser::parse (stream);
+    // the table and the entries have to come from one file, so the package is parsed through the descriptor too
+    int fd = ::open (path.c_str (), O_RDONLY | O_CLOEXEC);
+    const std::filesystem::path source
+	= fd >= 0 ? std::filesystem::path ("/proc/self/fd/" + std::to_string (fd)) : path;
+    auto stream = std::make_shared<std::ifstream> (source, std::ios::binary);
+
+    // without /proc the entries are read from this one stream as well, a second open could be another file
+    if (!stream->is_open ()) {
+	if (fd >= 0) {
+	    close (fd);
+	    fd = -1;
+	}
+
+	stream = std::make_shared<std::ifstream> (path, std::ios::binary);
+    }
+
+    std::unique_ptr<PackageAdapter> adapter;
+
+    try {
+	adapter = std::make_unique<PackageAdapter> (Data::Parsers::PackageParser::parse (stream));
+    } catch (...) {
+	if (fd >= 0) {
+	    close (fd);
+	}
+
+	throw;
+    }
+
+    adapter->fd = fd;
 
-    return std::make_unique<PackageAdapter> (std::move (package));
+    return adapter;
 }

+ 8 - 0
src/WallpaperEngine/FileSystem/Adapters/Package.h

@@ -6,6 +6,7 @@
 #include "Types.h"
 #include "WallpaperEngine/Data/Assets/Package.h"
 #include "WallpaperEngine/Data/Assets/Types.h"
+#include "WallpaperEngine/Debugging/ThreadSafety.h"
 
 namespace WallpaperEngine::FileSystem::Adapters {
 using namespace WallpaperEngine::Data::Assets;
@@ -19,6 +20,9 @@ struct PackageFactory final : Factory {
 
 struct PackageAdapter final : Adapter {
     explicit PackageAdapter (PackageUniquePtr package) : package (std::move (package)) { };
+    ~PackageAdapter () override;
+    PackageAdapter (const PackageAdapter&) = delete;
+    PackageAdapter& operator= (const PackageAdapter&) = delete;
 
     [[nodiscard]] ReadStreamSharedPtr open (const std::filesystem::path& path) const override;
     [[nodiscard]] bool exists (const std::filesystem::path& path) const override;
@@ -28,5 +32,9 @@ struct PackageAdapter final : Adapter {
     [[nodiscard]] std::vector<std::string> listFiles (const std::filesystem::path& dir) const override;
 
     PackageUniquePtr package;
+    int fd = -1;
+
+private:
+    mutable Debugging::Mutex m_readMutex;
 };
 }

+ 0 - 2
src/WallpaperEngine/FileSystem/Adapters/Virtual.cpp

@@ -1,7 +1,5 @@
 #include "Virtual.h"
 
-#include "WallpaperEngine/Assets/AssetLoadException.h"
-
 #include <cstring>
 
 using namespace WallpaperEngine::FileSystem;

+ 1 - 3
src/WallpaperEngine/FileSystem/Container.cpp

@@ -1,4 +1,3 @@
-#include <map>
 #include <memory>
 
 #include "Container.h"
@@ -7,14 +6,13 @@
 #include "Adapters/Package.h"
 #include "Adapters/Types.h"
 #include "Adapters/Virtual.h"
-#include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 using namespace WallpaperEngine::FileSystem;
 using namespace WallpaperEngine::FileSystem::Adapters;
 
 // strips relative components so adapters can trust the path, not a security measure
-std::filesystem::path normalize_path (const std::filesystem::path& input_path) {
+static std::filesystem::path normalize_path (const std::filesystem::path& input_path) {
     return input_path.lexically_normal ();
 }
 

+ 0 - 1
src/WallpaperEngine/Input/Drivers/GLFWMouseInput.cpp

@@ -1,5 +1,4 @@
 #include "GLFWMouseInput.h"
-#include <glm/common.hpp>
 
 #include "WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.h"
 

+ 72 - 23
src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp

@@ -45,68 +45,83 @@ KDECursorInput::~KDECursorInput () {
 	m_reload.get ();
     }
 
+    if (m_reconnect.valid ()) {
+	if (DBusConnection* connection = m_reconnect.get (); connection != nullptr) {
+	    WallpaperEngine::Desktop::closeBus (connection);
+	}
+    }
+
     unloadKWinScript ();
     stopDBus ();
 }
 
-bool KDECursorInput::initializeDBus () {
+DBusConnection* KDECursorInput::connectBus () {
     DBusError error;
     dbus_error_init (&error);
 
-    m_connection = dbus_bus_get (DBUS_BUS_SESSION, &error);
+    // a private connection: the shared one stays the same disconnected object once the broker dropped it
+    DBusConnection* connection = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
     if (dbus_error_is_set (&error)) {
 	sLog.error ("Failed to connect to the session DBus: ", error.message);
 	dbus_error_free (&error);
-	return false;
+	return nullptr;
     }
 
-    if (m_connection == nullptr) {
+    if (connection == nullptr) {
 	sLog.error ("Failed to connect to the session DBus: unknown error");
-	return false;
+	return nullptr;
     }
 
-    dbus_connection_set_exit_on_disconnect (m_connection, false);
+    dbus_connection_set_exit_on_disconnect (connection, false);
 
     dbus_error_init (&error);
     const std::string serviceName = std::string (kServiceName) + "_" + WallpaperEngine::Desktop::processTag ();
     const auto requestResult
-	= dbus_bus_request_name (m_connection, serviceName.c_str (), DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
+	= dbus_bus_request_name (connection, serviceName.c_str (), DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
 
     if (dbus_error_is_set (&error)) {
 	sLog.error ("Failed to request DBus service ", serviceName, ": ", error.message);
 	dbus_error_free (&error);
-	dbus_connection_unref (m_connection);
-	m_connection = nullptr;
-	return false;
+	WallpaperEngine::Desktop::closeBus (connection);
+	return nullptr;
     }
 
     if (requestResult != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER
 	&& requestResult != DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER) {
 	sLog.error ("DBus service ", serviceName, " is already owned by another process");
-	dbus_connection_unref (m_connection);
-	m_connection = nullptr;
-	return false;
+	WallpaperEngine::Desktop::closeBus (connection);
+	return nullptr;
     }
 
+    return connection;
+}
+
+bool KDECursorInput::attachBus (DBusConnection* connection) {
     static constexpr DBusObjectPathVTable objectVTable = {
 	.unregister_function = nullptr,
 	.message_function = &KDECursorInput::handleMessage,
     };
 
-    if (!dbus_connection_register_object_path (m_connection, kObjectPath, &objectVTable, this)) {
+    if (connection == nullptr) {
+	return false;
+    }
+
+    if (!dbus_connection_register_object_path (connection, kObjectPath, &objectVTable, this)) {
 	sLog.error ("Failed to register DBus object path for KDE cursor input");
-	dbus_connection_unref (m_connection);
-	m_connection = nullptr;
+	WallpaperEngine::Desktop::closeBus (connection);
 	return false;
     }
 
+    m_connection = connection;
     return true;
 }
 
+bool KDECursorInput::initializeDBus () { return attachBus (connectBus ()); }
+
 void KDECursorInput::stopDBus () {
     if (m_connection != nullptr) {
 	dbus_connection_unregister_object_path (m_connection, kObjectPath);
-	dbus_connection_unref (m_connection);
+	WallpaperEngine::Desktop::closeBus (m_connection);
 	m_connection = nullptr;
     }
 }
@@ -267,13 +282,39 @@ bool KDECursorInput::handleMethodCall (DBusMessage* message) {
 
 std::optional<glm::dvec2> KDECursorInput::position () {
     // KWin sends a call per cursor move, many per frame
+    if (m_connection == nullptr && m_lost) {
+	if (m_reconnect.valid ()) {
+	    if (m_reconnect.wait_for (std::chrono::seconds (0)) == std::future_status::ready) {
+		if (attachBus (m_reconnect.get ())) {
+		    sLog.out ("KDE cursor input: DBus connection is back");
+		    m_lost = false;
+		    m_nextReload = {};
+		} else {
+		    m_nextReconnect = std::chrono::steady_clock::now () + RELOAD_RETRY;
+		}
+	    }
+	} else if (std::chrono::steady_clock::now () >= m_nextReconnect) {
+	    // a broker that is slow to answer must not hold the frame loop
+	    m_reconnect = std::async (std::launch::async, [] {
+		DBusConnection* connection = nullptr;
+
+		WallpaperEngine::Logging::guardThread ("KDE cursor reconnect", [&] { connection = connectBus (); });
+
+		return connection;
+	    });
+	}
+    }
+
     if (m_connection != nullptr) {
 	if (!WallpaperEngine::Desktop::drainBus (m_connection)) {
-	    sLog.error ("KDE cursor input: DBus connection dropped unexpectedly");
+	    sLog.error (
+		"KDE cursor input: DBus connection dropped unexpectedly, trying to reconnect every ",
+		RELOAD_RETRY.count (), "s"
+	    );
 	    m_script.reset ();
-	    dbus_connection_unregister_object_path (m_connection, kObjectPath);
-	    dbus_connection_unref (m_connection);
-	    m_connection = nullptr;
+	    stopDBus ();
+	    m_lost = true;
+	    m_nextReconnect = std::chrono::steady_clock::now () + RELOAD_RETRY;
 	} else {
 	    pollReload ();
 
@@ -294,10 +335,18 @@ std::optional<glm::dvec2> KDECursorInput::position () {
 
 // the constructor drops the connection when the first load fails, so a missing script later is a reload in progress
 // and the input region must not flip to capturing every click meanwhile
-bool KDECursorInput::isInitialized () const { return m_connection != nullptr; }
+bool KDECursorInput::isInitialized () const { return m_connection != nullptr || m_lost; }
 
 void KDECursorInput::setSuspended (bool suspended) {
-    if (m_connection == nullptr || m_suspended == suspended) {
+    if (m_connection == nullptr) {
+	if (m_lost) {
+	    m_suspended = suspended;
+	}
+
+	return;
+    }
+
+    if (m_suspended == suspended) {
 	return;
     }
 

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

@@ -34,6 +34,8 @@ public:
 private:
     struct ScriptHandle;
 
+    static DBusConnection* connectBus ();
+    bool attachBus (DBusConnection* connection);
     bool initializeDBus ();
     void stopDBus ();
 
@@ -49,6 +51,9 @@ private:
     DBusConnection* m_connection = nullptr;
     std::optional<glm::dvec2> m_pos;
     bool m_suspended = false;
+    bool m_lost = false;
+    std::chrono::steady_clock::time_point m_nextReconnect {};
+    std::future<DBusConnection*> m_reconnect;
     unsigned m_reloadCount = 0;
 
     std::unique_ptr<ScriptHandle> m_script;

+ 0 - 1
src/WallpaperEngine/Led/LedLayout.cpp

@@ -1,7 +1,6 @@
 #include "LedLayout.h"
 
 #include <algorithm>
-#include <cmath>
 
 namespace WallpaperEngine::Led {
 std::vector<LedPixel> layoutDevice (const OpenRgb::Device& device) {

+ 7 - 7
src/WallpaperEngine/Led/LedOutput.cpp

@@ -3,9 +3,7 @@
 #include <algorithm>
 #include <chrono>
 
-#include <arpa/inet.h>
 #include <cerrno>
-#include <cstring>
 #include <netdb.h>
 #include <netinet/tcp.h>
 #include <poll.h>
@@ -188,7 +186,7 @@ void LedOutput::submit (const std::span<const uint8_t> rgb) {
     }
 
     {
-	const std::lock_guard lock (this->m_mutex);
+	const Debugging::LockGuard lock (this->m_mutex);
 	this->m_frame.assign (rgb.begin (), rgb.end ());
 	this->m_fresh = true;
     }
@@ -210,8 +208,8 @@ void LedOutput::run () {
 	    reported = true;
 	}
 
-	std::unique_lock lock (this->m_mutex);
-	this->m_wake.wait_for (lock, 3s, [this] { return !this->m_running.load (); });
+	Debugging::UniqueLock lock (this->m_mutex);
+	this->m_wake.wait_for (lock, 3s, [this] () LWE_REQUIRES (this->m_mutex) { return !this->m_running.load (); });
     }
 }
 
@@ -334,9 +332,11 @@ bool LedOutput::connectAndServe (const Options& options) {
 
     while (this->m_running.load ()) {
 	{
-	    std::unique_lock lock (this->m_mutex);
+	    Debugging::UniqueLock lock (this->m_mutex);
 
-	    this->m_wake.wait_for (lock, 250ms, [this] { return this->m_fresh || !this->m_running.load (); });
+	    this->m_wake.wait_for (lock, 250ms, [this] () LWE_REQUIRES (this->m_mutex) {
+		return this->m_fresh || !this->m_running.load ();
+	    });
 
 	    if (this->m_fresh) {
 		frame = this->m_frame;

+ 5 - 4
src/WallpaperEngine/Led/LedOutput.h

@@ -10,6 +10,7 @@
 #include <vector>
 
 #include "LedLayout.h"
+#include "WallpaperEngine/Debugging/ThreadSafety.h"
 
 namespace WallpaperEngine::Led {
 class LedOutput {
@@ -45,10 +46,10 @@ private:
     std::thread m_thread;
     std::atomic<bool> m_running = false;
     std::atomic<size_t> m_devices = 0;
-    std::mutex m_mutex;
-    std::condition_variable m_wake;
-    std::vector<uint8_t> m_frame;
-    bool m_fresh = false;
+    Debugging::Mutex m_mutex;
+    std::condition_variable_any m_wake;
+    std::vector<uint8_t> m_frame LWE_GUARDED_BY (m_mutex);
+    bool m_fresh LWE_GUARDED_BY (m_mutex) = false;
     bool m_protocolReported = false;
 };
 }

+ 2 - 2
src/WallpaperEngine/Logging/Log.cpp

@@ -17,12 +17,12 @@ Log& Log::get () {
 }
 
 void Log::addOutput (std::ostream* stream) {
-    const std::lock_guard lock (this->mMutex);
+    const Debugging::LockGuard lock (this->mMutex);
     this->mOutputs.push_back (stream);
 }
 
 void Log::addError (std::ostream* stream) {
-    const std::lock_guard lock (this->mMutex);
+    const Debugging::LockGuard lock (this->mMutex);
     this->mErrors.push_back (stream);
 }
 

+ 9 - 8
src/WallpaperEngine/Logging/Log.h

@@ -1,5 +1,6 @@
 #pragma once
 
+#include "WallpaperEngine/Debugging/ThreadSafety.h"
 #include <iostream>
 #include <memory>
 #include <mutex>
@@ -15,7 +16,7 @@ public:
 
     template <typename... Data> void out (const Data&... data) {
 	std::string str = this->buildBuffer (data...);
-	const std::lock_guard lock (this->mMutex);
+	const Debugging::LockGuard lock (this->mMutex);
 
 	for (const auto cur : this->mOutputs) {
 	    *cur << str << '\n' << std::flush;
@@ -25,7 +26,7 @@ public:
     template <typename... Data> void debug (const Data&... data) {
 #if (!NDEBUG) && (!ERRORONLY)
 	std::string str = this->buildBuffer (data...);
-	const std::lock_guard lock (this->mMutex);
+	const Debugging::LockGuard lock (this->mMutex);
 
 	for (const auto cur : this->mOutputs) {
 	    *cur << str << '\n';
@@ -36,7 +37,7 @@ public:
     template <typename... Data> void debugerror (const Data&... data) {
 #if (!NDEBUG) && (ERRORONLY)
 	std::string str = this->buildBuffer (data...);
-	const std::lock_guard lock (this->mMutex);
+	const Debugging::LockGuard lock (this->mMutex);
 
 	for (const auto cur : this->mOutputs) {
 	    *cur << str << '\n';
@@ -46,7 +47,7 @@ public:
 
     template <typename... Data> void error (const Data&... data) {
 	std::string str = this->buildBuffer (data...);
-	const std::lock_guard lock (this->mMutex);
+	const Debugging::LockGuard lock (this->mMutex);
 
 	for (const auto cur : this->mErrors) {
 	    *cur << str << '\n' << std::flush;
@@ -57,7 +58,7 @@ public:
 	std::string str = this->buildBuffer (data...);
 
 	{
-	    const std::lock_guard lock (this->mMutex);
+	    const Debugging::LockGuard lock (this->mMutex);
 
 	    for (const auto cur : this->mErrors) {
 		*cur << str << '\n';
@@ -85,9 +86,9 @@ private:
 	return buffer.str ();
     }
 
-    std::mutex mMutex;
-    std::vector<std::ostream*> mOutputs = {};
-    std::vector<std::ostream*> mErrors = {};
+    Debugging::Mutex mMutex;
+    std::vector<std::ostream*> mOutputs LWE_GUARDED_BY (mMutex) = {};
+    std::vector<std::ostream*> mErrors LWE_GUARDED_BY (mMutex) = {};
     static std::unique_ptr<Log> sInstance;
 };
 }

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

@@ -116,9 +116,9 @@ std::optional<std::filesystem::path> CoverDownloader::request (const std::string
     auto job = std::make_unique<Job> ();
     job->url = url;
     job->target = target;
-    job->thread = std::thread ([job = job.get ()] {
-	WallpaperEngine::Logging::guardThread ("Cover download", [job] { run (*job); });
-	job->finished = true;
+    job->thread = std::thread ([raw = job.get ()] {
+	WallpaperEngine::Logging::guardThread ("Cover download", [raw] { run (*raw); });
+	raw->finished = true;
     });
     this->m_jobs.push_back (std::move (job));
 

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

@@ -9,7 +9,7 @@
 
 using namespace WallpaperEngine::Media;
 
-DBusHandlerResult dbus_message_filter (DBusConnection* connection, DBusMessage* message, void* user_data) {
+static DBusHandlerResult dbus_message_filter (DBusConnection* connection, DBusMessage* message, void* user_data) {
     const auto mediaSource = static_cast<DBusMediaSource*> (user_data);
 
     if (!dbus_message_is_signal (message, "org.freedesktop.DBus.Properties", "PropertiesChanged")) {

+ 1 - 2
src/WallpaperEngine/Render/AlbumTexture.cpp

@@ -3,7 +3,6 @@
 #include "RenderContext.h"
 #include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Media/CoverImage.h"
-#include "WallpaperEngine/Media/MediaSource.h"
 
 #include <iterator>
 #include <span>
@@ -46,7 +45,7 @@ void AlbumTexture::decrementUsageCount () const { }
 void AlbumTexture::update () const { }
 
 void AlbumTexture::copyContents (const TextureProvider& other) const noexcept {
-    size_t bufferSize = other.getTextureWidth (0) * other.getTextureHeight (0) * 4;
+    size_t bufferSize = static_cast<size_t> (other.getTextureWidth (0)) * other.getTextureHeight (0) * 4;
 
     uint8_t* buffer = new uint8_t[bufferSize];
 

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

@@ -1,7 +1,5 @@
 #include "CObject.h"
 
-#include <utility>
-
 using namespace WallpaperEngine;
 using namespace WallpaperEngine::Render;
 using namespace WallpaperEngine::Render::Wallpapers;

+ 27 - 3
src/WallpaperEngine/Render/CTexture.cpp

@@ -6,7 +6,6 @@
 #include <atomic>
 #include <cstring>
 #include <exception>
-#include <lz4.h>
 #include <mutex>
 #include <ranges>
 #include <thread>
@@ -15,7 +14,6 @@
 #include "ImageDecoder.h"
 
 #define STB_IMAGE_IMPLEMENTATION
-#include "RenderContext.h"
 
 #include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include <stb_image.h>
@@ -89,6 +87,22 @@ CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
     this->releaseMipmapData ();
 }
 
+void CTexture::publishUpload () {
+    this->m_uploadFence = glFenceSync (GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
+    // the fence only exists for the other context once the commands before it are submitted
+    glFlush ();
+}
+
+void CTexture::acquireUpload () {
+    if (this->m_uploadFence == nullptr) {
+	return;
+    }
+
+    glWaitSync (this->m_uploadFence, 0, GL_TIMEOUT_IGNORED);
+    glDeleteSync (this->m_uploadFence);
+    this->m_uploadFence = nullptr;
+}
+
 void CTexture::releaseMipmapData () {
     // the GL texture holds the pixels now; repaints parse the file again and videos or GIFs never get here
     for (auto& mipmaps : this->m_header->images | std::views::values) {
@@ -112,7 +126,7 @@ void CTexture::uploadImages (const UploadFormat& upload) const {
     if (this->m_header->freeImageFormat != FIF_UNKNOWN) {
 	for (const auto& [index, mipmaps] : this->m_header->images) {
 	    for (const auto& mipmap : mipmaps) {
-		if (mipmap->composedPixels.empty ()) {
+		if (mipmap->composedPixels.empty () && mipmap->decodedPixels == nullptr) {
 		    decoded.push_back ({ .mipmap = mipmap.get (), .width = mipmap->width, .height = mipmap->height });
 		}
 	    }
@@ -208,6 +222,11 @@ void CTexture::uploadImages (const UploadFormat& upload) const {
 		if (!mipmap->composedPixels.empty ()) {
 		    dataptr = mipmap->composedPixels.data ();
 		    dataSize = mipmap->composedPixels.size ();
+		} else if (mipmap->decodedPixels != nullptr) {
+		    dataptr = mipmap->decodedPixels.get ();
+		    width = mipmap->decodedWidth;
+		    height = mipmap->decodedHeight;
+		    dataSize = static_cast<size_t> (width) * height * 4;
 		} else if (this->m_header->freeImageFormat != FIF_UNKNOWN) {
 		    dataptr = handle = nextDecoded->pixels;
 		    width = nextDecoded->width;
@@ -253,6 +272,7 @@ void CTexture::uploadImages (const UploadFormat& upload) const {
 		}
 
 		std::vector<unsigned char> ().swap (mipmap->composedPixels);
+		mipmap->decodedPixels.reset ();
 
 		level++;
 	    }
@@ -290,6 +310,10 @@ void CTexture::label (const std::string& name) const {
 }
 
 CTexture::~CTexture () {
+    if (this->m_uploadFence != nullptr) {
+	glDeleteSync (this->m_uploadFence);
+    }
+
     // release the player first so nothing else keeps using it via null references
     this->m_player.reset ();
 

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

@@ -45,6 +45,9 @@ public:
     void label (const std::string& name) const;
     bool repaint (TextureUniquePtr header);
 
+    void publishUpload ();
+    void acquireUpload ();
+
 private:
     struct UploadFormat {
 	GLint internalFormat;
@@ -64,6 +67,7 @@ private:
 
     TextureUniquePtr m_header;
     GLuint* m_textureID = nullptr;
+    GLsync m_uploadFence = nullptr;
     glm::vec4 m_resolution {};
     GLPlayerUniquePtr m_player;
     std::unique_ptr<GifAnimation> m_gif;

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

@@ -7,7 +7,6 @@
 
 #include "CWallpaper.h"
 #include "FrameMaterial.h"
-#include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Data/Parsers/TextureParser.h"
 #include "WallpaperEngine/Data/Utils/BinaryReader.h"
 #include "WallpaperEngine/Logging/Log.h"
@@ -653,7 +652,7 @@ void CWallpaper::present (const glm::ivec4& viewport, const glm::ivec2& globalPo
     if (this->getContext ().getApp ().getContext ().settings.render.debug.brightnessLog) {
 	static uint32_t brightnessFrameCounter = 0;
 	if ((brightnessFrameCounter++ % 30) == 0) {
-	    std::vector<unsigned char> px (viewport.z * viewport.w * 4);
+	    std::vector<unsigned char> px (static_cast<size_t> (viewport.z) * viewport.w * 4);
 	    glReadPixels (viewport.x, viewport.y, viewport.z, viewport.w, GL_RGBA, GL_UNSIGNED_BYTE, px.data ());
 	    uint64_t sum = 0;
 	    for (size_t i = 0; i < px.size (); i += 4) {

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

@@ -1,7 +1,6 @@
 #include <algorithm>
 #include <cmath>
 
-#include <glm/glm.hpp>
 #include <glm/gtc/matrix_transform.hpp>
 
 #include "Camera.h"

+ 1 - 1
src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp

@@ -459,7 +459,7 @@ bool WaylandFullScreenDetector::anythingFullscreen () const {
 
 void WaylandFullScreenDetector::reset () { }
 
-__attribute__ ((constructor)) void registerWaylandFullscreenDetector () {
+__attribute__ ((constructor)) static void registerWaylandFullscreenDetector () {
     sVideoFactories.registerFullscreenDetector (
 	"wayland", [] (ApplicationContext& context, VideoDriver& driver) -> std::unique_ptr<FullScreenDetector> {
 	    auto* wayland = dynamic_cast<WaylandOpenGLDriver*> (&driver);

+ 8 - 32
src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp

@@ -1,5 +1,6 @@
 #include "X11FullScreenDetector.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/Drivers/X11WindowType.h"
 
 #include <algorithm>
 #include <cstdlib>
@@ -17,7 +18,7 @@
 #include <GLFW/glfw3native.h>
 
 namespace WallpaperEngine::Render::Drivers::Detectors {
-void CustomXIOErrorExitHandler (Display* dsp, void* userdata) {
+static void CustomXIOErrorExitHandler (Display* dsp, void* userdata) {
     const auto context = static_cast<X11FullScreenDetector*> (userdata);
 
     sLog.debugerror ("Critical XServer error detected. Attempting to recover...");
@@ -25,13 +26,13 @@ void CustomXIOErrorExitHandler (Display* dsp, void* userdata) {
     context->reset ();
 }
 
-int CustomXErrorHandler (Display* dpy, XErrorEvent* event) {
+static int CustomXErrorHandler (Display* dpy, XErrorEvent* event) {
     sLog.debugerror ("Detected X error");
 
     return 0;
 }
 
-int CustomXIOErrorHandler (Display* dsp) {
+static int CustomXIOErrorHandler (Display* dsp) {
     sLog.debugerror ("Detected X error");
 
     return 0;
@@ -91,8 +92,8 @@ 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 || this->isDesktopWindow (client) || this->isHidden (client)
-	    || !this->onCurrentDesktop (client)) {
+	if (client == None || client == ourWindow || hasDesktopWindowType (this->m_display, client)
+	    || this->isHidden (client) || !this->onCurrentDesktop (client)) {
 	    continue;
 	}
 
@@ -155,7 +156,7 @@ bool X11FullScreenDetector::applicationFocused (Window ourWindow) const {
     }
 
     // sub_14003D050
-    if (active == None || active == ourWindow || this->isDesktopWindow (active)) {
+    if (active == None || active == ourWindow || hasDesktopWindowType (this->m_display, active)) {
 	return false;
     }
 
@@ -347,31 +348,6 @@ Window X11FullScreenDetector::clientOf (Window window) const {
     return client;
 }
 
-bool X11FullScreenDetector::isDesktopWindow (Window window) const {
-
-    const Atom typeAtom = XInternAtom (this->m_display, "_NET_WM_WINDOW_TYPE", False);
-    const Atom desktopAtom = XInternAtom (this->m_display, "_NET_WM_WINDOW_TYPE_DESKTOP", False);
-    Atom type;
-    int format;
-    unsigned long count, remaining;
-    unsigned char* data = nullptr;
-    bool desktop = false;
-
-    if (XGetWindowProperty (
-	    this->m_display, window, typeAtom, 0, 16, False, XA_ATOM, &type, &format, &count, &remaining, &data
-	) == Success
-	&& data != nullptr && format == 32) {
-	const auto* atoms = reinterpret_cast<const Atom*> (data);
-	desktop = std::find (atoms, atoms + count, desktopAtom) != atoms + count;
-    }
-
-    if (data != nullptr) {
-	XFree (data);
-    }
-
-    return desktop;
-}
-
 void X11FullScreenDetector::reset () {
     this->stop ();
     this->initialize ();
@@ -436,7 +412,7 @@ void X11FullScreenDetector::stop () {
     this->m_display = nullptr;
 }
 
-__attribute__ ((constructor)) void registerX11FullscreenDetector () {
+__attribute__ ((constructor)) static void registerX11FullscreenDetector () {
     sVideoFactories.registerFullscreenDetector (
 	"x11", [] (ApplicationContext& context, VideoDriver& driver) -> std::unique_ptr<FullScreenDetector> {
 	    return std::make_unique<X11FullScreenDetector> (context, driver);

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

@@ -24,7 +24,6 @@ namespace Detectors {
 
     private:
 	void initialize ();
-	[[nodiscard]] bool isDesktopWindow (Window window) const;
 	[[nodiscard]] Window clientOf (Window window) const;
 	[[nodiscard]] bool hasFullscreenState (Window client) const;
 	[[nodiscard]] bool hasMaximizedState (Window client) const;

+ 68 - 0
src/WallpaperEngine/Render/Drivers/EglSharedContext.h

@@ -0,0 +1,68 @@
+#pragma once
+
+#include "VideoDriver.h"
+
+#include <EGL/egl.h>
+#include <memory>
+#include <vector>
+
+namespace WallpaperEngine::Render::Drivers {
+class EglSharedContext final : public VideoDriver::SharedContext {
+public:
+    // the thread that creates it is the one that makes it current: eglBindAPI is per thread
+    static std::unique_ptr<EglSharedContext> create (
+	EGLDisplay display, EGLConfig config, EGLContext share, const std::vector<EGLint>& attributes, bool needsSurface
+    ) {
+	eglBindAPI (EGL_OPENGL_API);
+
+	auto context = std::unique_ptr<EglSharedContext> (new EglSharedContext (display));
+
+	context->m_context = eglCreateContext (display, config, share, attributes.data ());
+
+	if (context->m_context == EGL_NO_CONTEXT) {
+	    return nullptr;
+	}
+
+	if (needsSurface) {
+	    const EGLint size[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE };
+
+	    context->m_surface = eglCreatePbufferSurface (display, config, size);
+
+	    if (context->m_surface == EGL_NO_SURFACE) {
+		return nullptr;
+	    }
+	}
+
+	return context;
+    }
+
+    ~EglSharedContext () override {
+	this->release ();
+
+	if (this->m_context != EGL_NO_CONTEXT) {
+	    eglDestroyContext (this->m_display, this->m_context);
+	}
+
+	if (this->m_surface != EGL_NO_SURFACE) {
+	    eglDestroySurface (this->m_display, this->m_surface);
+	}
+    }
+
+    bool makeCurrent () override {
+	eglBindAPI (EGL_OPENGL_API);
+	return eglMakeCurrent (this->m_display, this->m_surface, this->m_surface, this->m_context) == EGL_TRUE;
+    }
+
+    void release () override {
+	eglMakeCurrent (this->m_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
+	eglReleaseThread ();
+    }
+
+private:
+    explicit EglSharedContext (EGLDisplay display) : m_display (display) { }
+
+    EGLDisplay m_display;
+    EGLContext m_context = EGL_NO_CONTEXT;
+    EGLSurface m_surface = EGL_NO_SURFACE;
+};
+}

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

@@ -9,7 +9,6 @@
 #endif
 
 #define GLFW_EXPOSE_NATIVE_X11
-#include "WallpaperEngine/Debugging/CallStack.h"
 
 #include <GLFW/glfw3native.h>
 
@@ -60,7 +59,9 @@ static bool wantsEglContext (const ApplicationContext& context) {
     });
 }
 
-void CustomGLFWErrorHandler (int errorCode, const char* reason) { sLog.error ("GLFW error ", errorCode, ": ", reason); }
+static void CustomGLFWErrorHandler (int errorCode, const char* reason) {
+    sLog.error ("GLFW error ", errorCode, ": ", reason);
+}
 
 GLFWOpenGLDriver::GLFWOpenGLDriver (const char* windowTitle, ApplicationContext& context, WallpaperApplication& app) :
     VideoDriver (app, m_mouseInput), m_mouseInput (*this) {
@@ -213,24 +214,7 @@ void GLFWOpenGLDriver::dispatchEventQueue () {
     if (this->m_output->haveImageBuffer ()) {
 	glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_targetFramebuffer);
 
-	// glReadnPixels requires GL 4.5; older drivers fall back to glReadPixels
-	if (GLEW_VERSION_4_5) {
-	    glReadnPixels (
-		0, 0, this->m_output->getFullWidth (), this->m_output->getFullHeight (), GL_BGRA, GL_UNSIGNED_BYTE,
-		this->m_output->getImageBufferSize (), this->m_output->getImageBuffer ()
-	    );
-	} else {
-	    glReadPixels (
-		0, 0, this->m_output->getFullWidth (), this->m_output->getFullHeight (), GL_BGRA, GL_UNSIGNED_BYTE,
-		this->m_output->getImageBuffer ()
-	    );
-	}
-
-	GLenum error = glGetError ();
-
-	if (error != GL_NO_ERROR) {
-	    sLog.exception ("OpenGL error when reading texture ", error);
-	}
+	this->m_output->readImageBuffer ();
     }
 
     glBindFramebuffer (GL_FRAMEBUFFER, 0);
@@ -260,7 +244,7 @@ void* GLFWOpenGLDriver::getX11Display () const {
 
 GLFWwindow* GLFWOpenGLDriver::getWindow () const { return this->m_window; }
 
-__attribute__ ((constructor)) void registerGLFWOpenGLDriver () {
+__attribute__ ((constructor)) static void registerGLFWOpenGLDriver () {
     sVideoFactories.registerDriver (
 	ApplicationContext::DESKTOP_BACKGROUND, "x11",
 	[] (ApplicationContext& context, WallpaperApplication& application) -> std::unique_ptr<VideoDriver> {

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

@@ -1,4 +1,5 @@
 #include "HeadlessOpenGLDriver.h"
+#include "EglSharedContext.h"
 #include "VideoFactories.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.h"
@@ -194,6 +195,14 @@ void HeadlessOpenGLDriver::createSurface () {
     this->m_surface = surface;
 }
 
+std::unique_ptr<VideoDriver::SharedContext> HeadlessOpenGLDriver::createSharedContext () const {
+    const std::vector<EGLint> attributes
+	= { EGL_CONTEXT_MAJOR_VERSION,           3,       EGL_CONTEXT_MINOR_VERSION, 3, EGL_CONTEXT_OPENGL_PROFILE_MASK,
+	    EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL_NONE };
+
+    return EglSharedContext::create (this->m_display, this->m_config, this->m_eglContext, attributes, true);
+}
+
 Output::Output& HeadlessOpenGLDriver::getOutput () { return *this->m_output; }
 
 float HeadlessOpenGLDriver::getRenderTime () const {
@@ -247,7 +256,7 @@ void* HeadlessOpenGLDriver::getProcAddress (const char* name) const {
     return reinterpret_cast<void*> (eglGetProcAddress (name));
 }
 
-__attribute__ ((constructor)) void registerHeadlessOpenGLDriver () {
+__attribute__ ((constructor)) static void registerHeadlessOpenGLDriver () {
     const auto create
 	= [] (ApplicationContext& context, WallpaperApplication& application) -> std::unique_ptr<VideoDriver> {
 	return std::make_unique<HeadlessOpenGLDriver> (context, application);

+ 1 - 0
src/WallpaperEngine/Render/Drivers/HeadlessOpenGLDriver.h

@@ -31,6 +31,7 @@ public:
     [[nodiscard]] uint32_t getFrameCounter () const override;
     void dispatchEventQueue () override;
     [[nodiscard]] void* getProcAddress (const char* name) const override;
+    [[nodiscard]] std::unique_ptr<SharedContext> createSharedContext () const override;
 
 private:
     class FixedMouse final : public Input::MouseInput {

+ 0 - 11
src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.cpp

@@ -2,17 +2,6 @@
 #include "GLFWOutputViewport.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "X11BackgroundWindow.h"
-#include <GL/glew.h>
-#include <GLFW/glfw3.h>
-
-#include <X11/Xatom.h>
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-#include <X11/extensions/shape.h>
-
-#include <algorithm>
-#include <cstdlib>
-#include <unistd.h>
 
 using namespace WallpaperEngine::Render::Drivers::Output;
 

+ 24 - 0
src/WallpaperEngine/Render/Drivers/Output/Output.cpp

@@ -1,5 +1,9 @@
 #include "Output.h"
 
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <GL/glew.h>
+
 using namespace WallpaperEngine::Render::Drivers::Output;
 
 Output::Output (ApplicationContext& context, VideoDriver& driver) : m_context (context), m_driver (driver) { }
@@ -9,3 +13,23 @@ const std::map<std::string, OutputViewport*>& Output::getViewports () const { re
 int Output::getFullWidth () const { return this->m_fullWidth; }
 
 int Output::getFullHeight () const { return this->m_fullHeight; }
+
+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 ()
+	);
+    } else {
+	glReadPixels (
+	    0, 0, this->getFullWidth (), this->getFullHeight (), GL_BGRA, GL_UNSIGNED_BYTE, this->getImageBuffer ()
+	);
+    }
+
+    GLenum error = glGetError ();
+
+    if (error != GL_NO_ERROR) {
+	sLog.exception ("OpenGL error when reading texture ", error);
+    }
+}

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

@@ -41,6 +41,8 @@ namespace Output {
 	virtual uint32_t getImageBufferSize () const = 0;
 	virtual void updateRender () const = 0;
 
+	void readImageBuffer () const;
+
     protected:
 	mutable int m_fullWidth = 0;
 	mutable int m_fullHeight = 0;

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

@@ -3,7 +3,6 @@
 
 #include <algorithm>
 #include <cctype>
-#include <csignal>
 #include <cstdlib>
 #include <cstring>
 #include <fstream>
@@ -15,7 +14,6 @@
 #include <sys/wait.h>
 #include <unistd.h>
 
-#include <X11/Xatom.h>
 #include <X11/Xutil.h>
 #include <X11/extensions/Xcomposite.h>
 #include <X11/extensions/Xdamage.h>
@@ -139,7 +137,7 @@ bool alive (pid_t pid) {
     std::string line;
 
     while (std::getline (status, line)) {
-	if (line.rfind ("State:", 0) == 0) {
+	if (line.starts_with ("State:")) {
 	    return line.find ('Z') == std::string::npos;
 	}
     }
@@ -468,7 +466,7 @@ private:
 	    while (std::getline (file, line)) {
 		if (!line.empty () && line[0] == '[') {
 		    desktop = line == "[Desktop]";
-		} else if (desktop && line.rfind (std::string (key) + "=", 0) == 0) {
+		} else if (desktop && line.starts_with (std::string (key) + "=")) {
 		    return line.substr (std::strlen (key) + 1);
 		}
 	    }

+ 5 - 28
src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp

@@ -1,6 +1,7 @@
 #include "X11Output.h"
 #include "GLFWOutputViewport.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/Drivers/X11WindowType.h"
 
 #include <algorithm>
 #include <cstdlib>
@@ -16,7 +17,7 @@
 
 using namespace WallpaperEngine::Render::Drivers::Output;
 
-void CustomXIOErrorExitHandler (Display* dsp, void* userdata) {
+static void CustomXIOErrorExitHandler (Display* dsp, void* userdata) {
     const auto context = static_cast<X11Output*> (userdata);
 
     sLog.debugerror ("Critical XServer error detected. Attempting to recover...");
@@ -25,13 +26,13 @@ void CustomXIOErrorExitHandler (Display* dsp, void* userdata) {
     context->requestReset ();
 }
 
-int CustomXErrorHandler (Display* dpy, XErrorEvent* event) {
+static int CustomXErrorHandler (Display* dpy, XErrorEvent* event) {
     sLog.debugerror ("Detected X error");
 
     return 0;
 }
 
-int CustomXIOErrorHandler (Display* dsp) {
+static int CustomXIOErrorHandler (Display* dsp) {
     sLog.debugerror ("Detected X error");
 
     return 0;
@@ -334,35 +335,11 @@ std::vector<Window> X11Output::stackingOrder () const {
     return windows;
 }
 
-bool X11Output::isDesktopType (Window window) const {
-    const Atom typeAtom = XInternAtom (this->m_display, "_NET_WM_WINDOW_TYPE", False);
-    const Atom desktopAtom = XInternAtom (this->m_display, "_NET_WM_WINDOW_TYPE_DESKTOP", False);
-    Atom type;
-    int format;
-    unsigned long count, remaining;
-    unsigned char* data = nullptr;
-    bool desktop = false;
-
-    if (XGetWindowProperty (
-	    this->m_display, window, typeAtom, 0, 16, False, XA_ATOM, &type, &format, &count, &remaining, &data
-	) == Success
-	&& data != nullptr && format == 32) {
-	const auto* atoms = reinterpret_cast<const Atom*> (data);
-	desktop = std::find (atoms, atoms + count, desktopAtom) != atoms + count;
-    }
-
-    if (data != nullptr) {
-	XFree (data);
-    }
-
-    return desktop;
-}
-
 std::vector<Window> X11Output::findCoveringDesktopWindows (const std::vector<Window>& stacking) const {
     std::vector<Window> found;
 
     for (const Window window : stacking) {
-	if (window == this->m_desktopWindow || !this->isDesktopType (window)) {
+	if (window == this->m_desktopWindow || !hasDesktopWindowType (this->m_display, window)) {
 	    continue;
 	}
 

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

@@ -49,7 +49,6 @@ private:
 #endif
     [[nodiscard]] std::vector<Window> findCoveringDesktopWindows (const std::vector<Window>& stacking) const;
     [[nodiscard]] std::vector<Window> stackingOrder () const;
-    [[nodiscard]] bool isDesktopType (Window window) const;
     [[nodiscard]] Window topLevelOf (Window window) const;
     void createDesktopWindow () const;
 

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

@@ -5,6 +5,7 @@
 #include "WallpaperEngine/Render/Drivers/Output/Output.h"
 #include <glm/vec2.hpp>
 #include <glm/vec4.hpp>
+#include <memory>
 #include <string>
 
 namespace WallpaperEngine::Application {
@@ -23,6 +24,13 @@ namespace Detectors {
 
 class VideoDriver {
 public:
+    class SharedContext {
+    public:
+	virtual ~SharedContext () = default;
+	virtual bool makeCurrent () = 0;
+	virtual void release () = 0;
+    };
+
     explicit VideoDriver (WallpaperApplication& app, Input::MouseInput& mouseInput);
     virtual ~VideoDriver () = default;
 
@@ -40,6 +48,7 @@ public:
     [[nodiscard]] virtual void* getX11Display () const { return nullptr; }
     // --hdr and a compositor that takes PQ: videos decode to linear BT.2020, HDR outputs get PQ
     [[nodiscard]] virtual bool isHDRAvailable () const { return false; }
+    [[nodiscard]] virtual std::unique_ptr<SharedContext> createSharedContext () const { return nullptr; }
     virtual void dispatchEventQueue () = 0;
     virtual void dispatchWhilePaused () { }
     [[nodiscard]] WallpaperApplication& getApp () const;

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

@@ -1,4 +1,5 @@
 #include "WaylandOpenGLDriver.h"
+#include "EglSharedContext.h"
 #include "VideoFactories.h"
 #include "WallpaperEngine/Application/WallpaperApplication.h"
 #include "WallpaperEngine/Desktop/HostWayland.h"
@@ -1004,6 +1005,22 @@ uint32_t WaylandOpenGLDriver::getFrameCounter () const { return m_frameCounter;
 
 WaylandOpenGLDriver::SEGLContext* WaylandOpenGLDriver::getEGLContext () { return &this->m_eglContext; }
 
+std::unique_ptr<VideoDriver::SharedContext> WaylandOpenGLDriver::createSharedContext () const {
+    const std::vector<EGLint> attributes = {
+	EGL_CONTEXT_MAJOR_VERSION_KHR,
+	3,
+	EGL_CONTEXT_MINOR_VERSION_KHR,
+	3,
+	EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR,
+	EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR,
+	EGL_NONE,
+    };
+
+    return EglSharedContext::create (
+	m_eglContext.display, m_eglContext.config, m_eglContext.context, attributes, false
+    );
+}
+
 void* WaylandOpenGLDriver::getProcAddress (const char* name) const {
     return reinterpret_cast<void*> (eglGetProcAddress (name));
 }
@@ -1034,7 +1051,7 @@ Output::WaylandOutputViewport* WaylandOpenGLDriver::surfaceToViewport (const wl_
     return nullptr;
 }
 
-__attribute__ ((constructor)) void registerWaylandOpenGL () {
+__attribute__ ((constructor)) static void registerWaylandOpenGL () {
     sVideoFactories.registerDriver (
 	ApplicationContext::DESKTOP_BACKGROUND, "wayland",
 	[] (ApplicationContext& context, WallpaperApplication& application) -> std::unique_ptr<VideoDriver> {

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

@@ -86,7 +86,7 @@ public:
     };
 
     explicit WaylandOpenGLDriver (ApplicationContext& context, WallpaperApplication& app);
-    ~WaylandOpenGLDriver ();
+    ~WaylandOpenGLDriver () override;
 
     [[nodiscard]] Output::Output& getOutput () override;
     float getRenderTime () const override;
@@ -102,6 +102,7 @@ public:
     /** frame callbacks don't draw while dispatchWhilePaused runs */
     [[nodiscard]] bool isDispatchingWhilePaused () const { return this->m_dispatchingWhilePaused; }
     [[nodiscard]] void* getProcAddress (const char* name) const override;
+    [[nodiscard]] std::unique_ptr<SharedContext> createSharedContext () const override;
     [[nodiscard]] void* getWaylandDisplay () const override;
     [[nodiscard]] bool isHDRAvailable () const override;
     /** PQ with BT.2020 primaries (and the PQ default luminances, 203 nits reference white), shared by every HDR surface

+ 31 - 0
src/WallpaperEngine/Render/Drivers/X11WindowType.h

@@ -0,0 +1,31 @@
+#pragma once
+
+#include <algorithm>
+
+#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);
+    Atom type;
+    int format;
+    unsigned long count, remaining;
+    unsigned char* data = nullptr;
+    bool desktop = false;
+
+    if (XGetWindowProperty (display, window, typeAtom, 0, 16, False, XA_ATOM, &type, &format, &count, &remaining, &data)
+	    == Success
+	&& data != nullptr && format == 32) {
+	const auto* atoms = reinterpret_cast<const Atom*> (data);
+	desktop = std::find (atoms, atoms + count, desktopAtom) != atoms + count;
+    }
+
+    if (data != nullptr) {
+	XFree (data);
+    }
+
+    return desktop;
+}
+}

+ 45 - 22
src/WallpaperEngine/Render/Fonts/SystemFonts.cpp

@@ -1,6 +1,7 @@
 #include "SystemFonts.h"
 
 #include <algorithm>
+#include <chrono>
 #include <cstdio>
 #include <cstdlib>
 #include <fstream>
@@ -153,10 +154,44 @@ std::string fcMatch (const std::string& pattern, const std::string& format) {
 	return {};
     }
 
+    // every call is a process, about 5 ms, and the answers only change when fonts are added to the user's folder
+    static std::mutex mutex;
+    static std::unordered_map<std::string, std::string> answers;
+    static std::filesystem::file_time_type stamp;
+    static std::chrono::steady_clock::time_point cleared;
+    constexpr auto ANSWER_LIFETIME = std::chrono::minutes (1);
+
+    std::error_code error;
+    const auto changed = std::filesystem::last_write_time (userFontDirectory (), error);
+    const std::string key = pattern + '\n' + format;
+
+    {
+	const std::scoped_lock lock (mutex);
+
+	const auto now = std::chrono::steady_clock::now ();
+
+	if (changed != stamp || now - cleared >= ANSWER_LIFETIME) {
+	    answers.clear ();
+	    stamp = changed;
+	    cleared = now;
+	}
+
+	if (const auto found = answers.find (key); found != answers.end ()) {
+	    return found->second;
+	}
+    }
+
     const std::string config = fontconfigFile ();
     const std::string prefix = config.empty () ? std::string () : "FONTCONFIG_FILE='" + config + "' ";
+    std::string answer = run (prefix + "fc-match -f '" + format + "' '" + pattern + "' 2>/dev/null");
 
-    return run (prefix + "fc-match -f '" + format + "' '" + pattern + "' 2>/dev/null");
+    const std::scoped_lock lock (mutex);
+
+    if (changed == stamp) {
+	answers.emplace (key, answer);
+    }
+
+    return answer;
 }
 
 std::vector<std::string> systemFontFamilies (const std::string& font) {
@@ -181,31 +216,19 @@ std::vector<std::string> systemFontFamilies (const std::string& font) {
 }
 
 std::string installedFamilyFile (const std::vector<std::string>& families) {
-    static std::unordered_map<std::string, std::string> cache;
-
     for (const auto& family : families) {
-	auto it = cache.find (family);
-
-	if (it == cache.end ()) {
-	    const std::string output = fcMatch (family, "%{family}\\n%{file}");
-	    std::string path;
-
-	    if (const size_t newline = output.find ('\n');
-		newline != std::string::npos && sameFamily (output.substr (0, newline), family)) {
-		path = output.substr (newline + 1);
-	    }
+	const std::string output = fcMatch (family, "%{family}\\n%{file}");
+	std::string path;
 
-	    std::error_code error;
-
-	    if (!path.empty () && !std::filesystem::exists (path, error)) {
-		path.clear ();
-	    }
-
-	    it = cache.emplace (family, path).first;
+	if (const size_t newline = output.find ('\n');
+	    newline != std::string::npos && sameFamily (output.substr (0, newline), family)) {
+	    path = output.substr (newline + 1);
 	}
 
-	if (!it->second.empty ()) {
-	    return it->second;
+	std::error_code error;
+
+	if (!path.empty () && std::filesystem::exists (path, error)) {
+	    return path;
 	}
     }
 

+ 63 - 100
src/WallpaperEngine/Render/Objects/CImage.cpp

@@ -1,6 +1,8 @@
 #include "CImage.h"
+#include "ParallaxClamp.h"
 #include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 #include "WallpaperEngine/Render/DepthRange.h"
 
 #include "CMesh.h"
@@ -11,19 +13,15 @@
 #include <array>
 #include <bit>
 #include <cmath>
-#include <cstdio>
 #include <cstdlib>
 #include <cstring>
 #include <iterator>
 #include <limits>
 #include <optional>
 #include <sstream>
-#include <strings.h>
 #include <tuple>
 #include <vector>
 
-#include <glm/glm.hpp>
-#include <glm/gtc/matrix_transform.hpp>
 #define GLM_ENABLE_EXPERIMENTAL
 #include <glm/gtx/rotate_vector.hpp>
 #undef GLM_ENABLE_EXPERIMENTAL
@@ -34,10 +32,7 @@
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Model/UserSetting.h"
 #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
-#include "WallpaperEngine/Data/Utils/BinaryReader.h"
-#include "WallpaperEngine/Data/Utils/MemoryStream.h"
 #include "WallpaperEngine/Logging/Log.h"
-#include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
 #include "WallpaperEngine/Scripting/ScriptEngine.h"
 
 using namespace WallpaperEngine;
@@ -51,6 +46,11 @@ extern float g_Time;
 extern float g_TimeLast;
 
 namespace {
+std::array<GLfloat, 18> sceneQuad (const glm::vec4& pos) {
+    return { pos.x, pos.y, 0.0f, pos.x, pos.w, 0.0f, pos.z, pos.y, 0.0f,
+	     pos.z, pos.y, 0.0f, pos.x, pos.w, 0.0f, pos.z, pos.w, 0.0f };
+}
+
 bool isMagentaNeonTint (const glm::vec3& color) { return color.r > 0.55f && color.g < 0.25f && color.b > 0.45f; }
 
 std::optional<glm::vec3> findMagentaCompositeTint (const Image& image, const std::vector<int>& skippedEffectIds) {
@@ -341,16 +341,7 @@ CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
 	);
     }
 
-    if ((size.x == 0.0f || size.y == 0.0f) && this->m_texture != nullptr) {
-	size.x = static_cast<float> (this->m_texture->getRealWidth ());
-	size.y = static_cast<float> (this->m_texture->getRealHeight ());
-    } else if (
-	(size.x == 0.0f || size.y == 0.0f) && this->getImage ().model->width.has_value ()
-	&& this->getImage ().model->height.has_value ()
-    ) {
-	size.x = static_cast<float> (this->getImage ().model->width.value ());
-	size.y = static_cast<float> (this->getImage ().model->height.value ());
-    }
+    this->fillMissingSize (size);
 
     // autosize takes the size of the loaded texture (a single frame for sprite sheets) over the
     // declared one, or the scene's for project layers. fullscreen still wins over it
@@ -410,28 +401,11 @@ CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
     this->m_currentSubFBO = this->m_subFBO = this->m_namedSubFBO = subFBO;
     this->m_layerBufferConfig = { .size = bufferSize, .format = layerFormat, .flags = compositeFlags };
 
-    GLfloat sceneSpacePosition[] = { this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f,
-				     this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f,
-				     this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f };
+    const auto sceneSpacePosition = sceneQuad (this->m_pos);
 
-    float width = 1.0f;
-    float height = 1.0f;
-
-    if (this->getTexture ()->isAnimated ()) {
-	width = static_cast<float> (this->getTexture ()->getRealWidth ())
-	    / static_cast<float> (this->getTexture ()->getTextureWidth (0));
-	height = static_cast<float> (this->getTexture ()->getRealHeight ())
-	    / static_cast<float> (this->getTexture ()->getTextureHeight (0));
-    } else if (
-	this->getTexture () != nullptr
-	&& (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth ()
-	    || this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())
-    ) {
-	width = static_cast<float> (this->getTexture ()->getRealWidth ())
-	    / static_cast<float> (this->getTexture ()->getTextureWidth (0));
-	height = static_cast<float> (this->getTexture ()->getRealHeight ())
-	    / static_cast<float> (this->getTexture ()->getTextureHeight (0));
-    }
+    const glm::vec2 uvScale = this->textureUvScale ();
+    float width = uvScale.x;
+    float height = uvScale.y;
 
     float x = 0.0f;
     float y = 0.0f;
@@ -480,7 +454,7 @@ CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
 
     glGenBuffers (1, &this->m_sceneSpacePosition);
     glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
-    glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition, GL_STATIC_DRAW);
+    glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition.data (), GL_STATIC_DRAW);
 
     glGenBuffers (1, &this->m_copySpacePosition);
     glBindBuffer (GL_ARRAY_BUFFER, this->m_copySpacePosition);
@@ -1027,15 +1001,7 @@ void CImage::updatePuppetPose () {
     this->m_rig.ropeEnvironment = this->getScene ().getRopeEnvironment ();
     this->m_rig.updatePose (this->puppetObjectWorld ());
     this->updatePuppetDrawOrder ();
-    for (const auto& payload : this->m_rig.takeFiredEvents ()) {
-	this->getScene ().getScriptEngine ().dispatchClipEvent (*this, payload);
-    }
-    this->m_rig.finishEndedLayers ([this] (size_t serial) {
-	this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
-    });
-    for (const auto& removed : this->m_rig.takeRemovedLayers ()) {
-	this->unregisterAnimationLayerProperties (removed.serial);
-    }
+    this->getScene ().getScriptEngine ().dispatchRigEvents (this->m_rig, *this);
 }
 
 void CImage::updatePuppetDrawOrder () {
@@ -2422,23 +2388,26 @@ void CImage::setup () {
 	return;
     }
 
-    this->m_readByOtherLayer = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
-	return object->id != this->getImage ().id
-	    && std::ranges::find (object->dependencies, this->getImage ().id) != object->dependencies.end ();
-    });
-    this->m_emitterImageSource
-	= std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
-	      return std::ranges::any_of (object->componentDependencies, [this] (const auto& record) {
-		  return record.type == "emitterimage" && record.id == this->getImage ().id;
+    {
+	LWE_ZONE ("image dependency scan");
+	this->m_readByOtherLayer
+	    = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
+		  return object->id != this->getImage ().id
+		      && std::ranges::find (object->dependencies, this->getImage ().id) != object->dependencies.end ();
+	      });
+	this->m_emitterImageSource
+	    = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
+		  return std::ranges::any_of (object->componentDependencies, [this] (const auto& record) {
+		      return record.type == "emitterimage" && record.id == this->getImage ().id;
+		  });
 	      });
-	  });
 
-    // setParent may add children later
-    this->m_hasPassthroughChildren = this->m_image.model->passthrough
-	&& (this->getScene ().scriptsMayReparent ()
-	    || std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
-		   return object->parent == this->getImage ().id;
-	       }));
+	this->m_hasPassthroughChildren = this->m_image.model->passthrough
+	    && (this->getScene ().scriptsMayReparent ()
+		|| std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
+		       return object->parent == this->getImage ().id;
+		   }));
+    }
 
     // passthrough without effects has nothing to draw unless another layer reads its _rt_imageLayerComposite or it
     // has children to draw into its buffer
@@ -2451,6 +2420,7 @@ void CImage::setup () {
 
     // a shape has no image of its own, only its effect is drawn (sub_14025FAF0)
     if (!this->getImage ().shape) {
+	LWE_ZONE ("image base passes");
 	for (const auto& cur : this->getImage ().model->material->passes) {
 	    this->m_passes.push_back (
 		new CPass (*this, std::make_shared<FBOProvider> (this), *cur, std::nullopt, std::nullopt, std::nullopt)
@@ -2462,6 +2432,7 @@ void CImage::setup () {
     std::vector<bool> passFromEffect (this->m_passes.size (), false);
 
     if (!debug.baseOnly && !this->getImage ().effects.empty ()) {
+	LWE_ZONE ("image effect passes");
 	for (const auto& cur : this->m_image.effects) {
 	    if (std::find (debug.skipEffects.begin (), debug.skipEffects.end (), static_cast<int> (cur->id))
 		!= debug.skipEffects.end ()) {
@@ -2514,6 +2485,7 @@ void CImage::setup () {
     }
 
     const size_t passCountBeforeTrailingPasses = this->m_passes.size ();
+    LWE_ZONE ("image passes finish");
 
     if (!debug.baseOnly && !this->getImage ().shape) {
 	const auto magentaCompositeTint = findMagentaCompositeTint (this->m_image, debug.skipEffects);
@@ -3230,9 +3202,7 @@ const glm::vec4& CImage::getColor4 () const {
 
 const glm::vec3& CImage::getCompositeColor () const { return this->m_image.color->value->getVec3 (); }
 
-glm::vec2 CImage::resolveGeometrySize () const {
-    glm::vec2 size = this->getSize ();
-
+void CImage::fillMissingSize (glm::vec2& size) const {
     if ((size.x == 0.0f || size.y == 0.0f) && this->m_texture != nullptr) {
 	size.x = static_cast<float> (this->m_texture->getRealWidth ());
 	size.y = static_cast<float> (this->m_texture->getRealHeight ());
@@ -3243,6 +3213,28 @@ glm::vec2 CImage::resolveGeometrySize () const {
 	size.x = static_cast<float> (this->getImage ().model->width.value ());
 	size.y = static_cast<float> (this->getImage ().model->height.value ());
     }
+}
+
+glm::vec2 CImage::textureUvScale () const {
+    const auto& texture = this->getTexture ();
+
+    if (texture == nullptr || texture->isAnimated ()) {
+	return { 1.0f, 1.0f };
+    }
+
+    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)) };
+}
+
+glm::vec2 CImage::resolveGeometrySize () const {
+    glm::vec2 size = this->getSize ();
+
+    this->fillMissingSize (size);
 
     if (this->getImage ().model->fullscreen) {
 	size = { static_cast<float> (this->getScene ().getCanvasWidth ()),
@@ -3269,20 +3261,11 @@ void CImage::updateScenePosition (const glm::vec2& size) {
 }
 
 void CImage::uploadGeometryBuffers (const glm::vec2& size) {
-    GLfloat sceneSpacePosition[] = { this->m_pos.x, this->m_pos.y, 0.0f, this->m_pos.x, this->m_pos.w, 0.0f,
-				     this->m_pos.z, this->m_pos.y, 0.0f, this->m_pos.z, this->m_pos.y, 0.0f,
-				     this->m_pos.x, this->m_pos.w, 0.0f, this->m_pos.z, this->m_pos.w, 0.0f };
+    const auto sceneSpacePosition = sceneQuad (this->m_pos);
 
-    float width = 1.0f;
-    float height = 1.0f;
-    if (this->getTexture () != nullptr && !this->getTexture ()->isAnimated ()
-	&& (this->getTexture ()->getTextureWidth (0) != this->getTexture ()->getRealWidth ()
-	    || this->getTexture ()->getTextureHeight (0) != this->getTexture ()->getRealHeight ())) {
-	width = static_cast<float> (this->getTexture ()->getRealWidth ())
-	    / static_cast<float> (this->getTexture ()->getTextureWidth (0));
-	height = static_cast<float> (this->getTexture ()->getRealHeight ())
-	    / static_cast<float> (this->getTexture ()->getTextureHeight (0));
-    }
+    const glm::vec2 uvScale = this->textureUvScale ();
+    float width = uvScale.x;
+    float height = uvScale.y;
 
     float x = 0.0f;
     float y = 0.0f;
@@ -3312,7 +3295,7 @@ void CImage::uploadGeometryBuffers (const glm::vec2& size) {
 				    realWidth, realHeight, 0.0f, realX, realY, 0.0f, realWidth, realY,      0.0f };
 
     glBindBuffer (GL_ARRAY_BUFFER, this->m_sceneSpacePosition);
-    glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition, GL_DYNAMIC_DRAW);
+    glBufferData (GL_ARRAY_BUFFER, sizeof (sceneSpacePosition), sceneSpacePosition.data (), GL_DYNAMIC_DRAW);
     glBindBuffer (GL_ARRAY_BUFFER, this->m_copySpacePosition);
     glBufferData (GL_ARRAY_BUFFER, sizeof (copySpacePosition), copySpacePosition, GL_DYNAMIC_DRAW);
     glBindBuffer (GL_ARRAY_BUFFER, this->m_texcoordCopy);
@@ -3399,26 +3382,6 @@ void CImage::updateGeometryBuffers () {
     }
 }
 
-namespace {
-// keeps an edge pair (m_pos.x/.z) from sliding into the visible canvas, so the image never uncovers ground it has no
-// pixels for; images too small to cover the axis move freely and cropped canvas may scroll in. WE has no clamp
-// (sub_14018AAC0)
-float clampParallaxAxis (float offset, float edgeA, float edgeB, float visibleLow, float visibleHigh) {
-    const float low = std::min (edgeA, edgeB);
-    const float high = std::max (edgeA, edgeB);
-    const float maxOffset = visibleLow - low;
-    const float minOffset = visibleHigh - high;
-
-    if (minOffset > maxOffset) {
-	return offset;
-    }
-
-    // a layer that doesn't cover the screen at rest stays where the scene puts it (3621923790's hair), the clamp
-    // only keeps the parallax from uncovering more
-    return std::clamp (offset, std::min (minOffset, 0.0f), std::max (maxOffset, 0.0f));
-}
-}
-
 void CImage::updateScreenSpacePosition () {
     this->updateGeometryBuffers ();
 

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

@@ -222,6 +222,8 @@ private:
     [[nodiscard]] bool hasLitMaterial () const;
     void updateGeometryBuffers ();
     [[nodiscard]] glm::vec2 resolveGeometrySize () const;
+    void fillMissingSize (glm::vec2& size) const;
+    [[nodiscard]] glm::vec2 textureUvScale () const;
     void updateScenePosition (const glm::vec2& size);
     void uploadGeometryBuffers (const glm::vec2& size);
     void uploadShapePointMesh (const glm::vec2& size);

+ 42 - 19
src/WallpaperEngine/Render/Objects/CMesh.cpp

@@ -1,4 +1,5 @@
 #include "CMesh.h"
+#include "WallpaperEngine/Debugging/Profiling.h"
 #include "WallpaperEngine/Render/DepthRange.h"
 
 #include <bit>
@@ -6,7 +7,6 @@
 
 #include <algorithm>
 #include <cstring>
-#include <glm/gtc/matrix_transform.hpp>
 #include <limits>
 
 #include "WallpaperEngine/Data/Model/Object.h"
@@ -15,7 +15,6 @@
 #include "WallpaperEngine/Render/Objects/CRenderable.h"
 #include "WallpaperEngine/Render/Objects/Effects/CPass.h"
 #include "WallpaperEngine/Render/Objects/PuppetMeshFile.h"
-#include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
 #include "WallpaperEngine/Scripting/ScriptEngine.h"
 
 using namespace WallpaperEngine::Render::Objects;
@@ -98,12 +97,6 @@ public:
 	return value;
     }
 
-    uint8_t u8 () {
-	const uint8_t value = this->has (1) ? static_cast<uint8_t> (this->m_data[this->m_offset]) : 0;
-	this->m_offset++;
-	return value;
-    }
-
     std::string string () {
 	std::string value;
 
@@ -753,6 +746,25 @@ CMesh::~CMesh () {
     }
 }
 
+struct WallpaperEngine::Render::Objects::ParsedModel {
+    std::vector<MdlMesh> meshes;
+    glm::vec3 boundsMin = glm::vec3 (0.0f);
+    glm::vec3 boundsMax = glm::vec3 (0.0f);
+    size_t end = 0;
+    uint32_t meshCount = 0;
+    std::vector<uint32_t> meshFlags;
+};
+
+std::shared_ptr<ParsedModel> CMesh::parseModel (const std::vector<char>& data) {
+    LWE_ZONE ("model meshes ahead");
+    auto parsed = std::make_shared<ParsedModel> ();
+
+    parsed->meshes
+	= readMdlMeshes (data, parsed->boundsMin, parsed->boundsMax, parsed->end, parsed->meshCount, parsed->meshFlags);
+
+    return parsed;
+}
+
 void CMesh::setup () {
     // sub_14021AD10: a number is a script's model data, which the layer keeps a reference to
     if (this->m_mesh.modelData.has_value ()) {
@@ -778,12 +790,25 @@ void CMesh::setup () {
     size_t end = 0;
     uint32_t meshCount = 0;
     std::vector<uint32_t> meshFlags;
-    auto meshes = readMdlMeshes (data, this->m_boundsMin, this->m_boundsMax, end, meshCount, meshFlags);
+    std::vector<MdlMesh> meshes;
+
+    if (const auto ahead = this->getScene ().takeParsedModel (this->m_mesh.model)) {
+	meshes = std::move (ahead->meshes);
+	this->m_boundsMin = ahead->boundsMin;
+	this->m_boundsMax = ahead->boundsMax;
+	end = ahead->end;
+	meshCount = ahead->meshCount;
+	meshFlags = std::move (ahead->meshFlags);
+    } else {
+	LWE_ZONE ("model meshes");
+	meshes = readMdlMeshes (data, this->m_boundsMin, this->m_boundsMax, end, meshCount, meshFlags);
+    }
     this->m_cullMin = this->m_boundsMin;
     this->m_cullMax = this->m_boundsMax;
 
     // v13+ have sections after the meshes, MDLS and clips load like a puppet's (sub_140261880)
     if (findMdlSection (data, end, "MDLS").has_value ()) {
+	LWE_ZONE ("model rig");
 	try {
 	    this->m_rig.load (data, end, meshCount, this->m_mesh.model);
 	    this->m_rig.addSceneLayers (this->m_mesh.animationLayers);
@@ -798,6 +823,7 @@ void CMesh::setup () {
     // morph texture (model +736)
     if (!this->m_rig.bones.empty ()) {
 	if (this->m_rig.getMorphSection () != 0) {
+	    LWE_ZONE ("model morph targets");
 	    loadMorphTargets (data, this->m_rig.getMorphSection (), meshFlags, meshes);
 	}
 
@@ -859,6 +885,7 @@ void CMesh::buildModelDataParts () {
 void CMesh::addPart (MdlMesh mesh, const ModelData::Mesh* source) {
     const auto& project = this->getScene ().getScene ().project;
     const std::string name = source != nullptr ? "script model data" : this->m_mesh.model;
+    LWE_ZONE_TEXT ("model part", mesh.material);
     auto material = MaterialParser::load (project, mesh.material);
 
     if (material == nullptr || material->passes.empty ()) {
@@ -881,10 +908,14 @@ void CMesh::addPart (MdlMesh mesh, const ModelData::Mesh* source) {
 	}
     }
 
-    auto part = std::make_unique<Part> (*this, *material, std::move (mesh), source);
+    auto part = [&] {
+	LWE_ZONE ("model part construct");
+	return std::make_unique<Part> (*this, *material, std::move (mesh), source);
+    }();
     this->m_materials.push_back (std::move (material));
 
     try {
+	LWE_ZONE ("model part setup");
 	part->setup ();
     } catch (const std::exception& e) {
 	sLog.error ("Cannot set up a mesh of ", name, ": ", e.what ());
@@ -907,15 +938,7 @@ void CMesh::updateAnimation () {
 
     this->m_rig.ropeEnvironment = this->getScene ().getRopeEnvironment ();
     this->m_rig.updatePose (this->getScene ().objectWorldMatrix (this->m_mesh), this);
-    for (const auto& payload : this->m_rig.takeFiredEvents ()) {
-	this->getScene ().getScriptEngine ().dispatchClipEvent (*this, payload);
-    }
-    this->m_rig.finishEndedLayers ([this] (size_t serial) {
-	this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
-    });
-    for (const auto& removed : this->m_rig.takeRemovedLayers ()) {
-	this->unregisterAnimationLayerProperties (removed.serial);
-    }
+    this->getScene ().getScriptEngine ().dispatchRigEvents (this->m_rig, *this);
     this->updateBones ();
 
     if (!this->m_rig.clipBounds (this->m_cullMin, this->m_cullMax)) {

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

@@ -13,6 +13,8 @@
 namespace WallpaperEngine::Render::Objects {
 using namespace WallpaperEngine::Data::Model;
 
+struct ParsedModel;
+
 class CMesh final : public Scripting::ScriptableObject, private PuppetRootMotionHost {
 public:
     CMesh (Wallpapers::CScene& scene, const Mesh& mesh);
@@ -63,6 +65,10 @@ public:
     class Part;
     struct MdlMesh;
 
+    /** What setup reads from a model file before it needs the skeleton, so a worker thread can do it ahead of time
+     * (CScene::storeParsedModel). Reads nothing but data */
+    [[nodiscard]] static std::shared_ptr<ParsedModel> parseModel (const std::vector<char>& data);
+
 private:
     [[nodiscard]] bool rootMotionEnabled () const override;
     [[nodiscard]] glm::mat4 rootMotionWorld () const override;

+ 86 - 143
src/WallpaperEngine/Render/Objects/CParticle.cpp

@@ -3,7 +3,6 @@
 #include "CMesh.h"
 #include "CText.h"
 
-#include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Maths.h"
 #include "WallpaperEngine/Render/Utils/NoiseUtils.h"
@@ -15,8 +14,6 @@
 #include <cstdlib>
 #include <cstring>
 #include <ctime>
-#include <glm/gtc/constants.hpp>
-#include <glm/gtc/matrix_transform.hpp>
 #include <limits>
 #include <numeric>
 
@@ -1189,16 +1186,47 @@ float CParticle::sampleAudio (
     return response >= 1.0f ? 1.0f : (response >= 0.0f ? response : 0.0f);
 }
 
-EmitterFunc CParticle::createBoxEmitter (const ParticleEmitter& emitter) {
-
-    int controlPointIndex = emitter.controlPoint;
-    if (controlPointIndex == -1 && !m_particle.controlPoints.empty ()) {
-	const auto& cp0 = m_particle.controlPoints[0];
-	if ((cp0.flags & 1) != 0) {
-	    controlPointIndex = 0;
-	}
+int CParticle::emitterControlPoint (const ParticleEmitter& emitter) const {
+    if (emitter.controlPoint == -1 && !m_particle.controlPoints.empty ()
+	&& (m_particle.controlPoints[0].flags & 1) != 0) {
+	return 0;
     }
 
+    return emitter.controlPoint;
+}
+
+const ControlPointData* CParticle::controlPointAt (int index) const {
+    return index >= 0 && index < static_cast<int> (m_controlPoints.size ()) ? &m_controlPoints[index] : nullptr;
+}
+
+void CParticle::startSpawn (ParticleInstance& p, const glm::vec3& color, float lifetime) {
+    p.acceleration = glm::vec3 (0.0f);
+    p.rotation = glm::vec3 (0.0f);
+    p.angularVelocity = glm::vec3 (0.0f);
+    p.angularAcceleration = glm::vec3 (0.0f);
+
+    p.color = color;
+    p.alpha = 1.0f * m_particle.instanceOverride.alpha->value->getFloat ();
+    // sub_14023B340: new slots start at size 0.5, lifetime 1; instanceoverride only scales the randoms
+    p.size = 0.5f;
+    p.lifetime = lifetime;
+    p.age = 0.0f;
+    p.alive = true;
+    p.frame = -1.0f;
+    p.seed = m_usesParticleSeed ? WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) : 0.0f;
+
+    p.initial.color = p.color;
+    p.initial.alpha = p.alpha;
+    p.initial.size = p.size;
+    p.initial.lifetime = p.lifetime;
+
+    // sub_14023B340 starts the step collisionquad looks at where the emitter put the particle
+    p.previousPosition = p.position;
+}
+
+EmitterFunc CParticle::createBoxEmitter (const ParticleEmitter& emitter) {
+    const int controlPointIndex = this->emitterControlPoint (emitter);
+
     const size_t clockIndex = m_emitters.size ();
 
     return [this, emitter, controlPointIndex,
@@ -1208,10 +1236,7 @@ EmitterFunc CParticle::createBoxEmitter (const ParticleEmitter& emitter) {
 	for (uint32_t i = 0; i < toEmit && count < particles.size (); i++) {
 	    auto& p = particles[count];
 
-	    const ControlPointData* cp
-		= controlPointIndex >= 0 && controlPointIndex < static_cast<int> (m_controlPoints.size ())
-		? &m_controlPoints[controlPointIndex]
-		: nullptr;
+	    const ControlPointData* cp = this->controlPointAt (controlPointIndex);
 
 	    // sub_1402378A0 box emitter: u = (2 rand - 1) * directions per axis, then
 	    // pos = sign (u) * (|u| * (distancemax - distancemin) + distancemin)
@@ -1228,28 +1253,7 @@ EmitterFunc CParticle::createBoxEmitter (const ParticleEmitter& emitter) {
 	    this->placeSpawn (p, cp, controlPointIndex, emitter.origin, randomPos);
 
 	    p.velocity = glm::vec3 (0.0f);
-	    p.acceleration = glm::vec3 (0.0f);
-	    p.rotation = glm::vec3 (0.0f);
-	    p.angularVelocity = glm::vec3 (0.0f);
-	    p.angularAcceleration = glm::vec3 (0.0f);
-
-	    p.color = m_colorOverride.tint;
-	    p.alpha = 1.0f * m_particle.instanceOverride.alpha->value->getFloat ();
-	    // sub_14023B340: new slots start at size 0.5, lifetime 1; instanceoverride only scales the randoms
-	    p.size = 0.5f;
-	    p.lifetime = 1.0f;
-	    p.age = 0.0f;
-	    p.alive = true;
-	    p.frame = -1.0f;
-	    p.seed = m_usesParticleSeed ? WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) : 0.0f;
-
-	    p.initial.color = p.color;
-	    p.initial.alpha = p.alpha;
-	    p.initial.size = p.size;
-	    p.initial.lifetime = p.lifetime;
-
-	    // sub_14023B340 starts the step collisionquad looks at where the emitter put the particle
-	    p.previousPosition = p.position;
+	    this->startSpawn (p, m_colorOverride.tint, 1.0f);
 
 	    for (auto& init : m_initializers) {
 		init (p);
@@ -1628,29 +1632,12 @@ EmitterFunc CParticle::createImageEmitter (const ParticleEmitter& emitter) {
 		    + emitter.speedMin;
 		p.velocity = (p.position - glm::vec3 (pixelPrevious * local)) / m_frameDelta * speed;
 	    }
-	    p.acceleration = glm::vec3 (0.0f);
-	    p.rotation = glm::vec3 (0.0f);
-	    p.angularVelocity = glm::vec3 (0.0f);
-	    p.angularAcceleration = glm::vec3 (0.0f);
-
 	    // flags 0x10000: the spawn colour takes the pixel's
-	    p.color = m_colorOverride.tint;
+	    glm::vec3 color = m_colorOverride.tint;
 	    if ((emitter.flags & 0x10000) != 0) {
-		p.color *= glm::vec3 (pixel.r, pixel.g, pixel.b) / 255.0f;
+		color *= glm::vec3 (pixel.r, pixel.g, pixel.b) / 255.0f;
 	    }
-	    p.alpha = 1.0f * m_particle.instanceOverride.alpha->value->getFloat ();
-	    p.size = 0.5f;
-	    p.lifetime = 1.0f;
-	    p.age = 0.0f;
-	    p.alive = true;
-	    p.frame = -1.0f;
-	    p.seed = m_usesParticleSeed ? WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) : 0.0f;
-
-	    p.initial.color = p.color;
-	    p.initial.alpha = p.alpha;
-	    p.initial.size = p.size;
-	    p.initial.lifetime = p.lifetime;
-	    p.previousPosition = p.position;
+	    this->startSpawn (p, color, 1.0f);
 	    m_emitOrientation = glm::mat3 (1.0f);
 
 	    for (auto& init : m_initializers) {
@@ -1671,15 +1658,7 @@ EmitterFunc CParticle::createSphereEmitter (const ParticleEmitter& emitter) {
     // sub_14023B340: lifetime 1 unless lifetimerandom sets it
     const float lifetime = 1.0f;
 
-    int controlPointIndex = emitter.controlPoint;
-
-    // control point 0 with linkMouse when none is given
-    if (controlPointIndex == -1 && !m_particle.controlPoints.empty ()) {
-	const auto& cp0 = m_particle.controlPoints[0];
-	if ((cp0.flags & 1) != 0) {
-	    controlPointIndex = 0;
-	}
-    }
+    const int controlPointIndex = this->emitterControlPoint (emitter);
 
     const size_t clockIndex = m_emitters.size ();
 
@@ -1690,10 +1669,7 @@ EmitterFunc CParticle::createSphereEmitter (const ParticleEmitter& emitter) {
 	for (uint32_t i = 0; i < toEmit && count < particles.size (); i++) {
 	    auto& p = particles[count];
 
-	    const ControlPointData* cp
-		= controlPointIndex >= 0 && controlPointIndex < static_cast<int> (m_controlPoints.size ())
-		? &m_controlPoints[controlPointIndex]
-		: nullptr;
+	    const ControlPointData* cp = this->controlPointAt (controlPointIndex);
 
 	    // sub_1402378A0 sphererandom: a point in the unit ball (cone around x) scaled by
 	    // directions, whose length also picks the distance between distancemin and distancemax
@@ -1710,11 +1686,11 @@ EmitterFunc CParticle::createSphereEmitter (const ParticleEmitter& emitter) {
 	    glm::vec3 randomPos = pointLength > 0.0f ? point / pointLength : glm::vec3 (0.0f);
 
 	    // a nonzero sign component forces that axis to its sign, zero leaves it alone
-	    for (int i = 0; i < 3; i++) {
-		if (emitter.sign[i] > 0.0f) {
-		    randomPos[i] = std::abs (randomPos[i]);
-		} else if (emitter.sign[i] < 0.0f) {
-		    randomPos[i] = -std::abs (randomPos[i]);
+	    for (int axis = 0; axis < 3; axis++) {
+		if (emitter.sign[axis] > 0.0f) {
+		    randomPos[axis] = std::abs (randomPos[axis]);
+		} else if (emitter.sign[axis] < 0.0f) {
+		    randomPos[axis] = -std::abs (randomPos[axis]);
 		}
 	    }
 	    randomPos *= distance;
@@ -1742,26 +1718,7 @@ EmitterFunc CParticle::createSphereEmitter (const ParticleEmitter& emitter) {
 		* speedScale;
 	    p.velocity = directionLength > 0.0f ? direction * (speed / directionLength) : glm::vec3 (0.0f);
 
-	    p.acceleration = glm::vec3 (0.0f);
-	    p.rotation = glm::vec3 (0.0f);
-	    p.angularVelocity = glm::vec3 (0.0f);
-	    p.angularAcceleration = glm::vec3 (0.0f);
-
-	    p.color = m_colorOverride.tint;
-	    p.alpha = 1.0f * m_particle.instanceOverride.alpha->value->getFloat ();
-	    p.size = 0.5f;
-	    p.lifetime = lifetime;
-	    p.age = 0.0f;
-	    p.alive = true;
-	    p.frame = -1.0f;
-	    p.seed = m_usesParticleSeed ? WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) : 0.0f;
-
-	    p.initial.color = p.color;
-	    p.initial.alpha = p.alpha;
-	    p.initial.size = p.size;
-	    p.initial.lifetime = p.lifetime;
-
-	    p.previousPosition = p.position;
+	    this->startSpawn (p, m_colorOverride.tint, lifetime);
 
 	    for (auto& init : m_initializers) {
 		init (p);
@@ -3000,6 +2957,31 @@ float remapApply (ParticleRemapOperation operation, float current, float value)
     }
 }
 
+template <typename Apply>
+glm::vec3 remapComponents (
+    ParticleRemapComponent component, const Apply& apply, glm::vec3 current, const glm::vec3& target, bool allFromX
+) {
+    switch (component) {
+	case ParticleRemapComponent::All:
+	    for (int c = 0; c < 3; c++) {
+		current[c] = apply (current[c], allFromX ? target.x : target[c]);
+	    }
+	    break;
+	case ParticleRemapComponent::X:
+	    current.x = apply (current.x, target.x);
+	    break;
+	case ParticleRemapComponent::Y:
+	    current.y = apply (current.y, target.y);
+	    break;
+	case ParticleRemapComponent::Z:
+	    current.z = apply (current.z, target.z);
+	    break;
+	default:
+	    break;
+    }
+    return current;
+}
+
 /** The transform functions of sub_14023FBC0 case 19, seed is the particle's random as integer bits */
 float remapTransformOperator (
     ParticleRemapTransform transform, float value, float scale, int octaves, float fbmAmplitude, int32_t seed
@@ -3364,7 +3346,7 @@ CParticle::createMapSequenceBetweenControlPointsInitializer (const MapSequenceBe
     return [this, start, end, flags, mirror, boundsMin, boundsRange, arcAmountValue, arcDirectionValue,
 	    sizeReductionValue, &counter] (ParticleInstance& p) {
 	float& sequence = counter.sequence;
-	float& step = counter.step;
+	float& stride = counter.step;
 	const glm::vec3 first = m_controlPoints[start].position;
 	const glm::vec3 line = m_controlPoints[end].position - first;
 	const float length = std::fmax (glm::length (line), 1.1754944e-38f);
@@ -3397,17 +3379,17 @@ CParticle::createMapSequenceBetweenControlPointsInitializer (const MapSequenceBe
 	    p.initial.size = p.size;
 	}
 
-	sequence += step;
+	sequence += stride;
 	if (sequence > 1.0f) {
 	    if (mirror) {
-		step = -step;
+		stride = -stride;
 		sequence = 1.0f - (sequence - 1.0f);
 	    } else {
 		sequence = 0.0f;
 	    }
 	} else if (sequence < 0.0f) {
 	    sequence = -sequence;
-	    step = -step;
+	    stride = -stride;
 	}
     };
 }
@@ -3520,26 +3502,8 @@ InitializerFunc CParticle::createRemapInitialValueInitializer (const RemapInitia
 	const auto apply
 	    = [&remap] (float current, float target) { return remapApply (remap.operation, current, target); };
 	// all three components, or the one outputcomponent names
-	const auto applyVector = [&remap, &apply] (glm::vec3 current, const glm::vec3& target) {
-	    switch (remap.outputComponent) {
-		case ParticleRemapComponent::All:
-		    for (int i = 0; i < 3; i++) {
-			current[i] = apply (current[i], target[i]);
-		    }
-		    break;
-		case ParticleRemapComponent::X:
-		    current.x = apply (current.x, target.x);
-		    break;
-		case ParticleRemapComponent::Y:
-		    current.y = apply (current.y, target.y);
-		    break;
-		case ParticleRemapComponent::Z:
-		    current.z = apply (current.z, target.z);
-		    break;
-		default:
-		    break;
-	    }
-	    return current;
+	const auto applyVector = [&remap, &apply] (const glm::vec3& current, const glm::vec3& target) {
+	    return remapComponents (remap.outputComponent, apply, current, target, false);
 	};
 
 	switch (remap.output) {
@@ -3767,30 +3731,9 @@ OperatorFunc CParticle::createRemapValueOperator (const RemapValueOperator& op)
 	    };
 	    // blended "remap" on all components gives every component the x value, like wallpaper64.exe's variant 39
 	    const auto applyVector
-		= [&remap, &blend, &apply] (glm::vec3 current, const glm::vec3& target, bool setQuirk) {
-		      switch (remap.outputComponent) {
-			  case ParticleRemapComponent::All:
-			      {
-				  const bool useX
-				      = setQuirk && blend.active && remap.operation == ParticleRemapOperation::Remap;
-				  for (int c = 0; c < 3; c++) {
-				      current[c] = apply (current[c], useX ? target.x : target[c]);
-				  }
-				  break;
-			      }
-			  case ParticleRemapComponent::X:
-			      current.x = apply (current.x, target.x);
-			      break;
-			  case ParticleRemapComponent::Y:
-			      current.y = apply (current.y, target.y);
-			      break;
-			  case ParticleRemapComponent::Z:
-			      current.z = apply (current.z, target.z);
-			      break;
-			  default:
-			      break;
-		      }
-		      return current;
+		= [&remap, &blend, &apply] (const glm::vec3& current, const glm::vec3& target, bool setQuirk) {
+		      const bool useX = setQuirk && blend.active && remap.operation == ParticleRemapOperation::Remap;
+		      return remapComponents (remap.outputComponent, apply, current, target, useX);
 		  };
 
 	    switch (remap.output) {

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

@@ -118,7 +118,7 @@ class CParticle final : public CRenderable, public Scripting::ScriptableObject {
 
 public:
     CParticle (Wallpapers::CScene& scene, const Particle& particle);
-    ~CParticle ();
+    ~CParticle () override;
 
     void setup () override;
     void render () override;
@@ -157,6 +157,9 @@ protected:
     EmitterFunc createBoxEmitter (const ParticleEmitter& emitter);
     EmitterFunc createSphereEmitter (const ParticleEmitter& emitter);
     uint32_t emitCount (EmitterClock& clock, const ParticleEmitter& emitter, float dt);
+    [[nodiscard]] int emitterControlPoint (const ParticleEmitter& emitter) const;
+    [[nodiscard]] const ControlPointData* controlPointAt (int index) const;
+    void startSpawn (ParticleInstance& p, const glm::vec3& color, float lifetime);
     void placeSpawn (
 	ParticleInstance& p, const ControlPointData* cp, int controlPointIndex, const glm::vec3& origin,
 	glm::vec3& offset

+ 2 - 1
src/WallpaperEngine/Render/Objects/CRenderable.cpp

@@ -4,6 +4,7 @@
 #include "WallpaperEngine/Data/Model/Material.h"
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
+#include "WallpaperEngine/Render/TextureNames.h"
 
 using namespace WallpaperEngine;
 using namespace WallpaperEngine::Render::Objects;
@@ -18,7 +19,7 @@ void CRenderable::detectTexture () {
     if (TextureMap* textures = &(*this->m_material.passes.begin ())->textures; !textures->empty ()) {
 	std::string textureName = textures->begin ()->second;
 
-	if (textureName.find ("_rt_") == 0 || textureName.find ("_alias_") == 0) {
+	if (isFramebufferName (textureName)) {
 	    this->m_texture = this->getScene ().findFBO (textureName);
 	} else {
 	    this->m_texture = this->getContext ().resolveTexture (textureName, this->getScene ().getScene ().project);

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

@@ -1,8 +1,6 @@
-#include <SDL.h>
 
 #include "CSound.h"
 
-#include "WallpaperEngine/FileSystem/Container.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 #include <glm/gtc/constants.hpp>
@@ -10,7 +8,6 @@
 
 #include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include <algorithm>
-#include <cfloat>
 #include <cmath>
 #include <limits>
 #include <random>

+ 37 - 36
src/WallpaperEngine/Render/Objects/CText.cpp

@@ -1,21 +1,17 @@
 #include "CText.h"
+#include "ParallaxClamp.h"
 #include "WallpaperEngine/Render/DepthRange.h"
 #include "WallpaperEngine/Render/Fonts/SystemFonts.h"
 
 #include <algorithm>
 #include <array>
-#include <cstdio>
 #include <filesystem>
 #include <map>
 #include <set>
 #include <sstream>
 #include <strings.h>
-#include <unordered_map>
 #include <vector>
 
-#include <glm/gtc/matrix_transform.hpp>
-#include <glm/gtc/type_ptr.hpp>
-
 #include "WallpaperEngine/Assets/AssetLocator.h"
 #include "WallpaperEngine/Data/Model/DynamicValue.h"
 #include "WallpaperEngine/Data/Model/Material.h"
@@ -64,11 +60,25 @@ FontMatch fontconfigMatch (const std::string& font) {
 
     FontMatch match { output.substr (newline + 1), output.substr (0, newline) };
 
-    return !match.path.empty () && std::filesystem::exists (match.path) ? match : FontMatch {};
+    std::error_code error;
+
+    return !match.path.empty () && std::filesystem::exists (match.path, error) ? match : FontMatch {};
 }
 
 std::string installedFamily (const std::vector<std::string>& families) { return Fonts::installedFamilyFile (families); }
 
+const std::vector<std::vector<std::string>> kFallbackBefore = {
+    { "Arial", "Liberation Sans", "Arimo" },
+    { "Segoe UI Emoji" },
+    { "Arial Unicode MS" },
+    { "Segoe UI" },
+};
+const std::vector<std::vector<std::string>> kFallbackAfter = {
+    { "Segoe UI Symbol" },
+    { "Microsoft YaHei", "Noto Sans CJK SC", "Source Han Sans SC", "WenQuanYi Zen Hei", "Droid Sans Fallback" },
+    { "Malgun Gothic", "Noto Sans CJK KR", "Source Han Sans KR" },
+};
+
 // WE's fallback fonts (off_140484C40, per character by sub_1401AD670): Windows fonts and the assets' Twemoji;
 // Windows fonts count when installed under their family (arial.ttf also via metric clones), CJK through the usual Linux
 // CJK families
@@ -118,20 +128,9 @@ std::vector<TextFontSource> weFallbackFonts (const WallpaperEngine::Assets::Asse
 	}
     }
 
-    const std::vector<std::vector<std::string>> before = {
-	{ "Arial", "Liberation Sans", "Arimo" },
-	{ "Segoe UI Emoji" },
-	{ "Arial Unicode MS" },
-	{ "Segoe UI" },
-    };
-    const std::vector<std::vector<std::string>> after = {
-	{ "Segoe UI Symbol" },
-	{ "Microsoft YaHei", "Noto Sans CJK SC", "Source Han Sans SC", "WenQuanYi Zen Hei", "Droid Sans Fallback" },
-	{ "Malgun Gothic", "Noto Sans CJK KR", "Source Han Sans KR" },
-    };
     std::vector<TextFontSource> fonts;
 
-    for (const auto& families : before) {
+    for (const auto& families : kFallbackBefore) {
 	if (std::string path = installedFamily (families); !path.empty ()) {
 	    fonts.push_back ({ nullptr, std::move (path) });
 	}
@@ -141,7 +140,7 @@ std::vector<TextFontSource> weFallbackFonts (const WallpaperEngine::Assets::Asse
 	fonts.push_back ({ twemoji, "fonts/TwemojiMozilla.ttf" });
     }
 
-    for (const auto& families : after) {
+    for (const auto& families : kFallbackAfter) {
 	if (std::string path = installedFamily (families); !path.empty ()) {
 	    fonts.push_back ({ nullptr, std::move (path) });
 	}
@@ -228,22 +227,6 @@ const Material& compositeMaterial () {
     return *material;
 }
 
-// same as CImage.cpp's clampParallaxAxis
-float clampParallaxAxis (float offset, float edgeA, float edgeB, float visibleLow, float visibleHigh) {
-    const float low = std::min (edgeA, edgeB);
-    const float high = std::max (edgeA, edgeB);
-    const float maxOffset = visibleLow - low;
-    const float minOffset = visibleHigh - high;
-
-    if (minOffset > maxOffset) {
-	return offset;
-    }
-
-    // a layer that doesn't cover the screen at rest stays where the scene puts it (3621923790's hair), the clamp
-    // only keeps the parallax from uncovering more
-    return std::clamp (offset, std::min (minOffset, 0.0f), std::max (maxOffset, 0.0f));
-}
-
 TextAlign parseAlign (const std::string& align) {
     if (align == "left") {
 	return TextAlign::Left;
@@ -256,6 +239,24 @@ TextAlign parseAlign (const std::string& align) {
 }
 }
 
+std::vector<std::function<void ()>> CText::fontLookups (const std::vector<std::string>& fonts) {
+    std::vector<std::function<void ()>> lookups;
+
+    for (const auto* groups : { &kFallbackBefore, &kFallbackAfter }) {
+	for (const auto& families : *groups) {
+	    for (const auto& family : families) {
+		lookups.emplace_back ([family] { (void)Fonts::installedFamilyFile ({ family }); });
+	    }
+	}
+    }
+
+    for (const auto& font : fonts) {
+	lookups.emplace_back ([font] { (void)fontconfigMatch (font); });
+    }
+
+    return lookups;
+}
+
 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) {
@@ -441,7 +442,7 @@ bool CText::loadFont () {
     }
 
     // a font WE can't load falls back to arial.ttf
-    const bool systemFont = m_loadedFont.rfind ("systemfont_", 0) == 0;
+    const bool systemFont = m_loadedFont.starts_with ("systemfont_");
 
     const FontMatch match = fontconfigMatch (systemFont ? m_loadedFont : std::string ("systemfont_arial"));
     std::string fontPath = match.path;

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

@@ -1,5 +1,6 @@
 #pragma once
 
+#include <functional>
 #include <string>
 #include <vector>
 
@@ -31,6 +32,11 @@ public:
     CText (Wallpapers::CScene& scene, const Text& text);
     ~CText () override;
 
+    /** The fontconfig lookups a text object makes (the fonts WE falls back to, and the match for each of fonts), one
+     * call each. They are cached, so running them before the objects are built takes the process spawns off the
+     * loading thread. Safe on any thread */
+    static std::vector<std::function<void ()>> fontLookups (const std::vector<std::string>& fonts);
+
     void setup () override;
     void render () override;
 

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

@@ -14,10 +14,10 @@
 #include "WallpaperEngine/Desktop/UserShortcut.h"
 #include "WallpaperEngine/Render/Helpers/ContextAware.h"
 
-#include "WallpaperEngine/Data/Model/Effect.h"
 #include "WallpaperEngine/Data/Model/Material.h"
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Data/Model/Property.h"
+#include "WallpaperEngine/Render/TextureNames.h"
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 
 #include "WallpaperEngine/Render/CFBO.h"
@@ -286,22 +286,36 @@ std::shared_ptr<const TextureProvider> CPass::resolveNamedTexture (const std::st
 	}
     }
 
-    if (name.starts_with ("_rt_") || name.starts_with ("_alias_")) {
+    if (isFramebufferName (name)) {
 	return this->resolveFBO (name);
     }
 
     return this->getContext ().resolveTexture (name, this->m_renderable.getScene ().getScene ().project);
 }
 
-void CPass::bindMissingTexture (int index) {
-    // WE's missing texture (sub_1400EEF70)
+void CPass::chainTexture (int index, std::shared_ptr<const TextureProvider> texture) {
     const auto it = this->m_textures.find (index);
     this->m_textures[index] = std::make_shared<TextureChainEntry> (TextureChainEntry {
-	.texture = this->m_renderable.getScene ().getMissingTexture (),
+	.texture = std::move (texture),
 	.next = it != this->m_textures.end () ? it->second : nullptr,
     });
 }
 
+void CPass::bindMissingTexture (int index) {
+    // WE's missing texture (sub_1400EEF70)
+    this->chainTexture (index, this->m_renderable.getScene ().getMissingTexture ());
+}
+
+void CPass::bindNamedTexture (int index, const std::string& textureName, bool track) {
+    auto texture = this->resolveNamedTexture (textureName);
+
+    this->chainTexture (index, texture);
+
+    if (track && !isFramebufferName (textureName)) {
+	this->trackPlayback (texture);
+    }
+}
+
 std::shared_ptr<const CFBO> CPass::resolveFBO (const std::string& name) const {
     std::shared_ptr<const CFBO> fbo = this->m_fboProvider->find (name);
 
@@ -896,8 +910,6 @@ void CPass::setPreviousInput (std::shared_ptr<const TextureProvider> input) {
 }
 
 void CPass::setTexture (int index, std::shared_ptr<const TextureProvider> texture) {
-    const auto it = this->m_textures.find (index);
-
     // the uniforms were set up with the pass, a texture set afterwards brings its own size
     if (texture != nullptr) {
 	this->addUniform ("g_Texture" + std::to_string (index) + "Resolution", texture->getResolution ());
@@ -907,10 +919,7 @@ void CPass::setTexture (int index, std::shared_ptr<const TextureProvider> textur
 	}
     }
 
-    this->m_textures[index] = std::make_shared<TextureChainEntry> (TextureChainEntry {
-	.texture = std::move (texture),
-	.next = it != this->m_textures.end () ? it->second : nullptr,
-    });
+    this->chainTexture (index, std::move (texture));
 }
 
 void CPass::setEffectModelViewProjectionMatrix (const glm::mat4* projection) {
@@ -1486,7 +1495,7 @@ bool CPass::applyFormatCombos (const TextureMap& passTextures, const TextureMap&
 		}
 	    }
 
-	    if (!name.has_value () || name->starts_with ("_rt_") || name->starts_with ("_alias_")) {
+	    if (!name.has_value () || isFramebufferName (*name)) {
 		continue;
 	    }
 
@@ -1557,16 +1566,7 @@ void CPass::setupTextureUniforms () {
 
     for (const auto& [index, textureName] : this->m_shader->getFragment ().getTextures ()) {
 	try {
-	    auto texture = this->resolveNamedTexture (textureName);
-
-	    const auto it = this->m_textures.find (index);
-	    const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
-		.texture = texture,
-		.next = it != this->m_textures.end () ? it->second : nullptr,
-	    });
-
-	    this->m_textures[index] = chain;
-
+	    this->bindNamedTexture (index, textureName, false);
 	} catch (std::runtime_error& ex) {
 	    sLog.error (
 		"Cannot resolve texture '", textureName, "' (index=", index,
@@ -1578,19 +1578,7 @@ void CPass::setupTextureUniforms () {
 
     for (const auto& [index, textureName] : this->m_pass.textures) {
 	try {
-	    auto texture = this->resolveNamedTexture (textureName);
-
-	    const auto it = this->m_textures.find (index);
-	    const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
-		.texture = texture,
-		.next = it != this->m_textures.end () ? it->second : nullptr,
-	    });
-
-	    this->m_textures[index] = chain;
-
-	    if (textureName.find ("_rt_") != 0 && textureName.find ("_alias_") != 0) {
-		this->trackPlayback (texture);
-	    }
+	    this->bindNamedTexture (index, textureName, true);
 	} catch (std::runtime_error& ex) {
 	    sLog.error (
 		"Cannot resolve texture '", textureName, "' (index=", index,
@@ -1609,18 +1597,7 @@ void CPass::setupTextureUniforms () {
 	const std::string& textureName = *resolvedName;
 
 	try {
-	    auto texture = this->resolveNamedTexture (textureName);
-
-	    const auto it = this->m_textures.find (index);
-	    const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
-		.texture = texture,
-		.next = it != this->m_textures.end () ? it->second : nullptr,
-	    });
-
-	    this->m_textures[index] = chain;
-	    if (textureName.find ("_rt_") != 0 && textureName.find ("_alias_") != 0) {
-		this->trackPlayback (texture);
-	    }
+	    this->bindNamedTexture (index, textureName, true);
 	} catch (std::runtime_error& ex) {
 	    sLog.error (
 		"Cannot resolve user texture '", textureName, "' (index=", index,
@@ -1641,19 +1618,7 @@ void CPass::setupTextureUniforms () {
 	}
 
 	try {
-	    auto texture = this->resolveNamedTexture (textureName);
-
-	    const auto it = this->m_textures.find (slot);
-	    const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
-		.texture = texture,
-		.next = it != this->m_textures.end () ? it->second : nullptr,
-	    });
-
-	    this->m_textures[slot] = chain;
-
-	    if (textureName.find ("_rt_") != 0 && textureName.find ("_alias_") != 0) {
-		this->trackPlayback (texture);
-	    }
+	    this->bindNamedTexture (slot, textureName, true);
 	} catch (std::runtime_error& ex) {
 	    sLog.error (
 		"Cannot resolve texture '", textureName, "' (slot=", slot, ", object id=", this->m_renderable.getId (),
@@ -1671,19 +1636,7 @@ void CPass::setupTextureUniforms () {
 	const std::string& textureName = *resolvedName;
 
 	try {
-	    auto texture = this->resolveNamedTexture (textureName);
-
-	    const auto it = this->m_textures.find (index);
-	    const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
-		.texture = texture,
-		.next = it != this->m_textures.end () ? it->second : nullptr,
-	    });
-
-	    this->m_textures[index] = chain;
-
-	    if (textureName.find ("_rt_") != 0 && textureName.find ("_alias_") != 0) {
-		this->trackPlayback (texture);
-	    }
+	    this->bindNamedTexture (index, textureName, true);
 	} catch (std::runtime_error& ex) {
 	    sLog.error (
 		"Cannot resolve user texture '", textureName, "' (index=", index,
@@ -2177,30 +2130,12 @@ void CPass::addUniform (const std::string& name, const int* value, int count) {
     this->addUniform (name, UniformType::Integer, value, count);
 }
 
-void CPass::addUniform (const std::string& name, const int** value) {
-    this->addUniform (name, UniformType::Integer, value);
-}
-
-void CPass::addUniform (const std::string& name, double value) { this->addUniform (name, UniformType::Double, value); }
-
-void CPass::addUniform (const std::string& name, const double* value, int count) {
-    this->addUniform (name, UniformType::Double, value, count);
-}
-
-void CPass::addUniform (const std::string& name, const double** value) {
-    this->addUniform (name, UniformType::Double, value);
-}
-
 void CPass::addUniform (const std::string& name, float value) { this->addUniform (name, UniformType::Float, value); }
 
 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, const float** value) {
-    this->addUniform (name, UniformType::Float, value);
-}
-
 void CPass::addUniform (const std::string& name, glm::vec2 value) {
     this->addUniform (name, UniformType::Vector2, value);
 }

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

@@ -96,6 +96,8 @@ public:
     [[nodiscard]] DynamicValue* getScriptConstant (const std::string& name);
     [[nodiscard]] std::shared_ptr<const CFBO> resolveFBO (const std::string& name) const;
     void bindMissingTexture (int index);
+    void chainTexture (int index, std::shared_ptr<const TextureProvider> texture);
+    void bindNamedTexture (int index, const std::string& textureName, bool track);
     [[nodiscard]] std::shared_ptr<const TextureProvider> resolveNamedTexture (const std::string& name) const;
 
     [[nodiscard]] std::shared_ptr<const FBOProvider> getFBOProvider () const;
@@ -229,7 +231,6 @@ private:
     void addUniform (ShaderVariable* value);
     void addUniform (const ShaderVariable* value, const DynamicValue* setting);
     void addUniform (const std::string& name, int value);
-    void addUniform (const std::string& name, double 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);
@@ -237,11 +238,7 @@ private:
     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 double* value, int count = 1);
     void addUniform (const std::string& name, const glm::vec2* value);
-    void addUniform (const std::string& name, const int** value);
-    void addUniform (const std::string& name, const double** value);
-    void addUniform (const std::string& name, const float** 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);

+ 23 - 0
src/WallpaperEngine/Render/Objects/ParallaxClamp.h

@@ -0,0 +1,23 @@
+#pragma once
+
+#include <algorithm>
+
+namespace WallpaperEngine::Render::Objects {
+// keeps an edge pair (m_pos.x/.z) from sliding into the visible canvas, so the image never uncovers ground it has no
+// pixels for; images too small to cover the axis move freely and cropped canvas may scroll in. WE has no clamp
+// (sub_14018AAC0)
+inline float clampParallaxAxis (float offset, float edgeA, float edgeB, float visibleLow, float visibleHigh) {
+    const float low = std::min (edgeA, edgeB);
+    const float high = std::max (edgeA, edgeB);
+    const float maxOffset = visibleLow - low;
+    const float minOffset = visibleHigh - high;
+
+    if (minOffset > maxOffset) {
+	return offset;
+    }
+
+    // a layer that doesn't cover the screen at rest stays where the scene puts it (3621923790's hair), the clamp
+    // only keeps the parallax from uncovering more
+    return std::clamp (offset, std::min (minOffset, 0.0f), std::max (maxOffset, 0.0f));
+}
+}

+ 9 - 9
src/WallpaperEngine/Render/Objects/PuppetClipping.cpp

@@ -204,9 +204,9 @@ void PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 	positionOf[this->order[position]] = position;
     }
 
-    std::vector<Record> records = this->records;
+    std::vector<Record> ordered = this->records;
 
-    for (auto& record : records) {
+    for (auto& record : ordered) {
 	for (auto* list : { &record.targets, &record.sources }) {
 	    for (auto& part : *list) {
 		part = positionOf[part];
@@ -216,7 +216,7 @@ void PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 
     std::vector<uint32_t> partFlags (this->parts.size (), 0);
 
-    for (const auto& record : records) {
+    for (const auto& record : ordered) {
 	for (const auto part : record.targets) {
 	    partFlags[part] |= Target;
 	}
@@ -244,11 +244,11 @@ void PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 	std::vector<uint32_t> targets;
     };
 
-    std::vector<Entry> entries (records.size ());
+    std::vector<Entry> entries (ordered.size ());
     std::set<uint32_t> hiddenSources;
 
-    for (size_t index = 0; index < records.size (); index++) {
-	const auto& record = records[index];
+    for (size_t index = 0; index < ordered.size (); index++) {
+	const auto& record = ordered[index];
 	auto& entry = entries[index];
 	entry.record = static_cast<uint32_t> (index);
 
@@ -282,7 +282,7 @@ void PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 
     // a nested mask can only be drawn once its ancestors' sources are
     for (size_t index = 0; index < entries.size (); index++) {
-	for (int parent = records[index].parent; parent != -1; parent = records[parent].parent) {
+	for (int parent = ordered[index].parent; parent != -1; parent = ordered[parent].parent) {
 	    entries[index].lastSource = std::max (entries[index].lastSource, entries[parent].lastSource);
 	}
     }
@@ -325,7 +325,7 @@ void PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
     // sub_14020CAB0
     const auto drawMasked = [&] (const Entry& entry, const std::vector<uint32_t>& targets) {
 	std::vector<int> chain;
-	for (int parent = records[entry.record].parent; parent != -1; parent = records[parent].parent) {
+	for (int parent = ordered[entry.record].parent; parent != -1; parent = ordered[parent].parent) {
 	    chain.push_back (parent);
 	}
 
@@ -361,7 +361,7 @@ void PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 
 	if (flags & Source) {
 	    for (const auto& entry : entries) {
-		if ((records[entry.record].flags & AtTargets) || entry.lastSource != part) {
+		if ((ordered[entry.record].flags & AtTargets) || entry.lastSource != part) {
 		    continue;
 		}
 

+ 2 - 3
src/WallpaperEngine/Render/Objects/PuppetIK.cpp

@@ -9,7 +9,6 @@
 #include <cmath>
 
 #include "WallpaperEngine/Data/Utils/FloatCompare.h"
-#include <glm/gtc/quaternion.hpp>
 #include <glm/gtc/type_ptr.hpp>
 
 using JSON = WallpaperEngine::Data::JSON::JSON;
@@ -706,10 +705,10 @@ void solvePuppetIKChain (
 		    }
 
 		    const glm::mat4& target = model[rule.target];
-		    const float inverse = 1.0f
+		    const float invLength = 1.0f
 			/ std::sqrt ((target[0].w * target[0].w + target[0].z * target[0].z)
 				     + (target[0].y * target[0].y + target[0].x * target[0].x));
-		    const glm::vec3 axis = glm::vec3 (target[0]) * inverse;
+		    const glm::vec3 axis = glm::vec3 (target[0]) * invLength;
 
 		    for (const auto& link : chain.links) {
 			for (const auto& entry : link.entries) {

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor