Переглянути джерело

Release prep: pointer and pause fixes, X11 background window, GNOME 46 frozen wallpaper fix, VM release test rig

- cursor hit test and script cursor position were mirrored on flipped (Wayland) and unflipped (X11) outputs, weekday hover zones picked the opposite day
  - X11: background window for desktops that paint over the root window (GNOME, Pantheon, Cinnamon) and for XFCE, MATE and LXQt covering desktop windows, one window across all
  screens
  - X11 fullscreen pause ignores minimized windows and windows on other desktops
  - PulseAudio: playing detector ignores corked and muted streams, race fixed; recorder no longer aborts after a capture failure; automute keeps following other programs while
  the wallpaper is paused
  - KWin 6.4: a new script could get the id of a loaded one after an unload and never ran
  - hotswap from a scene that left the colour mask alpha off no longer leaves a video wallpaper transparent
  - GNOME Shell extension hides orphaned wallpaper actors (frozen wallpaper after the engine stopped on GNOME 46)
  - fixes from static analysis: GifAnimation guard, DBusMediaSource dead store, uninitialized members
  - tools/linuxvm: release matrix of 25 distro VMs with profiles, pointer, dock, clean install and update checks, GNOME extension debug scripts
UwU 1 місяць тому
батько
коміт
d62d42972f
68 змінених файлів з 1830 додано та 475 видалено
  1. 2 0
      CMakeLists.txt
  2. 42 0
      README.md
  3. 11 0
      gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/extension.js
  4. 5 0
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  5. 7 1
      src/WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.cpp
  6. 2 1
      src/WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.h
  7. 12 14
      src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.cpp
  8. 2 0
      src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h
  9. 10 5
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.cpp
  10. 1 0
      src/WallpaperEngine/Audio/Drivers/Recorders/PulseAudioPlaybackRecorder.h
  11. 89 35
      src/WallpaperEngine/Desktop/KWinScript.cpp
  12. 1 1
      src/WallpaperEngine/Desktop/KWinScript.h
  13. 1 3
      src/WallpaperEngine/Media/DBusMediaSource.cpp
  14. 1 1
      src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.h
  15. 83 1
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp
  16. 2 0
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.h
  17. 15 265
      src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.cpp
  18. 6 17
      src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.h
  19. 2 2
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  20. 269 0
      src/WallpaperEngine/Render/Drivers/Output/X11BackgroundWindow.cpp
  21. 38 0
      src/WallpaperEngine/Render/Drivers/Output/X11BackgroundWindow.h
  22. 83 9
      src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
  23. 6 3
      src/WallpaperEngine/Render/Drivers/Output/X11Output.h
  24. 1 1
      src/WallpaperEngine/Render/GifAnimation.cpp
  25. 8 4
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  26. 10 0
      src/WallpaperEngine/Render/Wallpapers/MouseMapping.h
  27. 1 0
      src/WallpaperEngine/Testing/Cases/HyprlandIPC.cpp
  28. 1 0
      src/WallpaperEngine/Testing/Cases/MediaCover.cpp
  29. 15 0
      src/WallpaperEngine/Testing/Cases/MouseCoordinates.cpp
  30. 12 0
      src/WallpaperEngine/VideoPlayback/MPV/GLPlayer.cpp
  31. 22 0
      tools/check_hotswap_video.sh
  32. 143 54
      tools/linuxvm/RELEASE_TESTING.md
  33. 1 1
      tools/linuxvm/autostart_check.sh
  34. 5 4
      tools/linuxvm/bootstrap_ssh.sh
  35. 34 3
      tools/linuxvm/check_frame.py
  36. 85 0
      tools/linuxvm/clean_install_check.sh
  37. 127 0
      tools/linuxvm/debug_extension.py
  38. 1 1
      tools/linuxvm/deps_check.sh
  39. 38 0
      tools/linuxvm/fake_github_lib.sh
  40. 12 0
      tools/linuxvm/ghost_diag.sh
  41. 15 0
      tools/linuxvm/ghost_loop.sh
  42. 43 0
      tools/linuxvm/ghost_run.sh
  43. 201 7
      tools/linuxvm/guest_test.sh
  44. 59 0
      tools/linuxvm/hover_check.py
  45. 2 2
      tools/linuxvm/linuxvm.sh
  46. 13 2
      tools/linuxvm/maximize_kde.sh
  47. 36 0
      tools/linuxvm/pointer_check.sh
  48. 6 0
      tools/linuxvm/profiles/arch-hypr.sh
  49. 3 0
      tools/linuxvm/profiles/arch-xfce.sh
  50. 8 0
      tools/linuxvm/profiles/cachyos-hypr.sh
  51. 1 1
      tools/linuxvm/profiles/cachyos-kde.sh
  52. 3 0
      tools/linuxvm/profiles/debian-xfce.sh
  53. 6 0
      tools/linuxvm/profiles/elementary.sh
  54. 9 0
      tools/linuxvm/profiles/endeavouros-xfce.sh
  55. 7 0
      tools/linuxvm/profiles/endeavouros.sh
  56. 7 0
      tools/linuxvm/profiles/garuda-kde.sh
  57. 9 0
      tools/linuxvm/profiles/manjaro-xfce.sh
  58. 9 0
      tools/linuxvm/profiles/mint-cinnamon.sh
  59. 9 0
      tools/linuxvm/profiles/mint22-2.sh
  60. 9 0
      tools/linuxvm/profiles/mx-xfce.sh
  61. 3 0
      tools/linuxvm/profiles/opensuse-xfce.sh
  62. 8 0
      tools/linuxvm/profiles/steamos.sh
  63. 6 0
      tools/linuxvm/profiles/zorin-gnome.sh
  64. 11 1
      tools/linuxvm/qtype.sh
  65. 74 15
      tools/linuxvm/release_check.sh
  66. 31 1
      tools/linuxvm/sessenv.sh
  67. 22 12
      tools/linuxvm/update_check.sh
  68. 14 8
      tools/linuxvm/wem_check.sh

+ 2 - 0
CMakeLists.txt

@@ -503,6 +503,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/Drivers/Output/Output.h
     src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.cpp
     src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.h
+    src/WallpaperEngine/Render/Drivers/Output/X11BackgroundWindow.cpp
+    src/WallpaperEngine/Render/Drivers/Output/X11BackgroundWindow.h
     src/WallpaperEngine/Render/Drivers/Output/GLFWOutputViewport.cpp
     src/WallpaperEngine/Render/Drivers/Output/GLFWOutputViewport.h
     src/WallpaperEngine/Render/Drivers/Output/OutputViewport.cpp

+ 42 - 0
README.md

@@ -113,6 +113,48 @@ Other ways to get it:
 - **Flatpak**: [WE Manager](https://github.com/WallpaperEngineLover/we_manager)'s Flatpak comes with the engine.
 - **Nix**: `nix run github:WallpaperEngineLover/linux-wallpaperengine-kde -- --help` builds it from source against nixpkgs (the first build also compiles Node.js as a shared library for V8) (`packages.x86_64-linux.generic` without the KDE integration, `overlays.default` adds `linux-wallpaperengine-kde`).
 
+## Tested distributions
+
+Every release is tried in a virtual machine per row below (KVM, a real desktop session, started from a clean disk): the
+engine with a scene, a particle scene, a video, a preset and web wallpapers, hotswap, pause behind fullscreen windows,
+cleanup after a crash, and WE Manager's install, update and autostart. Several rows also check two monitors, minimizing a
+fullscreen window and automute.
+
+- **Supported**: passes the whole run.
+- **Work in progress**: a check fails, or the distribution has not been brought through the run yet.
+- **Not supported**: not tested, see the note.
+
+| Distribution | Desktop (session) | Status | Notes |
+|--------------|-------------------|--------|-------|
+| Fedora 44 | KDE Plasma (Wayland) | Supported | |
+| Fedora 44 | GNOME (Wayland) | Supported | |
+| Ubuntu 24.04 | GNOME (Wayland) | Supported | |
+| Debian 13 | GNOME (Wayland) | Supported | |
+| Debian 13 | XFCE (X11) | Supported | |
+| openSUSE Tumbleweed | KDE Plasma (Wayland) | Supported | |
+| openSUSE Leap 16 | KDE Plasma (Wayland) | Supported | |
+| openSUSE Tumbleweed | XFCE (X11) | Supported | |
+| Arch Linux | Hyprland (Wayland) | Supported | |
+| Arch Linux | XFCE (X11) | Supported | |
+| Manjaro | KDE Plasma (Wayland) | Supported | |
+| Manjaro | XFCE (X11) | Supported | |
+| CachyOS | KDE Plasma (Wayland) | Supported | |
+| CachyOS | Hyprland (Wayland) | Supported | |
+| Garuda Linux | KDE Plasma (Wayland) | Supported | |
+| EndeavourOS | KDE Plasma (Wayland) | Supported | |
+| EndeavourOS | XFCE (X11) | Supported | |
+| Linux Mint 22.2 | Cinnamon (X11) | Supported | |
+| MX Linux 25.3 | XFCE (X11) | Supported | |
+| Zorin OS | GNOME (Wayland) | Supported | its Xorg session shows nothing in root mode |
+| Pop!_OS | COSMIC | Supported | |
+| Bazzite | KDE Plasma (Wayland), image based | Supported | portable build or Flatpak |
+| SteamOS | KDE Plasma (Wayland), read-only root | Supported | system libraries cannot be installed on the read-only root, so that step is not part of the test |
+| elementary OS | Pantheon (Wayland) | Work in progress | Gala has no `wlr-layer-shell`, the X11 session needs `--window-background` |
+| ChimeraOS | gamescope, GNOME | Not supported | not tested: its Mesa cannot draw in a VM, and gamescope's game session has no desktop to put a wallpaper on. The GNOME desktop mode could theoretically work |
+
+Other distributions and desktops that are not listed (Sway, niri, KDE on X11, other Ubuntu flavours, ...) may well work,
+they are just not part of the release test.
+
 ## Build
 
 ```bash

+ 11 - 0
gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/extension.js

@@ -132,6 +132,7 @@ export default class WallpaperEngineExtension extends Extension {
             global.display.connect('restacked', () => {
                 this._pickStale = true;
                 this._pruneWallpapers();
+                this._hideOrphanActors();
                 this._keepBelowDesktopWindows();
                 this._queueState();
             }),
@@ -463,6 +464,16 @@ export default class WallpaperEngineExtension extends Extension {
         }
     }
 
+    // Shell 46 can free a wallpaper window without unmanaging it, its actor then stays in the window group with the last frame
+    _hideOrphanActors() {
+        for (const actor of global.window_group.get_children()) {
+            const window = actor.meta_window;
+            if (!window || !actor.visible || window.get_compositor_private() === actor || !this._isWallpaper(window))
+                continue;
+            actor.hide();
+        }
+    }
+
     // GNOME 45 drops a gone client's window without 'unmanaged' (Shell 45.2)
     _pruneWallpapers() {
         const live = new Set(global.display.list_all_windows());

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

@@ -2913,6 +2913,11 @@ void WallpaperApplication::render () {
 	usleep (FULLSCREEN_CHECK_WAIT_TIME);
 	m_videoDriver->dispatchWhilePaused ();
 
+	// automute keeps following other programs' sound, or the music stays on until the wallpaper resumes
+	if (this->m_audioDriver != nullptr) {
+	    this->m_audioDriver->getAudioDetector ().update ();
+	}
+
 	const uint32_t reasons = this->pauseReasons ();
 	this->logPauseReasons (reasons);
 

+ 7 - 1
src/WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.cpp

@@ -1,4 +1,5 @@
 #include "AudioPlayingDetector.h"
+#include "WallpaperEngine/Logging/Log.h"
 
 namespace WallpaperEngine::Audio::Drivers::Detectors {
 AudioPlayingDetector::AudioPlayingDetector (
@@ -16,7 +17,12 @@ const Render::Drivers::Detectors::FullScreenDetector& AudioPlayingDetector::getF
     return this->m_fullscreenDetector;
 }
 
-void AudioPlayingDetector::setIsPlaying (const bool newState) { this->m_isPlaying = newState; }
+void AudioPlayingDetector::setIsPlaying (const bool newState) {
+    if (newState != this->m_isPlaying) {
+	sLog.out (newState ? "Automute: another app is playing sound" : "Automute: other apps stopped playing sound");
+    }
+    this->m_isPlaying = newState;
+}
 
 void AudioPlayingDetector::update () { }
 

+ 2 - 1
src/WallpaperEngine/Audio/Drivers/Detectors/AudioPlayingDetector.h

@@ -2,6 +2,7 @@
 
 #include "WallpaperEngine/Application/ApplicationContext.h"
 #include "WallpaperEngine/Render/Drivers/Detectors/FullScreenDetector.h"
+#include <atomic>
 
 namespace WallpaperEngine {
 namespace Application {
@@ -33,7 +34,7 @@ namespace Audio::Drivers::Detectors {
 	[[nodiscard]] const Render::Drivers::Detectors::FullScreenDetector& getFullscreenDetector () const;
 
     private:
-	bool m_isPlaying = false;
+	std::atomic<bool> m_isPlaying = false;
 
 	Application::ApplicationContext& m_applicationContext;
 	const Render::Drivers::Detectors::FullScreenDetector& m_fullscreenDetector;

+ 12 - 14
src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.cpp

@@ -17,21 +17,12 @@ void sinkInputInfoCallback (pa_context* context, const pa_sink_input_info* info,
 
     const char* value = pa_proplist_gets (info->proplist, PA_PROP_APPLICATION_PROCESS_ID);
 
-    if (value && strtol (value, nullptr, 10) != getpid () && pa_cvolume_avg (&info->volume) != PA_VOLUME_MUTED) {
-	detector->setIsPlaying (true);
+    if (value && strtol (value, nullptr, 10) != getpid () && !info->corked && !info->mute
+	&& pa_cvolume_avg (&info->volume) != PA_VOLUME_MUTED) {
+	detector->markPlaying ();
     }
 }
 
-void defaultSinkInfoCallback (pa_context* context, const pa_server_info* info, void* userdata) {
-    if (info == nullptr) {
-	return;
-    }
-
-    pa_operation* op = pa_context_get_sink_input_info_list (context, sinkInputInfoCallback, userdata);
-
-    pa_operation_unref (op);
-}
-
 PulseAudioPlayingDetector::PulseAudioPlayingDetector (
     Application::ApplicationContext& appContext,
     const Render::Drivers::Detectors::FullScreenDetector& fullscreenDetector
@@ -66,14 +57,21 @@ void PulseAudioPlayingDetector::update () {
 	return this->setIsPlaying (true);
     }
 
-    this->setIsPlaying (false);
+    // the answer is set once the list is complete, the audio thread reads it while the query runs
+    this->m_found = false;
 
-    pa_operation* op = pa_context_get_server_info (this->m_context, defaultSinkInfoCallback, this);
+    pa_operation* op = pa_context_get_sink_input_info_list (this->m_context, sinkInputInfoCallback, this);
+    if (op == nullptr) {
+	return;
+    }
 
     while (pa_operation_get_state (op) == PA_OPERATION_RUNNING) {
 	pa_mainloop_iterate (this->m_mainloop, 1, nullptr);
     }
 
     pa_operation_unref (op);
+    this->setIsPlaying (this->m_found);
 }
+
+void PulseAudioPlayingDetector::markPlaying () { this->m_found = true; }
 }

+ 2 - 0
src/WallpaperEngine/Audio/Drivers/Detectors/PulseAudioPlayingDetector.h

@@ -14,10 +14,12 @@ public:
     ~PulseAudioPlayingDetector () override;
 
     void update () override;
+    void markPlaying ();
 
 private:
     pa_mainloop* m_mainloop = nullptr;
     pa_mainloop_api* m_mainloopApi = nullptr;
     pa_context* m_context = nullptr;
+    bool m_found = false;
 };
 }

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

@@ -40,9 +40,10 @@ void pa_retry_capture_cb (pa_mainloop_api* api, pa_time_event* event, const stru
 	return;
     }
 
-    pa_context* ctx = pa_stream_get_context (recorder->captureStream);
+    // a failed stream has let go of its context by now
+    pa_context* ctx = recorder->context;
 
-    if (pa_context_get_state (ctx) != PA_CONTEXT_READY) {
+    if (ctx == nullptr || pa_context_get_state (ctx) != PA_CONTEXT_READY) {
 	return;
     }
 
@@ -68,9 +69,11 @@ void pa_stream_notify_cb (pa_stream* stream, void* userdata) {
 		sLog.error ("Audio capture stream lost, retrying every second");
 	    }
 
-	    pa_context_rttime_new (
-		pa_stream_get_context (stream), pa_rtclock_now () + PA_USEC_PER_SEC, &pa_retry_capture_cb, userdata
-	    );
+	    if (recorder->context != nullptr) {
+		pa_context_rttime_new (
+		    recorder->context, pa_rtclock_now () + PA_USEC_PER_SEC, &pa_retry_capture_cb, userdata
+		);
+	    }
 	    break;
 	case PA_STREAM_READY:
 	    if (recorder->captureLost) {
@@ -129,6 +132,8 @@ void pa_server_info_cb (pa_context* ctx, const pa_server_info* info, void* userd
     auto* recorder = static_cast<PulseAudioPlaybackRecorder::PulseAudioData*> (userdata);
     const std::string monitor_name = std::string (info->default_sink_name) + ".monitor";
 
+    recorder->context = ctx;
+
     if (recorder->captureStream) {
 	// sink/source events also fire for volume and state changes (another wallpaper starting its sounds),
 	// only re-take the stream when the default sink moved or the old one died

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

@@ -19,6 +19,7 @@ public:
 	pa_stream* captureStream;
 	std::string monitorName;
 	bool captureLost;
+	pa_context* context = nullptr;
     };
 
     PulseAudioPlaybackRecorder ();

+ 89 - 35
src/WallpaperEngine/Desktop/KWinScript.cpp

@@ -11,6 +11,7 @@
 #include <cstdlib>
 #include <cstring>
 #include <fcntl.h>
+#include <set>
 #include <spawn.h>
 #include <sys/file.h>
 #include <unistd.h>
@@ -32,6 +33,7 @@ DBusMessage* callKWin (DBusConnection* connection, DBusMessage* call, const char
 }
 
 constexpr const char* SCRIPT_PREFIX = "lwe-";
+constexpr int MAX_LOAD_ATTEMPTS = 4;
 
 void unloadScript (DBusConnection* connection, const std::string& pluginName) {
     DBusMessage* unload
@@ -44,6 +46,38 @@ void unloadScript (DBusConnection* connection, const std::string& pluginName) {
     }
 }
 
+std::set<int> loadedScriptIds (DBusConnection* connection) {
+    std::set<int> ids;
+    DBusMessage* call = dbus_message_new_method_call (
+	"org.kde.KWin", "/Scripting", "org.freedesktop.DBus.Introspectable", "Introspect"
+    );
+    DBusMessage* reply = callKWin (connection, call, "Introspect");
+
+    if (reply == nullptr) {
+	return ids;
+    }
+
+    const char* xml = nullptr;
+
+    if (dbus_message_get_args (reply, nullptr, DBUS_TYPE_STRING, &xml, DBUS_TYPE_INVALID) && xml != nullptr) {
+	const std::string text = xml;
+	const std::string marker = "<node name=\"Script";
+
+	for (size_t at = text.find (marker); at != std::string::npos; at = text.find (marker, at + 1)) {
+	    const char* digits = text.c_str () + at + marker.size ();
+	    char* end = nullptr;
+	    const long id = std::strtol (digits, &end, 10);
+
+	    if (end != digits) {
+		ids.insert (static_cast<int> (id));
+	    }
+	}
+    }
+
+    dbus_message_unref (reply);
+    return ids;
+}
+
 bool writeAll (int descriptor, const std::string& text) {
     for (size_t done = 0; done < text.size ();) {
 	const ssize_t wrote = ::write (descriptor, text.data () + done, text.size () - done);
@@ -230,55 +264,75 @@ KWinScript::KWinScript (DBusConnection* connection, std::string pluginName, cons
 	return;
     }
 
-    DBusMessage* load
-	= dbus_message_new_method_call ("org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting", "loadScript");
-    const char* pathArg = this->m_path.c_str ();
-    const char* nameArg = this->m_pluginName.c_str ();
-    dbus_message_append_args (load, DBUS_TYPE_STRING, &pathArg, DBUS_TYPE_STRING, &nameArg, DBUS_TYPE_INVALID);
+    // KWin 6.4 numbers scripts by how many are loaded, so after an earlier script was unloaded the next one gets the id
+    // of a live one and "run" starts that one again, this script never runs. The collided entry stays loaded as
+    // padding and the script is loaded again under another name, which gets the next number
+    const auto liveBefore = loadedScriptIds (this->m_connection);
+    std::string error;
 
-    DBusMessage* reply = callKWin (this->m_connection, load, "loadScript");
-    dbus_int32_t scriptId = -1;
+    for (int attempt = 0; attempt < MAX_LOAD_ATTEMPTS; attempt++) {
+	const std::string name
+	    = attempt == 0 ? this->m_pluginName : this->m_pluginName + "-" + std::to_string (attempt);
 
-    if (reply != nullptr) {
-	dbus_message_get_args (reply, nullptr, DBUS_TYPE_INT32, &scriptId, DBUS_TYPE_INVALID);
-	dbus_message_unref (reply);
-    }
+	DBusMessage* load
+	    = dbus_message_new_method_call ("org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting", "loadScript");
+	const char* pathArg = this->m_path.c_str ();
+	const char* nameArg = name.c_str ();
+	dbus_message_append_args (load, DBUS_TYPE_STRING, &pathArg, DBUS_TYPE_STRING, &nameArg, DBUS_TYPE_INVALID);
 
-    if (scriptId < 0) {
-	sLog.error ("KWin refused to load the script ", this->m_pluginName);
-	std::remove (this->m_path.c_str ());
-	this->m_path.clear ();
-	return;
-    }
+	DBusMessage* reply = callKWin (this->m_connection, load, "loadScript");
+	dbus_int32_t scriptId = -1;
 
-    // the destructor unloads it even if run fails
-    this->m_registered = true;
-    Janitor::instance ().watch (this->m_pluginName, this->m_path);
+	if (reply != nullptr) {
+	    dbus_message_get_args (reply, nullptr, DBUS_TYPE_INT32, &scriptId, DBUS_TYPE_INVALID);
+	    dbus_message_unref (reply);
+	}
 
-    // KWin 6 puts the script at /Scripting/Script<id>, KWin 5 at /<id>
-    std::string error;
+	if (scriptId < 0) {
+	    sLog.error ("KWin refused to load the script ", name);
+	    break;
+	}
 
-    for (const std::string& object :
-	 { "/Scripting/Script" + std::to_string (scriptId), "/" + std::to_string (scriptId) }) {
-	DBusMessage* run = dbus_message_new_method_call ("org.kde.KWin", object.c_str (), "org.kde.kwin.Script", "run");
+	// the destructor unloads it even if run fails
+	this->m_loadedNames.push_back (name);
+	Janitor::instance ().watch (name, this->m_path);
 
-	if (DBusMessage* reply = callBlocking (this->m_connection, run, error); reply != nullptr) {
-	    dbus_message_unref (reply);
-	    this->m_running = true;
-	    return;
+	if (liveBefore.contains (scriptId)) {
+	    continue;
 	}
+
+	// KWin 6 puts the script at /Scripting/Script<id>, KWin 5 at /<id>
+	for (const std::string& object :
+	     { "/Scripting/Script" + std::to_string (scriptId), "/" + std::to_string (scriptId) }) {
+	    DBusMessage* run
+		= dbus_message_new_method_call ("org.kde.KWin", object.c_str (), "org.kde.kwin.Script", "run");
+
+	    if (DBusMessage* runReply = callBlocking (this->m_connection, run, error); runReply != nullptr) {
+		dbus_message_unref (runReply);
+		this->m_running = true;
+		return;
+	    }
+	}
+
+	sLog.error ("KWin script: run: ", error);
+	return;
     }
 
-    sLog.error ("KWin script: run: ", error);
+    if (this->m_loadedNames.empty ()) {
+	std::remove (this->m_path.c_str ());
+	this->m_path.clear ();
+    } else {
+	sLog.error ("KWin script ", this->m_pluginName, ": KWin gave it the id of a loaded script every time");
+    }
 }
 
 KWinScript::~KWinScript () {
-    if (this->m_registered && this->m_connection != nullptr) {
-	unloadScript (this->m_connection, this->m_pluginName);
-    }
+    for (const auto& name : this->m_loadedNames) {
+	if (this->m_connection != nullptr) {
+	    unloadScript (this->m_connection, name);
+	}
 
-    if (this->m_registered) {
-	Janitor::instance ().forget (this->m_pluginName);
+	Janitor::instance ().forget (name);
     }
 
     if (!this->m_path.empty ()) {

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

@@ -32,7 +32,7 @@ private:
     std::string m_pluginName;
     std::string m_path;
     int m_lock = -1;
-    bool m_registered = false;
+    std::vector<std::string> m_loadedNames;
     bool m_running = false;
 };
 }

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

@@ -236,14 +236,12 @@ void DBusMediaSource::parsePlaybackStatus (DBusMessageIter& variant, const char*
     const char* status = nullptr;
     dbus_message_iter_get_basic (&variant, &status);
     std::string statusStr = status ?: "";
-    PlaybackState newState = this->m_mediaInfo.playbackState;
+    PlaybackState newState = PlaybackState::Stopped;
 
     if (statusStr == "Playing") {
 	newState = PlaybackState::Playing;
     } else if (statusStr == "Paused") {
 	newState = PlaybackState::Paused;
-    } else {
-	newState = PlaybackState::Stopped;
     }
 
     if (newState != this->m_mediaInfo.playbackState) {

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

@@ -40,7 +40,7 @@ public:
     };
 
     struct Toplevel {
-	WaylandFullScreenDetector* detector;
+	WaylandFullScreenDetector* detector = nullptr;
 	zwlr_foreign_toplevel_handle_v1* handle = nullptr;
 	zcosmic_toplevel_handle_v1* cosmic = nullptr;
 	ext_foreign_toplevel_handle_v1* foreign = nullptr;

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

@@ -5,6 +5,7 @@
 
 #include <X11/Xatom.h>
 #include <X11/Xlib.h>
+#include <X11/Xutil.h>
 #include <X11/extensions/Xrandr.h>
 
 #include "WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.h"
@@ -76,7 +77,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)) {
+	if (client == None || client == ourWindow || this->isDesktopWindow (client) || this->isHidden (client)
+	    || !this->onCurrentDesktop (client)) {
 	    continue;
 	}
 
@@ -116,6 +118,86 @@ bool X11FullScreenDetector::applicationFocused (Window ourWindow) const {
     return XGetWindowAttributes (this->m_display, active, &attributes) && attributes.map_state == IsViewable;
 }
 
+bool X11FullScreenDetector::isHidden (Window client) const {
+    // minimized, or tabbed out: some window managers keep the frame of such a window mapped
+    const Atom stateAtom = XInternAtom (this->m_display, "_NET_WM_STATE", False);
+    const Atom hiddenAtom = XInternAtom (this->m_display, "_NET_WM_STATE_HIDDEN", False);
+    Atom type;
+    int format;
+    unsigned long count, remaining;
+    unsigned char* data = nullptr;
+    bool hidden = false;
+
+    if (XGetWindowProperty (
+	    this->m_display, client, stateAtom, 0, 32, False, XA_ATOM, &type, &format, &count, &remaining, &data
+	) == Success
+	&& data != nullptr && format == 32) {
+	const auto* atoms = reinterpret_cast<const Atom*> (data);
+	hidden = std::find (atoms, atoms + count, hiddenAtom) != atoms + count;
+    }
+
+    if (data != nullptr) {
+	XFree (data);
+    }
+
+    if (hidden) {
+	return true;
+    }
+
+    // ICCCM: WM_STATE 3 is iconic
+    const Atom wmState = XInternAtom (this->m_display, "WM_STATE", False);
+    data = nullptr;
+
+    if (XGetWindowProperty (
+	    this->m_display, client, wmState, 0, 2, False, wmState, &type, &format, &count, &remaining, &data
+	) == Success
+	&& data != nullptr && format == 32 && count >= 1) {
+	hidden = reinterpret_cast<const unsigned long*> (data)[0] == IconicState;
+    }
+
+    if (data != nullptr) {
+	XFree (data);
+    }
+
+    return hidden;
+}
+
+bool X11FullScreenDetector::onCurrentDesktop (Window client) const {
+    const auto cardinal = [this] (Window window, const char* name, unsigned long& value) {
+	const Atom atom = XInternAtom (this->m_display, name, False);
+	Atom type;
+	int format;
+	unsigned long count, remaining;
+	unsigned char* data = nullptr;
+	bool found = false;
+
+	if (XGetWindowProperty (
+		this->m_display, window, atom, 0, 1, False, XA_CARDINAL, &type, &format, &count, &remaining, &data
+	    ) == Success
+	    && data != nullptr && format == 32 && count == 1) {
+	    value = *reinterpret_cast<const unsigned long*> (data);
+	    found = true;
+	}
+
+	if (data != nullptr) {
+	    XFree (data);
+	}
+
+	return found;
+    };
+
+    unsigned long windowDesktop = 0, currentDesktop = 0;
+
+    // no EWMH desktops, or a sticky window (0xFFFFFFFF), counts everywhere
+    if (!cardinal (client, "_NET_WM_DESKTOP", windowDesktop)
+	|| !cardinal (this->m_root, "_NET_CURRENT_DESKTOP", currentDesktop)
+	|| (windowDesktop & 0xFFFFFFFF) == 0xFFFFFFFF) {
+	return true;
+    }
+
+    return windowDesktop == currentDesktop;
+}
+
 bool X11FullScreenDetector::hasFullscreenState (Window client) const {
     const Atom stateAtom = XInternAtom (this->m_display, "_NET_WM_STATE", False);
     const Atom fullscreenAtom = XInternAtom (this->m_display, "_NET_WM_STATE_FULLSCREEN", False);

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

@@ -25,6 +25,8 @@ namespace Detectors {
 	[[nodiscard]] bool isDesktopWindow (Window window) const;
 	[[nodiscard]] Window clientOf (Window window) const;
 	[[nodiscard]] bool hasFullscreenState (Window client) const;
+	[[nodiscard]] bool isHidden (Window client) const;
+	[[nodiscard]] bool onCurrentDesktop (Window client) const;
 	[[nodiscard]] bool coversScreen (Window client) const;
 	[[nodiscard]] bool applicationFocused (Window ourWindow) const;
 	void stop ();

+ 15 - 265
src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.cpp

@@ -1,6 +1,7 @@
 #include "GLFWWindowOutput.h"
 #include "GLFWOutputViewport.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "X11BackgroundWindow.h"
 #include <GL/glew.h>
 #include <GLFW/glfw3.h>
 
@@ -39,7 +40,8 @@ GLFWWindowOutput::GLFWWindowOutput (ApplicationContext& context, VideoDriver& dr
 	this->repositionWindow ();
 
 	if (background && driver.getX11Display () != nullptr) {
-	    this->createBackgroundWindow ();
+	    const auto& geometry = this->m_context.settings.render.window.geometry;
+	    this->m_background = std::make_unique<X11BackgroundWindow> (geometry.x, geometry.y, geometry.z, geometry.w);
 	}
     } else {
 	this->m_fullWidth = this->m_driver.getFramebufferSize ().x;
@@ -51,8 +53,6 @@ GLFWWindowOutput::GLFWWindowOutput (ApplicationContext& context, VideoDriver& dr
 }
 
 GLFWWindowOutput::~GLFWWindowOutput () {
-    this->destroyBackgroundWindow ();
-
     for (const auto& [name, viewport] : this->m_viewports) {
 	delete viewport;
     }
@@ -68,283 +68,33 @@ void GLFWWindowOutput::reset () {
     }
 }
 
-void GLFWWindowOutput::createBackgroundWindow () {
-    // A GL window can't sit below Cinnamon's desktop icons (it is composited over nemo-desktop whatever the
-    // stacking says), a plain X window can. So this one only gets the finished frames, like the root window does
-    Display* display = XOpenDisplay (nullptr);
-    this->m_display = display;
-
-    if (display == nullptr) {
-	sLog.error ("Cannot open the X display for the background window");
-	return;
-    }
-
-    const auto& geometry = this->m_context.settings.render.window.geometry;
-    const int screen = DefaultScreen (display);
-
-    XSetWindowAttributes attributes {};
-    attributes.background_pixel = BlackPixel (display, screen);
-    attributes.border_pixel = 0;
-
-    const Window window = XCreateWindow (
-	display, RootWindow (display, screen), geometry.x, geometry.y, geometry.z, geometry.w, 0, CopyFromParent,
-	InputOutput, CopyFromParent, CWBackPixel | CWBorderPixel, &attributes
-    );
-
-    const auto atom = [display] (const char* name) { return XInternAtom (display, name, False); };
-
-    const Atom type = atom ("_NET_WM_WINDOW_TYPE_DESKTOP");
-    XChangeProperty (
-	display, window, atom ("_NET_WM_WINDOW_TYPE"), XA_ATOM, 32, PropModeReplace,
-	reinterpret_cast<const unsigned char*> (&type), 1
-    );
-
-    const Atom states[]
-	= { atom ("_NET_WM_STATE_STICKY"), atom ("_NET_WM_STATE_SKIP_TASKBAR"), atom ("_NET_WM_STATE_SKIP_PAGER") };
-    XChangeProperty (
-	display, window, atom ("_NET_WM_STATE"), XA_ATOM, 32, PropModeReplace,
-	reinterpret_cast<const unsigned char*> (states), 3
-    );
-
-    const unsigned long allDesktops = 0xFFFFFFFF;
-    XChangeProperty (
-	display, window, atom ("_NET_WM_DESKTOP"), XA_CARDINAL, 32, PropModeReplace,
-	reinterpret_cast<const unsigned char*> (&allDesktops), 1
-    );
-
-    const unsigned long pid = getpid ();
-    XChangeProperty (
-	display, window, atom ("_NET_WM_PID"), XA_CARDINAL, 32, PropModeReplace,
-	reinterpret_cast<const unsigned char*> (&pid), 1
-    );
-
-    // never takes the focus
-    XWMHints wmHints {};
-    wmHints.flags = InputHint;
-    wmHints.input = False;
-    XSetWMHints (display, window, &wmHints);
-
-    // undecorated
-    const unsigned long motif[] = { 2, 0, 0, 0, 0 };
-    XChangeProperty (
-	display, window, atom ("_MOTIF_WM_HINTS"), atom ("_MOTIF_WM_HINTS"), 32, PropModeReplace,
-	reinterpret_cast<const unsigned char*> (motif), 5
-    );
-
-    // like the other X windows of ours, the clicks go to what is below
-    XShapeCombineRectangles (display, window, ShapeInput, 0, 0, nullptr, 0, ShapeSet, Unsorted);
-
-    char name[] = "linux-wallpaperengine";
-    XClassHint classHint { name, name };
-    XSetClassHint (display, window, &classHint);
-    XStoreName (display, window, "wallpaperengine");
-
-    this->m_background = window;
-    this->m_gc = XCreateGC (display, window, 0, nullptr);
-    this->m_imageSize = this->m_fullWidth * this->m_fullHeight * 4;
-    // XDestroyImage () frees this with free ()
-    this->m_imageData = static_cast<char*> (malloc (this->m_imageSize));
-    this->m_image = XCreateImage (
-	display, CopyFromParent, 24, ZPixmap, 0, this->m_imageData, this->m_fullWidth, this->m_fullHeight, 32, 0
-    );
-
-    XMapWindow (display, window);
-    XFlush (display);
-
-    sLog.out (
-	"Background window 0x", std::hex, window, std::dec, " ", geometry.z, "x", geometry.w, "+", geometry.x, "+",
-	geometry.y, ", screen depth ", DefaultDepth (display, screen), ", compositor ",
-	XGetSelectionOwner (display, atom ("_NET_WM_CM_S0")) != None ? "running" : "not running"
-    );
-}
-
-void GLFWWindowOutput::destroyBackgroundWindow () {
-    auto* display = static_cast<Display*> (this->m_display);
-
-    if (display == nullptr) {
-	return;
-    }
-
-    if (this->m_image != nullptr) {
-	// frees m_imageData as well
-	XDestroyImage (static_cast<XImage*> (this->m_image));
-	this->m_image = nullptr;
-	this->m_imageData = nullptr;
-    }
-
-    if (this->m_nudge != 0) {
-	XDestroyWindow (display, this->m_nudge);
-	this->m_nudge = 0;
-    }
-
-    if (this->m_gc != nullptr) {
-	XFreeGC (display, static_cast<GC> (this->m_gc));
-	this->m_gc = nullptr;
-    }
-
-    if (this->m_background != 0) {
-	XDestroyWindow (display, this->m_background);
-	this->m_background = 0;
-    }
-
-    XCloseDisplay (display);
-    this->m_display = nullptr;
-}
-
-bool GLFWWindowOutput::desktopWindowBelowUs () const {
-    auto* display = static_cast<Display*> (this->m_display);
-    const Atom listAtom = XInternAtom (display, "_NET_CLIENT_LIST_STACKING", False);
-    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 = 0, remaining;
-    unsigned char* data = nullptr;
-    bool below = false;
-
-    if (XGetWindowProperty (
-	    display, DefaultRootWindow (display), listAtom, 0, 4096, False, XA_WINDOW, &type, &format, &count,
-	    &remaining, &data
-	) != Success
-	|| data == nullptr || format != 32) {
-	return false;
-    }
-
-    // bottom to top
-    const auto* windows = reinterpret_cast<const Window*> (data);
-    unsigned long ours = count;
+bool GLFWWindowOutput::renderVFlip () const { return !this->hasBackground (); }
 
-    for (unsigned long i = 0; i < count; i++) {
-	if (windows[i] == this->m_background) {
-	    ours = i;
-	}
-    }
-
-    for (unsigned long i = 0; i < ours && !below; i++) {
-	Atom windowType;
-	int windowFormat;
-	unsigned long typeCount, typeRemaining;
-	unsigned char* typeData = nullptr;
-
-	if (XGetWindowProperty (
-		display, windows[i], typeAtom, 0, 16, False, XA_ATOM, &windowType, &windowFormat, &typeCount,
-		&typeRemaining, &typeData
-	    ) == Success
-	    && typeData != nullptr && windowFormat == 32) {
-	    const auto* atoms = reinterpret_cast<const Atom*> (typeData);
-	    below = std::find (atoms, atoms + typeCount, desktopAtom) != atoms + typeCount;
-	}
-
-	if (typeData != nullptr) {
-	    XFree (typeData);
-	}
-    }
-
-    XFree (data);
-
-    return below;
-}
-
-void GLFWWindowOutput::keepBackgroundWindowLow () const {
-    auto* display = static_cast<Display*> (this->m_display);
-    const uint32_t tick = this->m_updates++;
-
-    if (this->m_nudge != 0 && tick >= this->m_nudgeUntil) {
-	XDestroyWindow (display, this->m_nudge);
-	this->m_nudge = 0;
-    }
-
-    if (tick % 60 != 5 || this->m_nudge != 0 || !this->desktopWindowBelowUs ()) {
-	return;
-    }
-
-    // Desktop windows stack by age and nemo-desktop is one too, so ours goes below it. Muffin keeps those in a group
-    // of their own and only syncs it to the new order when a normal window changes the stacking as well, which on an
-    // empty desktop never happens. A normal window, invisible and gone again a moment later, makes it happen.
-    XLowerWindow (display, this->m_background);
-
-    XSetWindowAttributes attributes {};
-    attributes.background_pixel = BlackPixel (display, DefaultScreen (display));
-    const Window nudge = XCreateWindow (
-	display, DefaultRootWindow (display), 0, 0, 1, 1, 0, CopyFromParent, InputOutput, CopyFromParent, CWBackPixel,
-	&attributes
-    );
+bool GLFWWindowOutput::renderMultiple () const { return false; }
 
-    const auto atom = [display] (const char* name) { return XInternAtom (display, name, False); };
-    const unsigned long transparent = 0;
-    XChangeProperty (
-	display, nudge, atom ("_NET_WM_WINDOW_OPACITY"), XA_CARDINAL, 32, PropModeReplace,
-	reinterpret_cast<const unsigned char*> (&transparent), 1
-    );
-    const Atom states[] = { atom ("_NET_WM_STATE_SKIP_TASKBAR"), atom ("_NET_WM_STATE_SKIP_PAGER") };
-    XChangeProperty (
-	display, nudge, atom ("_NET_WM_STATE"), XA_ATOM, 32, PropModeReplace,
-	reinterpret_cast<const unsigned char*> (states), 2
-    );
-    XWMHints wmHints {};
-    wmHints.flags = InputHint;
-    wmHints.input = False;
-    XSetWMHints (display, nudge, &wmHints);
-    XShapeCombineRectangles (display, nudge, ShapeInput, 0, 0, nullptr, 0, ShapeSet, Unsorted);
+bool GLFWWindowOutput::haveImageBuffer () const { return this->hasBackground (); }
 
-    XMapWindow (display, nudge);
-    this->m_nudge = nudge;
-    this->m_nudgeUntil = tick + 6;
+void* GLFWWindowOutput::getImageBuffer () const {
+    return this->hasBackground () ? this->m_background->data () : nullptr;
 }
 
-bool GLFWWindowOutput::frameIsBlack () const {
-    const auto* pixels = reinterpret_cast<const uint32_t*> (this->m_imageData);
-    const size_t count = this->m_imageSize / 4;
-
-    // every 97th pixel is plenty, a wallpaper that is black there is black
-    for (size_t i = 0; i < count; i += 97) {
-	if ((pixels[i] & 0x00FFFFFF) != 0) {
-	    return false;
-	}
-    }
-
-    return true;
+uint32_t GLFWWindowOutput::getImageBufferSize () const {
+    return this->hasBackground () ? this->m_background->size () : 0;
 }
 
-bool GLFWWindowOutput::renderVFlip () const { return this->m_image == nullptr; }
-
-bool GLFWWindowOutput::renderMultiple () const { return false; }
-
-bool GLFWWindowOutput::haveImageBuffer () const { return this->m_image != nullptr; }
-
-void* GLFWWindowOutput::getImageBuffer () const { return this->m_imageData; }
-
-uint32_t GLFWWindowOutput::getImageBufferSize () const { return this->m_imageSize; }
+bool GLFWWindowOutput::hasBackground () const { return this->m_background != nullptr && this->m_background->valid (); }
 
 void GLFWWindowOutput::updateRender () const {
     // re-read every frame so window resizes re-stretch the scene instead of cropping it, the image buffer of a
     // background window has a fixed size
-    if (this->m_image == nullptr) {
+    if (!this->hasBackground ()) {
 	this->m_fullWidth = this->m_driver.getFramebufferSize ().x;
 	this->m_fullHeight = this->m_driver.getFramebufferSize ().y;
     }
 
     this->m_viewports["default"]->viewport = { 0, 0, this->m_fullWidth, this->m_fullHeight };
 
-    if (this->m_image == nullptr) {
-	return;
-    }
-
-    auto* display = static_cast<Display*> (this->m_display);
-
-    if (this->m_updates == 90 && this->frameIsBlack ()) {
-	sLog.error (
-	    "The background window got 90 frames and every pixel is black. Either the wallpaper is black or the frames "
-	    "never reach the window; the line above names the window to look for with xwininfo"
-	);
+    if (this->hasBackground ()) {
+	this->m_background->present ();
     }
-
-    XPutImage (
-	display, this->m_background, static_cast<GC> (this->m_gc), static_cast<XImage*> (this->m_image), 0, 0, 0, 0,
-	this->m_fullWidth, this->m_fullHeight
-    );
-
-    this->keepBackgroundWindowLow ();
-
-    XFlush (display);
-}
+}

+ 6 - 17
src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.h

@@ -1,7 +1,10 @@
 #pragma once
 
+#include <memory>
+
 #include "Output.h"
 #include "WallpaperEngine/Render/Drivers/VideoDriver.h"
+#include "X11BackgroundWindow.h"
 
 namespace WallpaperEngine::Render::Drivers::Output {
 class GLFWWindowOutput final : public Output {
@@ -19,22 +22,8 @@ public:
 
 private:
     void repositionWindow () const;
-    void createBackgroundWindow ();
-    void destroyBackgroundWindow ();
-    void keepBackgroundWindowLow () const;
-    bool desktopWindowBelowUs () const;
-    bool frameIsBlack () const;
+    [[nodiscard]] bool hasBackground () const;
 
-    // --window-background: the frames go into a plain X window of our own, see createBackgroundWindow
-    // Xlib types are kept out of this header, its macros clash with the rest of the engine
-    void* m_display = nullptr;
-    unsigned long m_background = 0;
-    void* m_gc = nullptr;
-    void* m_image = nullptr;
-    char* m_imageData = nullptr;
-    uint32_t m_imageSize = 0;
-    mutable uint32_t m_updates = 0;
-    mutable unsigned long m_nudge = 0;
-    mutable uint32_t m_nudgeUntil = 0;
+    std::unique_ptr<X11BackgroundWindow> m_background;
 };
-}
+}

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

@@ -500,9 +500,9 @@ void WaylandOutputViewport::createEGLSurface () {
     static const auto XCURSORSIZE = [] {
 	const char* text = getenv ("XCURSOR_SIZE");
 	char* end = nullptr;
-	const long size = text != nullptr ? std::strtol (text, &end, 10) : 0;
+	const long parsed = text != nullptr ? std::strtol (text, &end, 10) : 0;
 
-	return text != nullptr && end != text && size > 0 && size <= 1024 ? static_cast<int> (size) : 24;
+	return text != nullptr && end != text && parsed > 0 && parsed <= 1024 ? static_cast<int> (parsed) : 24;
     }();
     cursorTheme
 	= wl_cursor_theme_load (getenv ("XCURSOR_THEME"), XCURSORSIZE * scale, m_driver->getWaylandContext ()->shm);

+ 269 - 0
src/WallpaperEngine/Render/Drivers/Output/X11BackgroundWindow.cpp

@@ -0,0 +1,269 @@
+#include "X11BackgroundWindow.h"
+#include "WallpaperEngine/Logging/Log.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;
+
+X11BackgroundWindow::X11BackgroundWindow (int x, int y, int width, int height) : m_width (width), m_height (height) {
+    // A GL window can't sit below Cinnamon's desktop icons (it is composited over nemo-desktop whatever the
+    // stacking says), a plain X window can. So this one only gets the finished frames, like the root window does
+    Display* display = XOpenDisplay (nullptr);
+    this->m_display = display;
+
+    if (display == nullptr) {
+	sLog.error ("Cannot open the X display for the background window");
+	return;
+    }
+
+    const int screen = DefaultScreen (display);
+
+    XSetWindowAttributes attributes {};
+    attributes.background_pixel = BlackPixel (display, screen);
+    attributes.border_pixel = 0;
+
+    const Window window = XCreateWindow (
+	display, RootWindow (display, screen), x, y, width, height, 0, CopyFromParent, InputOutput, CopyFromParent,
+	CWBackPixel | CWBorderPixel, &attributes
+    );
+
+    const auto atom = [display] (const char* name) { return XInternAtom (display, name, False); };
+
+    const Atom type = atom ("_NET_WM_WINDOW_TYPE_DESKTOP");
+    XChangeProperty (
+	display, window, atom ("_NET_WM_WINDOW_TYPE"), XA_ATOM, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (&type), 1
+    );
+
+    const Atom states[]
+	= { atom ("_NET_WM_STATE_STICKY"), atom ("_NET_WM_STATE_SKIP_TASKBAR"), atom ("_NET_WM_STATE_SKIP_PAGER") };
+    XChangeProperty (
+	display, window, atom ("_NET_WM_STATE"), XA_ATOM, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (states), 3
+    );
+
+    const unsigned long allDesktops = 0xFFFFFFFF;
+    XChangeProperty (
+	display, window, atom ("_NET_WM_DESKTOP"), XA_CARDINAL, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (&allDesktops), 1
+    );
+
+    const unsigned long pid = getpid ();
+    XChangeProperty (
+	display, window, atom ("_NET_WM_PID"), XA_CARDINAL, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (&pid), 1
+    );
+
+    XWMHints wmHints {};
+    wmHints.flags = InputHint;
+    wmHints.input = False;
+    XSetWMHints (display, window, &wmHints);
+
+    const unsigned long motif[] = { 2, 0, 0, 0, 0 };
+    XChangeProperty (
+	display, window, atom ("_MOTIF_WM_HINTS"), atom ("_MOTIF_WM_HINTS"), 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (motif), 5
+    );
+
+    XShapeCombineRectangles (display, window, ShapeInput, 0, 0, nullptr, 0, ShapeSet, Unsorted);
+
+    char name[] = "linux-wallpaperengine";
+    XClassHint classHint { name, name };
+    XSetClassHint (display, window, &classHint);
+    XStoreName (display, window, "wallpaperengine");
+
+    this->m_window = window;
+    this->m_gc = XCreateGC (display, window, 0, nullptr);
+    this->m_imageSize = static_cast<uint32_t> (width) * height * 4;
+    // XDestroyImage () frees this with free ()
+    this->m_imageData = static_cast<char*> (malloc (this->m_imageSize));
+    this->m_image = XCreateImage (display, CopyFromParent, 24, ZPixmap, 0, this->m_imageData, width, height, 32, 0);
+
+    XMapWindow (display, window);
+    XFlush (display);
+
+    sLog.out (
+	"Background window 0x", std::hex, window, std::dec, " ", width, "x", height, "+", x, "+", y, ", screen depth ",
+	DefaultDepth (display, screen), ", compositor ",
+	XGetSelectionOwner (display, atom ("_NET_WM_CM_S0")) != None ? "running" : "not running"
+    );
+}
+
+X11BackgroundWindow::~X11BackgroundWindow () {
+    auto* display = static_cast<Display*> (this->m_display);
+
+    if (display == nullptr) {
+	return;
+    }
+
+    if (this->m_image != nullptr) {
+	// frees m_imageData as well
+	XDestroyImage (static_cast<XImage*> (this->m_image));
+	this->m_image = nullptr;
+	this->m_imageData = nullptr;
+    }
+
+    if (this->m_nudge != 0) {
+	XDestroyWindow (display, this->m_nudge);
+	this->m_nudge = 0;
+    }
+
+    if (this->m_gc != nullptr) {
+	XFreeGC (display, static_cast<GC> (this->m_gc));
+	this->m_gc = nullptr;
+    }
+
+    if (this->m_window != 0) {
+	XDestroyWindow (display, this->m_window);
+	this->m_window = 0;
+    }
+
+    XCloseDisplay (display);
+    this->m_display = nullptr;
+}
+
+bool X11BackgroundWindow::desktopWindowBelowUs () const {
+    auto* display = static_cast<Display*> (this->m_display);
+    const Atom listAtom = XInternAtom (display, "_NET_CLIENT_LIST_STACKING", False);
+    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 = 0, remaining;
+    unsigned char* data = nullptr;
+    bool below = false;
+
+    if (XGetWindowProperty (
+	    display, DefaultRootWindow (display), listAtom, 0, 4096, False, XA_WINDOW, &type, &format, &count,
+	    &remaining, &data
+	) != Success
+	|| data == nullptr || format != 32) {
+	return false;
+    }
+
+    // bottom to top
+    const auto* windows = reinterpret_cast<const Window*> (data);
+    unsigned long ours = count;
+
+    for (unsigned long i = 0; i < count; i++) {
+	if (windows[i] == this->m_window) {
+	    ours = i;
+	}
+    }
+
+    for (unsigned long i = 0; i < ours && !below; i++) {
+	Atom windowType;
+	int windowFormat;
+	unsigned long typeCount, typeRemaining;
+	unsigned char* typeData = nullptr;
+
+	if (XGetWindowProperty (
+		display, windows[i], typeAtom, 0, 16, False, XA_ATOM, &windowType, &windowFormat, &typeCount,
+		&typeRemaining, &typeData
+	    ) == Success
+	    && typeData != nullptr && windowFormat == 32) {
+	    const auto* atoms = reinterpret_cast<const Atom*> (typeData);
+	    below = std::find (atoms, atoms + typeCount, desktopAtom) != atoms + typeCount;
+	}
+
+	if (typeData != nullptr) {
+	    XFree (typeData);
+	}
+    }
+
+    XFree (data);
+
+    return below;
+}
+
+void X11BackgroundWindow::keepLow () {
+    auto* display = static_cast<Display*> (this->m_display);
+    const uint32_t tick = this->m_updates++;
+
+    if (this->m_nudge != 0 && tick >= this->m_nudgeUntil) {
+	XDestroyWindow (display, this->m_nudge);
+	this->m_nudge = 0;
+    }
+
+    if (tick % 60 != 5 || this->m_nudge != 0 || !this->desktopWindowBelowUs ()) {
+	return;
+    }
+
+    // Desktop windows stack by age and nemo-desktop is one too, so ours goes below it. Muffin keeps those in a group
+    // of their own and only syncs it to the new order when a normal window changes the stacking as well, which on an
+    // empty desktop never happens. A normal window, invisible and gone again a moment later, makes it happen.
+    XLowerWindow (display, this->m_window);
+
+    XSetWindowAttributes attributes {};
+    attributes.background_pixel = BlackPixel (display, DefaultScreen (display));
+    const Window nudge = XCreateWindow (
+	display, DefaultRootWindow (display), 0, 0, 1, 1, 0, CopyFromParent, InputOutput, CopyFromParent, CWBackPixel,
+	&attributes
+    );
+
+    const auto atom = [display] (const char* name) { return XInternAtom (display, name, False); };
+    const unsigned long transparent = 0;
+    XChangeProperty (
+	display, nudge, atom ("_NET_WM_WINDOW_OPACITY"), XA_CARDINAL, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (&transparent), 1
+    );
+    const Atom states[] = { atom ("_NET_WM_STATE_SKIP_TASKBAR"), atom ("_NET_WM_STATE_SKIP_PAGER") };
+    XChangeProperty (
+	display, nudge, atom ("_NET_WM_STATE"), XA_ATOM, 32, PropModeReplace,
+	reinterpret_cast<const unsigned char*> (states), 2
+    );
+    XWMHints wmHints {};
+    wmHints.flags = InputHint;
+    wmHints.input = False;
+    XSetWMHints (display, nudge, &wmHints);
+    XShapeCombineRectangles (display, nudge, ShapeInput, 0, 0, nullptr, 0, ShapeSet, Unsorted);
+
+    XMapWindow (display, nudge);
+    this->m_nudge = nudge;
+    this->m_nudgeUntil = tick + 6;
+}
+
+bool X11BackgroundWindow::frameIsBlack () const {
+    const auto* pixels = reinterpret_cast<const uint32_t*> (this->m_imageData);
+    const size_t count = this->m_imageSize / 4;
+
+    // every 97th pixel is plenty, a wallpaper that is black there is black
+    for (size_t i = 0; i < count; i += 97) {
+	if ((pixels[i] & 0x00FFFFFF) != 0) {
+	    return false;
+	}
+    }
+
+    return true;
+}
+
+void X11BackgroundWindow::present () {
+    auto* display = static_cast<Display*> (this->m_display);
+
+    if (display == nullptr || this->m_image == nullptr) {
+	return;
+    }
+
+    if (this->m_updates == 90 && this->frameIsBlack ()) {
+	sLog.error (
+	    "The background window got 90 frames and every pixel is black. Either the wallpaper is black or the frames "
+	    "never reach the window; the line above names the window to look for with xwininfo"
+	);
+    }
+
+    XPutImage (
+	display, this->m_window, static_cast<GC> (this->m_gc), static_cast<XImage*> (this->m_image), 0, 0, 0, 0,
+	this->m_width, this->m_height
+    );
+
+    this->keepLow ();
+
+    XFlush (display);
+}

+ 38 - 0
src/WallpaperEngine/Render/Drivers/Output/X11BackgroundWindow.h

@@ -0,0 +1,38 @@
+#pragma once
+
+#include <cstdint>
+
+namespace WallpaperEngine::Render::Drivers::Output {
+// Xlib types stay out of this header, its macros clash with the rest of the engine
+class X11BackgroundWindow {
+public:
+    X11BackgroundWindow (int x, int y, int width, int height);
+    ~X11BackgroundWindow ();
+
+    X11BackgroundWindow (const X11BackgroundWindow&) = delete;
+    X11BackgroundWindow& operator= (const X11BackgroundWindow&) = delete;
+
+    [[nodiscard]] bool valid () const { return this->m_image != nullptr; }
+    [[nodiscard]] char* data () const { return this->m_imageData; }
+    [[nodiscard]] uint32_t size () const { return this->m_imageSize; }
+
+    void present ();
+
+private:
+    void keepLow ();
+    [[nodiscard]] bool desktopWindowBelowUs () const;
+    [[nodiscard]] bool frameIsBlack () const;
+
+    void* m_display = nullptr;
+    unsigned long m_window = 0;
+    void* m_gc = nullptr;
+    void* m_image = nullptr;
+    char* m_imageData = nullptr;
+    uint32_t m_imageSize = 0;
+    int m_width;
+    int m_height;
+    uint32_t m_updates = 0;
+    unsigned long m_nudge = 0;
+    uint32_t m_nudgeUntil = 0;
+};
+}

+ 83 - 9
src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp

@@ -4,6 +4,8 @@
 
 #include <algorithm>
 #include <cstdlib>
+#include <memory>
+#include <string_view>
 #include <unistd.h>
 
 #include <X11/Xatom.h>
@@ -65,6 +67,8 @@ void X11Output::free () {
     this->m_screens.clear ();
     this->m_viewports.clear ();
 
+    this->m_background.reset ();
+
     // XDestroyImage() frees m_imageData itself
     if (this->m_desktopWindow != None) {
 	XDestroyWindow (this->m_display, this->m_desktopWindow);
@@ -186,7 +190,51 @@ void X11Output::validateOutputs () const {
     }
 }
 
+bool X11Output::desktopHidesRootWindow () {
+    if (const char* forced = std::getenv ("LWE_X11_BACKGROUND_WINDOW"); forced != nullptr && *forced != '\0') {
+	return forced[0] != '0';
+    }
+
+    const char* desktops = std::getenv ("XDG_CURRENT_DESKTOP");
+
+    if (desktops == nullptr) {
+	return false;
+    }
+
+    std::string_view rest (desktops);
+
+    while (!rest.empty ()) {
+	const auto colon = rest.find (':');
+	const auto name = rest.substr (0, colon);
+
+	if (name == "GNOME" || name == "Pantheon" || name == "X-Cinnamon") {
+	    return true;
+	}
+
+	if (colon == std::string_view::npos) {
+	    break;
+	}
+
+	rest.remove_prefix (colon + 1);
+    }
+
+    return false;
+}
+
 void X11Output::initX11Background () {
+    if (desktopHidesRootWindow ()) {
+	auto window = std::make_unique<X11BackgroundWindow> (0, 0, this->m_fullWidth, this->m_fullHeight);
+
+	if (window->valid ()) {
+	    sLog.out ("The desktop paints over the root window, drawing into a background window of our own");
+	    this->m_imageData = window->data ();
+	    this->m_imageSize = window->size ();
+	    this->m_background = std::move (window);
+	    this->m_driver.resizeWindow ({ this->m_fullWidth, this->m_fullHeight });
+	    return;
+	}
+    }
+
     this->m_pixmap = XCreatePixmap (this->m_display, this->m_root, this->m_fullWidth, this->m_fullHeight, 24);
     this->m_gc = XCreateGC (this->m_display, this->m_pixmap, 0, nullptr);
     XFillRectangle (this->m_display, this->m_pixmap, this->m_gc, 0, 0, this->m_fullWidth, this->m_fullHeight);
@@ -201,6 +249,11 @@ void X11Output::initX11Background () {
 }
 
 void X11Output::updateRender () const {
+    if (this->m_background != nullptr) {
+	this->m_background->present ();
+	return;
+    }
+
     XPutImage (
 	this->m_display, this->m_pixmap, this->m_gc, this->m_image, 0, 0, 0, 0, this->m_fullWidth, this->m_fullHeight
     );
@@ -288,7 +341,9 @@ bool X11Output::isDesktopType (Window window) const {
     return desktop;
 }
 
-Window X11Output::findCoveringDesktopWindow (const std::vector<Window>& stacking) const {
+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)) {
 	    continue;
@@ -313,11 +368,11 @@ Window X11Output::findCoveringDesktopWindow (const std::vector<Window>& stacking
 	});
 
 	if (covers) {
-	    return window;
+	    found.push_back (window);
 	}
     }
 
-    return None;
+    return found;
 }
 
 void X11Output::createDesktopWindow () const {
@@ -411,9 +466,9 @@ void X11Output::updateDesktopWindow () const {
 
     this->m_nextDesktopCheck = now + std::chrono::seconds (2);
 
-    const Window covering = this->findCoveringDesktopWindow (this->stackingOrder ());
+    const auto covering = this->findCoveringDesktopWindows (this->stackingOrder ());
 
-    if (covering == None) {
+    if (covering.empty ()) {
 	if (this->m_desktopWindowMapped) {
 	    XUnmapWindow (this->m_display, this->m_desktopWindow);
 	    this->m_desktopWindowMapped = false;
@@ -434,15 +489,34 @@ void X11Output::updateDesktopWindow () const {
 	sLog.out ("A desktop window covers the root window, drawing into a desktop window of our own above it");
     }
 
-    const Window theirs = this->topLevelOf (covering);
+    std::vector<Window> theirTopLevels;
+    theirTopLevels.reserve (covering.size ());
+
+    for (const Window window : covering) {
+	theirTopLevels.push_back (this->topLevelOf (window));
+    }
+
     Window rootReturn, parent, *children = nullptr;
     unsigned int count = 0;
+    Window theirs = theirTopLevels.front ();
     bool inPlace = false;
 
     if (XQueryTree (this->m_display, this->m_root, &rootReturn, &parent, &children, &count)) {
+	// one desktop window per monitor (xfdesktop): ours goes above the topmost, or the others hide it on their
+	// monitor
 	const Window* end = children + count;
-	const Window* their = std::find (children, children + count, theirs);
-	inPlace = their != end && their + 1 != end && *(their + 1) == this->m_desktopWindow;
+	const Window* topmost = children;
+
+	for (const Window top : theirTopLevels) {
+	    const Window* position = std::find (static_cast<const Window*> (children), end, top);
+
+	    if (position != end && position >= topmost) {
+		topmost = position;
+		theirs = top;
+	    }
+	}
+
+	inPlace = topmost != end && topmost + 1 != end && *(topmost + 1) == this->m_desktopWindow;
     }
 
     if (children != nullptr) {
@@ -455,4 +529,4 @@ void X11Output::updateDesktopWindow () const {
 	changes.stack_mode = Above;
 	XConfigureWindow (this->m_display, this->m_desktopWindow, CWSibling | CWStackMode, &changes);
     }
-}
+}

+ 6 - 3
src/WallpaperEngine/Render/Drivers/Output/X11Output.h

@@ -3,6 +3,7 @@
 #include <chrono>
 #include <glm/vec4.hpp>
 #include <map>
+#include <memory>
 #include <string>
 #include <vector>
 
@@ -11,6 +12,7 @@
 
 #include "Output.h"
 #include "WallpaperEngine/Render/Drivers/VideoDriver.h"
+#include "X11BackgroundWindow.h"
 
 namespace WallpaperEngine::Render::Drivers::Output {
 class X11Output final : public Output {
@@ -34,10 +36,10 @@ private:
     void initX11Background ();
     void free ();
 
-    // XFCE, MATE and LXQt cover the root with an opaque desktop window; frames then go into our own window right above
-    // it, input passing through. Translucent ones (nemo-desktop) are left alone
+    [[nodiscard]] static bool desktopHidesRootWindow ();
+
     void updateDesktopWindow () const;
-    [[nodiscard]] Window findCoveringDesktopWindow (const std::vector<Window>& stacking) const;
+    [[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;
@@ -52,6 +54,7 @@ private:
     XImage* m_image = nullptr;
     std::vector<OutputViewport*> m_screens = {};
 
+    std::unique_ptr<X11BackgroundWindow> m_background;
     mutable Window m_desktopWindow = None;
     mutable bool m_desktopWindowMapped = false;
     mutable std::chrono::steady_clock::time_point m_nextDesktopCheck = {};

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

@@ -255,7 +255,7 @@ GifAnimation::Result GifAnimation::loadNext (const uint8_t* twoBack, const bool
 	int dispose = (m_eflags >> 2) & 7;
 	const size_t count = static_cast<size_t> (m_width) * m_height;
 
-	if ((m_eflags & 0x1C) == 12 && twoBack == nullptr) {
+	if (dispose == 3 && twoBack == nullptr) {
 	    dispose = 2;
 	}
 

+ 8 - 4
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -12,6 +12,7 @@
 #include "WallpaperEngine/Render/WallpaperState.h"
 
 #include "CScene.h"
+#include "MouseMapping.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
@@ -1955,9 +1956,11 @@ void CScene::dispatchCursorEvents () {
     const bool dragging = down && !this->m_cursorPressed.empty ();
     // hitBox only while pressed or the button changed
     const bool wantsHitBox = !this->m_cursorPressed.empty () || pressed || released;
-    // scene buffer clip space, what the objects' matrices project to; the buffer is stored upside down, clip y grows
-    // towards the bottom of the screen like the cursor's
-    const glm::vec2 ndc = this->m_cursorScreen * 2.0f - 1.0f;
+    // scene buffer clip space, what the objects' matrices project to (clip y grows towards the bottom of the screen);
+    // m_cursorScreen.y is mirrored on flipped outputs, the hover zones of 3599498791 picked the opposite weekday on
+    // Wayland
+    const glm::vec2 ndc { this->m_cursorScreen.x * 2.0f - 1.0f,
+			  cursorClipY (this->m_cursorScreen.y, this->getState ().isVFlipped ()) };
 
     // topmost first, like WE. Hidden objects are hit tested and get events too, they just can't stop propagation.
     // Images and text (object types 1 and 4) test their quad, models (type 5) their bounds
@@ -2258,7 +2261,8 @@ glm::vec3 CScene::unprojectCursor () const {
     // WE unprojects the cursor (x, 1 - y) through the view and projection on top of the renderer's stacks, with glm's
     // unProject (depth 0.5 -> NDC 0) for scripts (sub_14018E070 -> sub_14019DF90) and NDC depth 0 for particle control
     // points (sub_14022E3E0). Its projections are Direct3D ones, so NDC depth 0 is the near plane
-    const glm::vec2 ndc { this->m_cursorScreen.x * 2.0f - 1.0f, (1.0f - this->m_cursorScreen.y) * 2.0f - 1.0f };
+    const glm::vec2 ndc { this->m_cursorScreen.x * 2.0f - 1.0f,
+			  cursorClipY (this->m_cursorScreen.y, this->getState ().isVFlipped ()) };
     const auto& camera = this->getCamera ();
 
     if (camera.isPerspective ()) {

+ 10 - 0
src/WallpaperEngine/Render/Wallpapers/MouseMapping.h

@@ -0,0 +1,10 @@
+#pragma once
+
+namespace WallpaperEngine::Render::Wallpapers {
+// the cursor's y in the scene buffer's clip space, which grows towards the bottom of the screen like WE's client y.
+// cursorScreenY is the buffer coordinate the output samples under the pointer: top down on an unflipped output and
+// bottom up on a flipped one, the clip y is the same picture either way
+inline float cursorClipY (float cursorScreenY, bool vFlipped) {
+    return vFlipped ? 1.0f - cursorScreenY * 2.0f : cursorScreenY * 2.0f - 1.0f;
+}
+}

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

@@ -39,6 +39,7 @@ struct RuntimeDir {
 	sockaddr_un addr {};
 	addr.sun_family = AF_UNIX;
 	std::strncpy (addr.sun_path, socketPath.c_str (), sizeof (addr.sun_path) - 1);
+	REQUIRE (fd >= 0);
 	REQUIRE (bind (fd, reinterpret_cast<sockaddr*> (&addr), sizeof (addr)) == 0);
 	REQUIRE (listen (fd, 4) == 0);
 

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

@@ -54,6 +54,7 @@ class CoverServer {
 public:
     CoverServer () {
 	this->m_socket = socket (AF_INET, SOCK_STREAM, 0);
+	REQUIRE (this->m_socket >= 0);
 
 	sockaddr_in address {};
 	address.sin_family = AF_INET;

+ 15 - 0
src/WallpaperEngine/Testing/Cases/MouseCoordinates.cpp

@@ -3,6 +3,8 @@
 #include <cmath>
 #include <glm/glm.hpp>
 
+#include "WallpaperEngine/Render/Wallpapers/MouseMapping.h"
+
 // GLFW y down, GL y up
 TEST_CASE ("GLFW to OpenGL coordinate conversion") {
     const int framebufferHeight = 1080;
@@ -113,3 +115,16 @@ TEST_CASE ("Coordinate conversion with different viewport sizes") {
 	CHECK (openglY == 600.0);
     }
 }
+
+TEST_CASE ("Cursor clip y is the same picture on flipped and unflipped outputs") {
+    using WallpaperEngine::Render::Wallpapers::cursorClipY;
+
+    // pointer at the top of the screen: an unflipped output samples buffer row 0 there, a flipped one row 1
+    CHECK (cursorClipY (0.0f, false) == -1.0f);
+    CHECK (cursorClipY (1.0f, true) == -1.0f);
+
+    CHECK (cursorClipY (1.0f, false) == 1.0f);
+    CHECK (cursorClipY (0.0f, true) == 1.0f);
+
+    CHECK (cursorClipY (0.25f, false) == cursorClipY (0.75f, true));
+}

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

@@ -496,6 +496,18 @@ void GLPlayer::render () const {
 	this->m_needsRedraw = false;
     }
 
+    // scene passes leave their own mask behind, and a frame drawn without alpha leaves the texture transparent
+    struct FullColorMask {
+	GLboolean saved[4] {};
+
+	FullColorMask () {
+	    glGetBooleanv (GL_COLOR_WRITEMASK, this->saved);
+	    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+	}
+
+	~FullColorMask () { glColorMask (this->saved[0], this->saved[1], this->saved[2], this->saved[3]); }
+    } colorMask;
+
     glViewport (0, 0, this->m_width, this->m_height);
 
     mpv_opengl_fbo fbo { static_cast<int> (this->m_fbo), static_cast<int> (this->m_width),

+ 22 - 0
tools/check_hotswap_video.sh

@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Regression check for the grey-clouds bug: hotswapping from a scene that leaves glColorMask's alpha off (3471294034, cursor
+# particles) onto a video layer wallpaper (3818199837) left the video transparent. Renders the swap and a fresh start of the
+# target headlessly on the GPU (headless_render.sh) and compares the two pictures.
+# Usage: tools/check_hotswap_video.sh <engine binary> [assets dir] [workshop content dir]
+# Exit code 0 when the swapped picture looks like the fresh one. Needs Pillow (run with python3 -I).
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+BINARY=${1:?engine binary}
+ASSETS=${2:-/workspace/SteamLibrary/steamapps/common/wallpaper_engine/assets}
+CONTENT=${3:-/workspace/SteamLibrary/steamapps/workshop/content/431960}
+FROM=3471294034 TO=3818199837
+for id in $FROM $TO; do [ -d "$CONTENT/$id" ] || { echo "SKIP: wallpaper $id not in $CONTENT"; exit 0; }; done
+work=$(mktemp -d /tmp/lwe-hotswap-video.XXXXXX)
+trap 'rm -rf "$work"' EXIT
+
+echo "path=$CONTENT/$TO" > "$work/ctl"
+LWE_HOTSWAP_AT_FRAME=30 HEADLESS_RENDER_DELAY=300 "$HERE/headless_render.sh" "$BINARY" "$work/swap.png" \
+    --assets-dir "$ASSETS" --control-file "$work/ctl" "$CONTENT/$FROM" > "$work/swap.log" 2>&1 || { cat "$work/swap.log"; exit 1; }
+HEADLESS_RENDER_DELAY=300 "$HERE/headless_render.sh" "$BINARY" "$work/fresh.png" \
+    --assets-dir "$ASSETS" "$CONTENT/$TO" > "$work/fresh.log" 2>&1 || { cat "$work/fresh.log"; exit 1; }
+python3 -I "$HERE/linuxvm/check_frame.py" --similar "$work/fresh.png" "$work/swap.png" 10

+ 143 - 54
tools/linuxvm/RELEASE_TESTING.md

@@ -1,7 +1,7 @@
 # Release testing in the distro VMs
 
-Trigger: when the maintainer says a release is planned, run the whole matrix below, one VM after the other, and report
-before anything is tagged. Nothing here runs on its own schedule.
+Trigger: when the maintainer says a release is planned, run the whole matrix below and report before anything is tagged.
+Nothing here runs on its own schedule.
 
 ## What is tested
 
@@ -10,6 +10,10 @@ distribution builds, `tools/package_release.sh`, built in the proot rootfs under
 we_manager's .deb, AppImage and Flatpak. Wallpapers used everywhere: one scene with parallax (1111948150), one scene with
 particles (1120596121), one video, one preset, two web items (1078208425, 834237690).
 
+Besides the VMs: the PVS-Studio, scan-build and clang-tidy runs against their baselines, the unit tests, the regression sweep
+over the installed scenes (`tools/regression/regress.py`), `tools/smoke_test_release.sh` on every tarball, the formatting
+check (clang-format 22 on `src`) and a build of both CMake variants (`DISABLE_KDE_FEATURES` on and off).
+
 ## The matrix (a VM per row, `tools/linuxvm/linuxvm.sh`)
 
 | VM | Session | Engine path | Extra checks |
@@ -17,18 +21,32 @@ particles (1120596121), one video, one preset, two web items (1078208425, 834237
 | fedora-kde | Plasma Wayland | distribution + Flatpak | KWin script pause (maximized, fullscreen, show desktop), click passthrough |
 | fedora-gnome | GNOME Wayland | distribution | shell extension, per-output pause |
 | ubuntu-gnome | GNOME Wayland | distribution + .deb we_manager | polkit install/update dialog |
-| arch-hypr | Hyprland | portable + AUR packages | layer shell, per-output pause |
-| mint-cinnamon | Cinnamon X11 | portable | `--window-background` (icons above, below windows, sticky), root mode |
 | debian-gnome | GNOME Wayland | portable + .deb + Flatpak | maximized + fullscreen pause, apt dependency install |
+| debian-xfce | XFCE X11 | portable + .deb | covered root window, second monitor, apt dependency install |
+| zorin-gnome | GNOME Wayland | portable + .deb | Ubuntu 24.04 base; its Xorg session shows nothing in root mode |
+| elementary | Pantheon Wayland (X11 selectable) | portable + .deb | the default Wayland session cannot run the engine (Gala has no wlr-layer-shell), the golden disk is that default session; the X11 session needs `--window-background` |
 | opensuse-kde | Plasma Wayland | portable | newest libraries, zypper dependency install, maximized pause |
-| opensuse-xfce | XFCE X11 | portable | PulseAudio only desktop (no libpipewire), covered root window, zypper dependency install |
+| opensuse-leap | Plasma Wayland (Leap 16, KWin 6.4) | portable | greeter login, KWin 6.4 script ids |
+| opensuse-xfce | XFCE X11 | portable | PulseAudio only desktop (no libpipewire), covered root window, second monitor, zypper dependency install |
+| arch-hypr | Hyprland | portable + AUR packages | layer shell, per-output pause |
+| arch-xfce | XFCE X11 | portable | Arch on a covered root window, second monitor |
 | manjaro-kde | Plasma Wayland | portable | pacman dependency install (needs a fully updated system) |
-| popos-cosmic | COSMIC | portable + .deb | layer shell and window states (`zcosmic_toplevel_info`) on cosmic-comp |
+| manjaro-xfce | XFCE X11 | portable | Arch family on a covered root window, second monitor, pacman dependency install after a full update |
 | cachyos-kde | Plasma Wayland | portable | x86-64-v3 packages and kernel, Plasma Login Manager autologin, pacman dependency install |
+| cachyos-hypr | Hyprland (uwsm, Noctalia shell) | portable | layer shell on Hyprland, greetd autologin, Hello window and keyring prompt closed by PREP |
+| garuda-kde | Plasma Wayland | portable | Garuda gaming edition, pacman dependency install after a full update |
+| endeavouros | Plasma Wayland | portable | the real EndeavourOS (offline installer, KDE), pacman dependency install after a full update |
+| endeavouros-xfce | XFCE X11 | portable | second monitor, the Welcome window is closed by title |
+| mint-cinnamon | Cinnamon X11 | portable + .deb | `--window-background` (icons above, below windows, sticky), root mode, second monitor |
+| mint22-2 | Cinnamon X11 (Linux Mint 22.2) | portable + .deb | the same checks as mint-cinnamon |
+| mx-xfce | XFCE X11 (MX Linux 25.3, Debian 13 based) | portable + .deb | second monitor, we_manager's .deb self update |
+| popos-cosmic | COSMIC | portable + .deb | layer shell and window states (`zcosmic_toplevel_info`) on cosmic-comp |
+| steamos | Plasma Wayland, read-only root | portable | Steam Deck image on an NVMe disk with Valve SMBIOS, `WEM_LAUNCH` (see below), no dependency install (immutable) |
 | bazzite | KDE, immutable | portable + Flatpak | rpm-ostree: dependency install refused, Flatpak |
 
-Rows are added as the VMs of `TODO.md` -> "Real-session distro VMs" get built. A new distro joins the matrix once its
-VM has a profile and a golden snapshot.
+A new distro joins the matrix once its VM has a profile and a golden snapshot. ChimeraOS is not in it: its image installs and
+boots in a VM but cannot draw (its Mesa has no virgl, llvmpipe or lavapipe, and the root is read-only), so it needs real
+hardware or GPU passthrough.
 
 ## One VM run
 
@@ -39,65 +57,136 @@ VM has a profile and a golden snapshot.
    `grim` or `cosmic-screenshot` per profile), check it.
 5. Behaviour checks: hotswap to another wallpaper, pause while a window is fullscreen (CPU of the engine drops below
    3%) and resume, stop leaves no engine, no web host and no stray window or KWin script, autostart entry works.
-6. Collect engine and we_manager logs, powers the VM off, deletes the overlay.
+6. Collect engine and we_manager logs, power the VM off, delete the overlay.
 
 A screenshot passes when the wallpaper area is not black or flat, is not upside down (compare with the reference frame
 of the same wallpaper from `~/.local/share/we_live/refs` or the previous run, tolerance per wallpaper) and the desktop
 icons/panel are still visible where the profile says they must be. A run fails on: engine exit or crash (core, `SIGSEGV`
 in the log), missing frames, black desktop, a leftover process, a log line matching the error list in the profile.
 
+After a failed first pass the driver repeats only the failed groups in the same boot. A failure that only shows in the retry
+is a state problem of the session, not of the first run.
+
+## Regression checks for known bugs (guest_test.sh, BEHAVIOR=1)
+
+Run on every VM of the matrix, each one SKIPs where the guest cannot do it:
+
+- hotswap from 3471294034 (cursor particles leave the colour mask's alpha off) to 3818199837 (video layer): the swapped
+  frame must look like a fresh start (`check_frame.py --similar`), the old bug left the video transparent, grey clouds.
+  The VMs' virgl does not reproduce it (the old engine passes there), so the real test is `tools/check_hotswap_video.sh
+  <engine binary>` on the host GPU (difference 102 on the old engine, 3.5 on the fixed one): run it in the regression step
+- hotswap changes the picture: `hot-after.png` must differ from `hot-before.png` (`check_frame.py --differ`). On GNOME 46 an
+  orphaned window actor of an earlier wallpaper kept a frozen frame on screen and made them identical (see Known problems)
+- fullscreen pause, then `MINIMIZE_CMD` hides the window (X11 profiles): the engine must resume
+- automute (`--automute`, pulse tools in the guest): another app's sound mutes the wallpaper, the music is back within 5s
+  of it stopping, the same while a fullscreen window has the wallpaper paused (it used to take up to 15s and ignored
+  other apps while paused)
+- hotswap cycle (`hotswap_cycle_check`): one engine goes through scene (1120596121), video (1367456719), web (1078208425), scene
+  (1111948150), web (834237690), video and scene again; every step must keep the process, log the swap, show a picture that is not
+  flat or the empty desktop (`shot-cycle-*.png`), have a web host only on web wallpapers and add no crash lines to the log
+- pointer y direction (`pointer_check.sh`, `hover_check.py`): workshop item 3599498791 (a dock and a calendar whose weekday hover zones
+  are the engine's cursor hit test) with the VM's pointer on the Monday row and on the Sunday row of the calendar, the enlarged
+  label has to be the one under the pointer (it was mirrored on flipped outputs, i.e. KDE Wayland), and the dock icons have to
+  magnify with the pointer on the dock. Windows that open late and cover the calendar are closed by title before every pointer
+  position (XFCE's Displays dialog, an xfce4-panel plugin dialog, EndeavourOS Welcome, Ubuntu's update prompts, Steam's sign-in on
+  SteamOS). `POINTER=0` in a profile skips it
+- second monitor (`MULTI=1` and `MULTI_SHOT_CMD` in the profile, the VM starts with `LINUXVM_OUTPUTS=2`): the wallpaper must
+  show on both screens, the old X11 root handling painted one
+- `clean_install_check.sh` (needs `--app` and `--engine-tarball`): no engine, libvulkan removed (the engine needs it, Electron
+  does not; nss and libXxf86vm take Electron down too), we_manager's prebuilt install has to bring the library back (pacman, apt,
+  dnf and zypper paths). Ubuntu-based systems (Ubuntu, Mint, Zorin) bundle their libraries in the test tarball and removing libvulkan1
+  leaves apt with broken dependents, so there the check only starts from a system without `libglut.so.3.12`. The app dir is pushed to the
+  guest on every run (golden disks carry an old build), a .deb is installed when `we-manager` is missing; its engine tag is `v98.0.*` so
+  `update_check.sh`'s `v99.0.*` is the newer one and the engine must find all its libraries
+- unit test `Cursor y in scene units ...` (tests/MouseCoordinates.cpp): cursor y grows upwards on flipped and unflipped outputs
+
 ## Automation
 
 All of it lives in `tools/linuxvm/`:
 
 - `profiles/<vm>.sh`: how to reach the session (`SCREEN`, `SHOT_CMD`, `FULLSCREEN_CMD`, `MAXIMIZE_CMD`, `WEM`, `WEM_FLAGS`,
-  `PREP`, `LOGIN_PASSWORD` for greeters without autologin). Written for the VMs above, the older VMs (fedora, ubuntu, arch,
-  mint) still need theirs checked.
+  `WEM_LAUNCH`, `PREP`, `MULTI`, `POINTER`, `LOGIN_PASSWORD` for greeters without autologin). `WEM_LAUNCH` is the prefix of the
+  we_manager start line: SteamOS needs `systemd-run --user --scope -q` because a process started from an ssh session dies with it.
 - `linuxvm.sh golden <vm>` / `fresh <vm>`: the VM's disk is frozen as `golden.qcow2` and runs on a throwaway overlay, `fresh`
-  throws the overlay away. Done for debian-gnome, opensuse-kde, opensuse-xfce, popos-cosmic, bazzite and manjaro-kde.
-- `release_check.sh [--vm name]... [--candidate dir] [--app dir|.deb] [--engine-tarball tgz]`: loops over the profiles
-  sequentially, writes `reports/<date>/summary.md` with screenshots and logs per VM, retries the failed checks once,
-  powers the VM off (ssh `systemctl poweroff`, ACPI does not reach a locked KDE session) and resets the overlay.
+  throws the overlay away. Every VM of the matrix has one.
+- `release_check.sh [--vm name]... [--candidate dir] [--app dir|.deb] [--engine-tarball tgz] [--no-overlay]`: loops over the
+  profiles sequentially, writes `<REPORT_DIR>/summary.md` (default `reports/<date>/`) with screenshots and logs per VM, retries the
+  failed checks once, powers the VM off (ssh `systemctl poweroff`, ACPI does not reach a locked KDE session) and resets the
+  overlay. `KEEP_VM=1` leaves the VM running, `REPORT_DIR` keeps parallel runs apart (they would share one summary.md).
 - `guest_test.sh` (one PASS/FAIL/SKIP line per check; BEHAVIOR=1 adds hotswap, fullscreen and maximized pause through
-  `pause_check`, SIGKILL cleanup), `run_behavior.sh` (the same by hand), `host_shots.sh` (screenshots through the VM's
-  display, and a click on the screen centre so a test window gets the focus), `check_frame.py` (black/flat/unchanged/
-  hotswap differs, Pillow, run with `-I`).
-- `wem_check.sh` (we_manager install, launch, stop, kill all, autostart entry), `update_check.sh` (`fake_github.py` serving a
-  newer app .deb, `bump_deb.py`, and the candidate engine as a newer release), `deps_check.sh` (the "install build
-  dependencies" button on the VM's package manager, then the engine's CMake configure on the source tarball),
-  `autostart_check.sh` (a one wallpaper autostart playlist, a real reboot, we_manager and the engine back; wallpapers only
-  come back through the autostart playlist, a wallpaper launched by hand is not restored), `flatpak_check.sh` (bundle install,
-  scene + web wallpaper, stop, kill all, autostart entry).
-- Still open: reference frames per wallpaper in `check_frame.py` (upside down, wrong crop), profiles for the older VMs.
+  `pause_check`, SIGKILL cleanup), `run_behavior.sh` (the same by hand), `pointer_check.sh` and `hover_check.py` (the pointer
+  checks), `host_shots.sh` (screenshots through the VM's display, and a click on the screen centre so a test window gets the
+  focus), `check_frame.py` (black/flat/unchanged/hotswap differs, Pillow, run with `-I`).
+- `clean_install_check.sh` (a first install of the prebuilt engine through we_manager), `wem_check.sh` (we_manager install,
+  launch, stop, kill all, autostart entry), `update_check.sh` (`fake_github.py` serving a newer app .deb, `bump_deb.py`, and the
+  candidate engine as a newer release), `deps_check.sh` (the "install build dependencies" button on the VM's package manager,
+  then the engine's CMake configure on the source tarball), `autostart_check.sh` (a one wallpaper autostart playlist, a real
+  reboot, we_manager and the engine back; wallpapers only come back through the autostart playlist, a wallpaper launched by hand
+  is not restored), `flatpak_check.sh` (bundle install, scene + web wallpaper, stop, kill all, autostart entry).
+- `update_check.sh` and `clean_install_check.sh` start `fake_github.py` through `fake_github_lib.sh`: the apps ask
+  `https://api.github.com` (port 443), so the guest redirects 10.0.2.2:443 to a host port of the VM's own (nft or iptables rule)
+  and VMs run these checks in parallel. A guest without nft/iptables, or a redirect that does not reach our server, falls back to
+  host port 443 behind `/tmp/lwe-fake-github.lock`. The report's `wem.txt` says which one ran (`fake api.github.com on host port ...`).
+- `prep_guest.sh <vm>` fills `~/lwe` in a VM (the payload from `$LINUXVM/payload`, the candidate engine, the guest scripts), it must
+  exist before `release_check.sh` runs. `qtype.sh <vm> <us|de> <text>` types one key at a time over QMP (`linuxvm.sh type` drops
+  characters under load). `bootstrap_ssh.sh <vm> <port> <us|de>` sets up ssh in an ISO installed VM: it serves a setup script from
+  the host and runs it in a terminal already open in the guest (`FETCH='wget -q'` where curl is missing). `<vm>/qemu-extra` holds
+  extra QEMU arguments (SteamOS: NVMe disk and Valve SMBIOS, MX Linux: the ISO as USB disk).
+- GNOME Shell extension debugging without touching the golden disks: `debug_extension.py <dir>` builds the extension with `LWE_DBG`
+  journal lines, `ghost_run.sh <vm> <tag> [extension.js]` runs `release_check.sh` on an overlay that has that extension (needs
+  `LWE_CANDIDATE`, `LWE_ENGINE_TARBALL`, `LWE_APP_DEB` or `LWE_APP_DIR`, writes `reports/ghost/<vm>-<tag>/shell-debug.log`),
+  `ghost_loop.sh <vm> <tries>` repeats it until a check fails, and `ghost_diag.sh <vm>` looks at a VM kept up with `KEEP_VM=1`.
 
 ## Running it
 
-I start `release_check.sh` in the background and watch it, roughly 10 minutes per VM, so about two hours for ten.
-A failing VM is reported with its screenshot and log excerpt and the matrix carries on with the next one. I do not fix
-and re-tag on my own: the report goes to the maintainer first. Cleanup after a run: all VMs powered off, overlays gone.
-
-## State (2026-10-19)
-
-Built and used: everything under "Automation". Golden disks and profiles exist for debian-gnome, debian-xfce, opensuse-kde,
-opensuse-xfce, opensuse-leap, manjaro-kde, cachyos-kde, arch-xfce (Arch with XFCE, stands in for EndeavourOS), popos-cosmic and bazzite.
-fedora-kde, fedora-gnome and ubuntu-gnome have draft profiles that were not run through `release_check.sh`, arch-hypr and
-mint-cinnamon have none yet. Per VM notes: KDE VMs need screen lock and sleep disabled (`kde-inhibit`, in the profile's
-PREP), Bazzite's /home is /var/home, Debian's cloud image needs the regular kernel for any graphics, GNOME needs its extension
-enabled and one relogin, Bazzite, Leap and COSMIC stop at a greeter (LOGIN_PASSWORD), the COSMIC VM needs
-`--disable-gpu-compositing` for we_manager.
-
-Pitfalls found while writing it: a locked or sleeping screen makes every picture identical, leftover test windows keep the
-engine paused (a paused engine does not read hotswap requests), the engine's command line shows /var/home on Fedora Atomic
-systems, `pkill -f` patterns match the ssh command that carries them (use `pkill -x`), the remote login shell can be zsh (an
-unmatched glob aborts the command), two runs on one VM disturb each other, a GNOME fullscreen window only counts when it has
-the focus (host_shots.sh clicks it), we_manager's library scan skips symlinked folders, an autostarted we_manager only
-brings wallpapers back through its autostart playlist, one or two VMs fit in RAM at a time (8 GB each).
-
-## Order of work
-
-1. Profiles for fedora-kde, fedora-gnome, ubuntu-gnome, arch-hypr and mint-cinnamon, golden disks, and `release_check.sh` runs
-   of them.
-2. Run the whole matrix on the committed build, fix what it finds, keep that report as the baseline for comparisons
-   (reference frames per wallpaper for `check_frame.py` first).
-3. Remaining distros from the TODO (SteamOS, Zorin, Manjaro XFCE, Garuda, ChimeraOS, elementary, MX; installer
-   ISOs, no cloud images) join the matrix one by one.
+Start `release_check.sh` in the background and watch it, 10 to 25 minutes per VM. One or two VMs fit in RAM comfortably (6 to 8 GB
+each); four at a time worked on a 30 GB host, check `free -g` before starting another. Every VM has its own fake GitHub port, so
+parallel runs are fine, but a pause check can fail only because of the extra CPU load: rerun that VM alone. Power off every VM that
+was started for an experiment. A failing VM is reported with its screenshot and log excerpt and the matrix carries on with the next
+one. Nothing is fixed and tagged on its own: the report goes to the maintainer first. Cleanup after a run: all VMs powered off,
+overlays gone.
+
+## Pitfalls of the rig
+
+- A locked or sleeping screen makes every picture identical: KDE VMs need screen lock and sleep disabled (`kde-inhibit`, in the
+  profile's PREP).
+- Leftover test windows keep the engine paused, and a paused engine does not read hotswap requests. Windows of the desktop itself
+  (Welcome apps, update prompts, panel dialogs) cover the wallpaper the same way.
+- `pkill -f` patterns match the ssh command that carries them (use `pkill -x`). The remote login shell can be zsh, which aborts a
+  command on an unmatched glob.
+- Two runs on one VM disturb each other, including a hand started experiment while a matrix lane reaches that VM.
+- A GNOME fullscreen window only counts when it has the focus (`host_shots.sh` clicks it).
+- KWin 6.4 reuses the id of a live script after any unload, which also hits `maximize_kde.sh` and any script loaded over D-Bus
+  (check the ids against the `Script<id>` children of `/Scripting`).
+- The engine's command line shows `/var/home` on Fedora Atomic systems. we_manager's library scan skips symlinked folders. An
+  autostarted we_manager only brings wallpapers back through its autostart playlist.
+- Force-removing a library with dpkg breaks apt for the rest of the run (hence the `libglut` path for Ubuntu-based profiles).
+- Many `qemu-system-x86` zombies pile up under a long matrix run (the container's pid limit): restart before a very long run.
+
+## Per VM notes
+
+- Bazzite's /home is /var/home.
+- Debian's cloud image needs the regular kernel for any graphics.
+- GNOME needs the extension enabled and one relogin. Bazzite, Leap and COSMIC stop at a greeter (`LOGIN_PASSWORD`). The COSMIC VM
+  needs `--disable-gpu-compositing` for we_manager.
+- Hyprland: `sessenv.sh` reads the session variables from `systemctl --user show-environment` when the compositor process does not
+  carry them (uwsm).
+- MX Linux 25.3 XFCE: the ISO does not boot as a CD-ROM under OVMF ("Failed to boot both default and fallback entries") but boots as a
+  USB disk (`qemu-extra`: `-drive file=<iso>,if=none,id=usbd,format=raw,readonly=on -device usb-storage,drive=usbd,bootindex=1`, pick
+  the systemd entry). Its own installer (whole disk, user lab, autologin, no Samba), then `openssh-server` from a terminal
+  (ctrl-alt-t) and `bootstrap_ssh.sh mx-xfce 8772 us lab`.
+- Installer pitfalls: Calamares starts with a German layout, pick English on the keyboard page (or use `qtype.sh de`), clear the
+  prefilled login and hostname fields, Zorin and elementary need `openssh-server` installed from the live terminal, never click
+  "Restart now" in an installer (it boots the ISO again).
+
+## Known problems and open items
+
+- **elementary** stays red: the default Wayland session (Gala) has no wlr-layer-shell, the engine cannot start.
+- **Frozen wallpaper on GNOME 46** (Ubuntu, Zorin): Mutter frees a wallpaper window without unmanaging it, and its actor stays in
+  the Shell's window group with the last frame (`hot-after` identical to `hot-before`, no engine alive). It turns up in a minority
+  of full runs, so a single clean run proves little. A ghost shows as a surplus wallpaper `MetaWindowActor` in the `GROUP` lines of
+  the debug extension. The extension hides such orphans (`_hideOrphanActors`). The golden disks of the GNOME VMs (ubuntu-gnome,
+  zorin-gnome, debian-gnome, fedora-gnome) still carry the old extension: until they are updated, `ghost_run.sh` is the way to run
+  the shipped one.
+- Reference frames per wallpaper for `check_frame.py` (upside down, wrong crop) are still missing; the checks compare with the
+  previous run.

+ 1 - 1
tools/linuxvm/autostart_check.sh

@@ -13,7 +13,7 @@ cdp() { sshv ". ~/sessenv; cd ~/wem; timeout ${CDP_TIMEOUT:-90} python3 cdp.py \
 
 if ! cdp 'window.electronAPI.lwe.listScreens()' | grep -q "$screen"; then
     sshv 'pkill -f "[w]e-manager"; true'; sleep 3
-    if [[ $2 == installed ]]; then start="we-manager ${WEM_FLAGS:-}"; else start="~/wem/$(basename "$2")/we-manager --no-sandbox ${WEM_FLAGS:-}"; fi
+    if [[ $2 == installed ]]; then start="${WEM_LAUNCH:-} we-manager ${WEM_FLAGS:-}"; else start="${WEM_LAUNCH:-} ~/wem/$(basename "$2")/we-manager --no-sandbox ${WEM_FLAGS:-}"; fi
     sshv ". ~/sessenv; (setsid nohup $start --remote-debugging-port=9222 > ~/wem/app-auto.log 2>&1 </dev/null &); sleep 25"
 fi
 sshv 'cd ~/.steam/steam/steamapps/workshop/content/431960 && for id in 1120596121 1078208425; do [ -L $id ] && rm $id; [ -d $id ] || cp -al ~/lwe/wp-$id $id; done'  # the scan skips symlinked folders

+ 5 - 4
tools/linuxvm/bootstrap_ssh.sh

@@ -2,7 +2,7 @@
 # bootstrap_ssh.sh <vm> <port> <layout us|de> [password] - for a VM installed from an ISO that has no ssh: serves a setup script
 # from this host ($PORT, pick one nobody else uses) and runs it in a terminal that is already open and focused in the guest
 # (the QEMU user network reaches the host as 10.0.2.2). The script enables sshd, adds the rig key, passwordless sudo,
-# autologin is distro specific and not done here. The guest password is typed by the script's sudo (default labbalab1).
+# FETCH='wget -q' for a guest without curl (default 'curl -sO'); autologin is distro specific and not done here. The guest password is typed by the script's sudo (default labbalab1).
 HERE=$(cd "$(dirname "$0")" && pwd)
 LINUXVM=${LINUXVM:-$HOME/.local/share/linuxvm}
 vm=$1 port=$2 layout=$3 pw=${4:-labbalab1}
@@ -17,8 +17,9 @@ sudo chsh -s /bin/bash lab
 sudo ufw allow 22 2>/dev/null; sudo firewall-cmd --add-service=ssh --permanent 2>/dev/null
 echo SETUP-DONE
 EOS
-(cd "$dir" && python3 -m http.server "$port" --bind 0.0.0.0 >/dev/null 2>&1 & echo $! > "$dir/pid")
+(cd "$dir" && exec python3 -m http.server "$port" --bind 0.0.0.0 >/dev/null 2>&1) &
+server=$!
 sleep 1
 q() { "$HERE/qtype.sh" "$vm" "$layout" "$1"; }
-q "curl -sO 10.0.2.2:$port/s"; q ret; sleep 4; q "bash s"; q ret; sleep 15
-kill "$(cat "$dir/pid")"; rm -rf "$dir"
+q "${FETCH:-curl -sO} 10.0.2.2:$port/s"; q ret; sleep 4; q "bash s"; q ret; sleep 15
+kill "$server"; rm -rf "$dir"

+ 34 - 3
tools/linuxvm/check_frame.py

@@ -1,5 +1,8 @@
 """check_frame.py [--baseline base.png] shot.png [shot.png ...] - did the wallpaper reach the screen?
 check_frame.py --differ a.png b.png - do two frames differ (hotswap)?
+check_frame.py --similar a.png b.png [max] - are two frames of the same wallpaper alike (a hotswap must look like a fresh start)?
+check_frame.py --crop from,to [--baseline base.png] shot.png - only the part of the width between the two fractions (one
+monitor of a multi monitor screenshot)
 
 Without --baseline a screenshot only fails when it is pure black. With the baseline (the desktop's own screenshot taken
 before the engine started) it must also differ from it along the right edge and the top, where windows, panels and
@@ -19,8 +22,18 @@ def strips(image):
     ]
 
 
+CROP = None
+
+
+def crop(image):
+    if CROP is None:
+        return image
+    w, h = image.size
+    return image.crop((int(w * CROP[0]), 0, int(w * CROP[1]), h))
+
+
 def check(path, baseline):
-    image = Image.open(path).convert("RGB")
+    image = crop(Image.open(path).convert("RGB"))
     parts = strips(image)
     stats = [ImageStat.Stat(part.convert("L")) for part in parts]
     mean = sum(stat.mean[0] for stat in stats) / len(stats)
@@ -28,10 +41,13 @@ def check(path, baseline):
     if mean < 1 and stddev < 1:
         return False, "black"
     if baseline is not None:
-        base_parts = strips(baseline.resize(image.size))
+        base_parts = strips(crop(baseline).resize(image.size))
         diffs = [ImageStat.Stat(ImageChops.difference(a, b).convert("L")).mean[0] for a, b in zip(parts, base_parts)]
         diff = sum(diffs) / len(diffs)
-        if diff < 6:
+        # a mostly black wallpaper has a small mean difference but still some lit pixels where a bare desktop has none
+        histograms = [ImageChops.difference(a, b).convert("L").histogram() for a, b in zip(parts, base_parts)]
+        lit = sum(sum(h[9:]) for h in histograms) / sum(sum(h) for h in histograms)
+        if diff < 6 and lit < 0.003:
             return False, f"same as the desktop without a wallpaper (difference {diff:.1f})"
         return True, f"mean {mean:.0f}, difference from the baseline {diff:.0f}"
     return True, f"mean {mean:.0f}, stddev {stddev:.0f}"
@@ -47,8 +63,23 @@ def differ(a, b):
     sys.exit(0 if ok else 1)
 
 
+def similar(a, b, limit):
+    size = (96, 54)
+    first, second = Image.open(a).convert("RGB").resize(size), Image.open(b).convert("RGB").resize(size)
+    diff = ImageStat.Stat(ImageChops.difference(first, second).convert("L")).mean[0]
+    ok = diff <= limit
+    print(f"{'PASS' if ok else 'FAIL'} {b}: {'like' if ok else 'not like'} {a} (difference {diff:.1f}, limit {limit:g})")
+    sys.exit(0 if ok else 1)
+
+
 def main():
+    global CROP
     args = sys.argv[1:]
+    if args[:1] == ["--similar"]:
+        similar(args[1], args[2], float(args[3]) if len(args) > 3 else 10)
+    if args[:1] == ["--crop"]:
+        CROP = [float(x) for x in args[1].split(",")]
+        args = args[2:]
     if args[:1] == ["--differ"]:
         differ(args[1], args[2])
     baseline = None

+ 85 - 0
tools/linuxvm/clean_install_check.sh

@@ -0,0 +1,85 @@
+#!/bin/bash
+# clean_install_check.sh <vm> <app dir | .deb> - a first install of the prebuilt engine through we_manager the way a new user
+# does it: no engine under ~/.local/share/linux-wallpaperengine-kde and one of the system libraries the engine leaves to the
+# distribution removed (libvulkan: the engine needs it, Electron does not, so we_manager keeps running; nss would be the
+# realistic one but Electron needs it too, and libXxf86vm takes Electron down through Mesa on X11), so the "install missing libraries" step has to run. The
+# candidate's portable tarball is served by fake_github.py under every asset name we_manager may ask for. Checks: the library
+# is gone before, the install reports installed, the library is back, the engine's own library check finds nothing missing.
+# Needs the session running (sessenv) and we_manager on the VM (wem_check.sh / update_check.sh put it there).
+#   ENGINE_TARBALL the candidate's portable tarball (required)
+HERE=$(cd "$(dirname "$0")" && pwd)
+vm=$1 app=$2
+sshv() { "$HERE/linuxvm.sh" ssh "$vm" "$@" </dev/null; }
+status=0
+pass() { echo "PASS $1"; }
+fail() { echo "FAIL $1"; status=1; }
+cdp() { sshv ". ~/sessenv; cd ~/wem; NODE_EXTRA_CA_CERTS= timeout ${CDP_TIMEOUT:-90} python3 cdp.py \"$1\" 2>&1 | cut -c1-${2:-700}"; }
+[ -f "$ENGINE_TARBALL" ] || { echo "ENGINE_TARBALL is not set to the candidate's portable tarball"; exit 2; }
+
+remove_cmd=$(sshv '. /etc/os-release; case " $ID $ID_LIKE " in
+  *" arch "*) echo "sudo pacman -Rdd --noconfirm vulkan-icd-loader" ;;
+  *linuxmint*) echo "sudo apt-get -o DPkg::Lock::Timeout=180 remove -y libvulkan1" ;;
+  *" ubuntu "*|*" debian "*) echo "sudo dpkg --remove --force-depends libvulkan1" ;;
+  *" fedora "*) echo "sudo rpm -e --nodeps vulkan-loader" ;;
+  *suse*) echo "sudo rpm -e --nodeps libvulkan1" ;;
+esac')
+# Ubuntu 24.04 gets the distribution build, whose own libraries (freeglut and the rest) are missing on a fresh install: nothing has to be
+# removed there, and removing libvulkan1 leaves apt with broken dependents (dpkg) or takes the GNOME session along (apt-get remove)
+victim=libvulkan.so.1
+if sshv '. /etc/os-release; [ "$ID" = ubuntu ] || [ "$ID" = linuxmint ] || case " $ID_LIKE " in *" ubuntu "*) true;; *) false;; esac'; then victim=libglut.so.3.12; remove_cmd="sudo apt-get remove -y libglut3.12"; fi
+if [ -z "$remove_cmd" ]; then echo "SKIP clean install: no way to remove a system library on this distribution"; exit 0; fi
+if sshv 'touch /usr/.lwe-rw 2>/dev/null && rm /usr/.lwe-rw' || sshv 'sudo touch /usr/.lwe-rw 2>/dev/null && sudo rm /usr/.lwe-rw'; then :; else
+    echo "SKIP clean install: read-only system, libraries cannot be installed here"; exit 0
+fi
+
+work=$(mktemp -d)
+engine_tag=v98.0.$(date +%s)
+for variant in kde generic; do
+    for distro in portable ubuntu-24.04 fedora-44; do cp "$ENGINE_TARBALL" "$work/linux-wallpaperengine-$variant-$distro-x86_64.tar.gz"; done
+done
+assets=$(ls "$work"/*.tar.gz | paste -sd,)
+mkdir -p "$work/certs"
+. "$HERE/fake_github_lib.sh"
+fgh_start "$vm" "$work" --release "WallpaperEngineLover/linux-wallpaperengine-kde=$engine_tag:$assets"
+trap 'kill $fake 2>/dev/null; rm -rf "$work"; sshv "pkill -f \"[w]e-manager\" 2>/dev/null; sudo sed -i \"/api.github.com/d\" /etc/hosts; true" >/dev/null 2>&1' EXIT
+sleep 3
+kill -0 $fake 2>/dev/null || { cat "$work/fake.log"; echo "fake_github did not start (port 443?)"; exit 2; }
+
+sshv 'mkdir -p ~/wem'
+if [ -d "$app" ]; then
+    tar -C "$(dirname "$app")" -cf - "$(basename "$app")" | ssh -i "$HOME/.local/share/linuxvm/id_ed25519" -p "$(cat "$HOME/.local/share/linuxvm/vms/$vm/port")" \
+        -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR lab@127.0.0.1 'mkdir -p ~/wem && tar -C ~/wem -xf -'
+fi
+"$HERE/linuxvm.sh" scp "$vm" "$work/certs/ca.pem" wem/fake-ca.pem
+"$HERE/linuxvm.sh" scp "$vm" "$HERE/cdp.py" wem/cdp.py
+sshv 'grep -q "api.github.com" /etc/hosts || echo "10.0.2.2 api.github.com" | sudo tee -a /etc/hosts >/dev/null
+sudo mkdir -p /etc/polkit-1/rules.d
+printf "polkit.addRule(function(action, subject) { if (subject.user == \"lab\") return polkit.Result.YES; });\n" | sudo tee /etc/polkit-1/rules.d/49-lab-test.rules >/dev/null
+pkill -f "[w]e-manager" 2>/dev/null; for _ in $(seq 20); do pgrep -f "[w]e-manager" >/dev/null || break; sleep 1; done; rm -rf ~/.local/share/linux-wallpaperengine-kde; true'
+sleep 2
+
+if [[ $app == *.deb ]]; then
+    "$HERE/linuxvm.sh" scp "$vm" "$app" wem/app.deb
+    sshv 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-downgrades ./wem/app.deb >/tmp/wem-deb.log 2>&1'
+fi
+if [[ $app == *.deb ]]; then start="${WEM_LAUNCH:-} we-manager ${WEM_FLAGS:-}"; else start="${WEM_LAUNCH:-} ~/wem/$(basename "$app")/we-manager --no-sandbox ${WEM_FLAGS:-}"; fi
+sshv ". ~/sessenv; export NODE_EXTRA_CA_CERTS=\$HOME/wem/fake-ca.pem; (setsid nohup $start --remote-debugging-port=9222 > ~/wem/app-clean.log 2>&1 </dev/null &); for _ in \$(seq 40); do grep -q 'DevTools listening' ~/wem/app-clean.log 2>/dev/null && break; sleep 1; done; sleep 8"
+[ "$(sshv 'pgrep -fc "[w]e-manager"')" -gt 0 ] || { fail "clean install: we_manager did not start: $(sshv 'tail -3 ~/wem/app-clean.log')"; exit 1; }
+
+sshv "$remove_cmd" > /tmp/lwe-clean-remove.log 2>&1
+if sshv "/sbin/ldconfig -p | grep -q \"$victim (libc6,x86-64)\""; then fail "clean install: $victim is still installed after '$remove_cmd'"; exit 1; fi
+pass "clean install: no engine and no $victim on the system"
+
+# installPrebuilt resolves with the engine status either way, the outcome comes as progress events
+expr='(async () => { const seen = []; const off = window.electronAPI.on.lweInstallProgress(p => seen.push(p.stage + ": " + p.message)); const status = await window.electronAPI.lwe.installPrebuilt(); off(); return { installed: status.installed, last: seen.slice(-3) }; })()'
+out=$(sshv ". ~/sessenv; cd ~/wem; NODE_EXTRA_CA_CERTS=\$HOME/wem/fake-ca.pem timeout 900 python3 cdp.py '$expr' 2>&1 | cut -c1-700")
+if echo "$out" | grep -q '"installed": true' && ! echo "$out" | grep -q 'error: '; then pass "clean install: we_manager installed the engine"
+else fail "clean install: the install failed: $out"; fi
+if [ "$victim" = libglut.so.3.12 ]; then echo "SKIP clean install: the test tarball bundles $victim, nothing has to be installed on the way"
+elif sshv "/sbin/ldconfig -p | grep -q \"$victim (libc6,x86-64)\""; then pass "clean install: the missing system library was installed on the way"
+else fail "clean install: $victim is still missing after the install"; fi
+engine=$(sshv 'find ~/.local/share/linux-wallpaperengine-kde -maxdepth 2 -name linux-wallpaperengine -type f | head -1')
+missing=$(sshv "$engine --check-libraries 2>&1 | grep -c 'not found'")
+if [ "$missing" = 0 ]; then pass "clean install: the engine finds all its libraries"; else fail "clean install: $missing libraries still not found"; fi
+sshv 'pkill -f "[w]e-manager" 2>/dev/null; for _ in $(seq 20); do pgrep -f "[w]e-manager" >/dev/null || break; sleep 1; done; sudo rm -f /etc/polkit-1/rules.d/49-lab-test.rules; true'
+exit $status

+ 127 - 0
tools/linuxvm/debug_extension.py

@@ -0,0 +1,127 @@
+#!/usr/bin/env python3
+"""debug_extension.py <out dir> [extension.js] - writes <out dir>/extension.js, the GNOME Shell extension with LWE-DBG
+journal lines added: every wallpaper window's adopt, unmanaging, unmanaged, wm map/destroy, restacked, lower, the pruning of
+windows that vanished and the hiding of orphan actors, plus a line whenever the wallpaper actors or the children of the
+Shell's window group change. Read them with `journalctl -b -o short-monotonic | grep LWE-DBG` (ghost_run.sh does)."""
+import os
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+DEFAULT = os.path.join(HERE, '..', '..', 'gnome-shell-extension',
+                       'linux-wallpaperengine@wallpaperenginelover.github.io', 'extension.js')
+
+
+def replace(source, old, new):
+    if source.count(old) != 1:
+        sys.exit(f"anchor not found exactly once in the extension: {old.strip()[:60]!r}")
+    return source.replace(old, new)
+
+
+HELPERS = '''function dbg(message) {
+    console.log(`LWE-DBG ${message}`);
+}
+
+function wdesc(window) {
+    try {
+        return `#${window.get_stable_sequence()} "${window.get_title()}" type=${window.get_window_type()} layer=${window.get_layer()} mon=${window.get_monitor()} actor=${window.get_compositor_private() ? 1 : 0}`;
+    } catch (e) {
+        return `(window gone: ${e.message})`;
+    }
+}
+
+function appIdOf(window) {'''
+
+DUMP = '''        for (const actor of global.get_window_actors())
+            this._watch(actor.meta_window);
+
+        this._dbgLast = '';
+        this._dbgTimer = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 2, () => {
+            const live = new Set(global.display.list_all_windows());
+            const lines = global.get_window_actors().map(actor => {
+                const w = actor.meta_window;
+                return `${wdesc(w)} vis=${actor.visible ? 1 : 0} mapped=${actor.mapped ? 1 : 0} inlist=${live.has(w) ? 1 : 0} ours=${this._wallpapers.has(w) ? 1 : 0} shown=${this._shown.has(w) ? 1 : 0}`;
+            }).filter(line => line.includes('wallpaper') || line.includes('linux-wallpaperengine'));
+            const text = lines.join(' | ') || '(no wallpaper actors)';
+            if (text !== this._dbgLast) {
+                this._dbgLast = text;
+                dbg(`ACTORS ${text}`);
+            }
+            const group = global.window_group.get_children().map(c => {
+                let title = '';
+                try { title = c.meta_window ? c.meta_window.get_title() : '-'; } catch (e) { title = '?'; }
+                return `${c.constructor.name}[${title}|v${c.visible ? 1 : 0}|m${c.mapped ? 1 : 0}|${Math.round(c.width)}x${Math.round(c.height)}|o${c.opacity}]`;
+            }).join(' ');
+            if (group !== this._dbgGroup) {
+                this._dbgGroup = group;
+                dbg(`GROUP ${group}`);
+            }
+            return GLib.SOURCE_CONTINUE;
+        });
+        this._dbgWm = [
+            global.window_manager.connect('map', (_wm, actor) => dbg(`wm map ${wdesc(actor.meta_window)}`)),
+            global.window_manager.connect('destroy', (_wm, actor) => dbg(`wm destroy ${wdesc(actor.meta_window)}`)),
+        ];
+        dbg('enabled');
+
+        this._queueState();
+    }
+'''
+
+PLAIN_DUMP = '''        for (const actor of global.get_window_actors())
+            this._watch(actor.meta_window);
+
+        this._queueState();
+    }
+'''
+
+
+def main():
+    out = sys.argv[1] if len(sys.argv) > 1 else sys.exit(__doc__)
+    path = sys.argv[2] if len(sys.argv) > 2 else DEFAULT
+    source = open(path).read()
+
+    source = replace(source, 'function appIdOf(window) {', HELPERS)
+    source = replace(source, PLAIN_DUMP, DUMP)
+    source = replace(source, '    disable() {\n', '''    disable() {
+        dbg('disable');
+        if (this._dbgTimer)
+            GLib.source_remove(this._dbgTimer);
+        for (const id of this._dbgWm ?? [])
+            global.window_manager.disconnect(id);
+''')
+    source = replace(source, "            window.connect('unmanaged', () => {\n", '''            window.connect('unmanaging', () => dbg(`unmanaging ${wdesc(window)} ours=${this._wallpapers.has(window) ? 1 : 0}`)),
+            window.connect('unmanaged', () => {
+                dbg(`unmanaged ours=${this._wallpapers.has(window) ? 1 : 0}`);
+''')
+    source = replace(source, '    _adopt(window) {\n', '    _adopt(window) {\n        dbg(`adopt ${wdesc(window)}`);\n')
+    source = replace(source, '                wallpaper.lower();\n', '''            {
+                dbg(`lower ${wdesc(wallpaper)} index=${index} of ${stack.length}`);
+                wallpaper.lower();
+            }
+''')
+    source = replace(source, '''            for (const id of this._watched.get(window) ?? [])
+                window.disconnect(id);
+            this._watched.delete(window);
+            this._wallpapers.delete(window);
+            this._shown.delete(window);
+            this._raisedIds.delete(window);
+            this._syncOverview();''', '''            dbg(`PRUNE drops ${wdesc(window)} (not in list_all_windows, shown)`);
+            for (const id of this._watched.get(window) ?? [])
+                window.disconnect(id);
+            this._watched.delete(window);
+            this._wallpapers.delete(window);
+            this._shown.delete(window);
+            this._raisedIds.delete(window);
+            this._syncOverview();''')
+    source = replace(source, "            global.display.connect('restacked', () => {\n", '''            global.display.connect('restacked', () => {
+                dbg(`restacked wallpapers=${[...this._wallpapers.keys()].map(w => '#' + w.get_stable_sequence()).join(',')}`);
+''')
+    if '            actor.hide();\n' in source:
+        source = replace(source, '            actor.hide();\n', '            dbg(`hiding orphan ${wdesc(window)}`);\n            actor.hide();\n')
+
+    os.makedirs(out, exist_ok=True)
+    with open(os.path.join(out, 'extension.js'), 'w') as f:
+        f.write(source)
+
+
+main()

+ 1 - 1
tools/linuxvm/deps_check.sh

@@ -20,7 +20,7 @@ if [ -d "$app" ]; then
     tar -C "$(dirname "$app")" -cf - "$rm_old" | ssh -i "$HOME/.local/share/linuxvm/id_ed25519" -p "$(cat "$HOME/.local/share/linuxvm/vms/$vm/port")" \
         -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR lab@127.0.0.1 'mkdir -p ~/wem && tar -C ~/wem -xf -'
 fi
-if [[ $app == installed ]]; then start="we-manager ${WEM_FLAGS:-}"; else start="~/wem/$(basename "$app")/we-manager --no-sandbox ${WEM_FLAGS:-}"; fi
+if [[ $app == installed ]]; then start="${WEM_LAUNCH:-} we-manager ${WEM_FLAGS:-}"; else start="${WEM_LAUNCH:-} ~/wem/$(basename "$app")/we-manager --no-sandbox ${WEM_FLAGS:-}"; fi
 sshv ". ~/sessenv; (setsid nohup $start --remote-debugging-port=9222 > ~/wem/app-deps.log 2>&1 </dev/null &); sleep 25"
 distro=$(cdp 'window.electronAPI.lwe.detectDistro()'); echo "     detected distro: $distro"
 if sshv 'test -e /run/ostree-booted'; then

+ 38 - 0
tools/linuxvm/fake_github_lib.sh

@@ -0,0 +1,38 @@
+# fake_github_lib.sh - starts fake_github.py for a VM (sourced by clean_install_check.sh and update_check.sh, which define HERE and sshv).
+# The apps ask https://api.github.com, so the VM resolves it to the host (10.0.2.2) and the port is 443. With nft or iptables in the guest that
+# 443 is redirected to a port of the VM's own, so several VMs can run these checks at the same time; without (or when the redirect does not
+# reach our server) the old way is used: port 443 behind a host wide lock.
+# fgh_start <vm> <work dir> <fake_github.py args...> sets $fake (pid) and $fgh_port; the work dir holds certs/ and gets fake.log.
+
+fgh_redirect() {
+    sshv "sudo sh -c 'if command -v nft >/dev/null 2>&1; then nft add table ip lwefgh && nft \"add chain ip lwefgh out { type nat hook output priority -100 ; }\" && nft add rule ip lwefgh out ip daddr 10.0.2.2 tcp dport 443 dnat to 10.0.2.2:$1; elif command -v iptables >/dev/null 2>&1; then iptables -t nat -A OUTPUT -d 10.0.2.2 -p tcp --dport 443 -j DNAT --to-destination 10.0.2.2:$1; else exit 1; fi'" >/dev/null 2>&1
+}
+
+fgh_unredirect() {
+    sshv "sudo sh -c 'nft delete table ip lwefgh 2>/dev/null; iptables -t nat -F OUTPUT 2>/dev/null; true'" >/dev/null 2>&1
+}
+
+fgh_start() {
+    local vm=$1 work=$2
+    shift 2
+    fgh_port=$((30000 + $(cat "$HOME/.local/share/linuxvm/vms/$vm/port") % 10000))
+    if fgh_redirect "$fgh_port"; then
+        python3 "$HERE/fake_github.py" "$work/certs" "$@" --port "$fgh_port" > "$work/fake.log" 2>&1 &
+        fake=$!
+        sleep 3
+        # a request from the guest to the host's 443 has to show up in our own log
+        sshv "python3 -c \"import ssl, urllib.request as u; u.urlopen('https://10.0.2.2/repos/x/y/releases/latest', context=ssl._create_unverified_context(), timeout=8)\"" >/dev/null 2>&1
+        if kill -0 $fake 2>/dev/null && grep -q GET "$work/fake.log"; then
+            echo "     fake api.github.com on host port $fgh_port (redirected in the guest)"
+            return 0
+        fi
+        kill $fake 2>/dev/null
+        fgh_unredirect
+    fi
+    exec 9>"${TMPDIR:-/tmp}/lwe-fake-github.lock"
+    flock 9
+    fgh_port=443
+    python3 "$HERE/fake_github.py" "$work/certs" "$@" --port 443 > "$work/fake.log" 2>&1 &
+    fake=$!
+    echo "     fake api.github.com on host port 443 (host wide lock)"
+}

+ 12 - 0
tools/linuxvm/ghost_diag.sh

@@ -0,0 +1,12 @@
+#!/bin/bash
+# ghost_diag.sh <vm> - on a running GNOME VM: what is left of the engine, who holds a connection to the compositor and what
+# the extension still tracks. For a VM kept up with KEEP_VM=1 after a frozen wallpaper.
+HERE=$(cd "$(dirname "$0")" && pwd)
+"$HERE/linuxvm.sh" ssh "$1" '
+echo "== engine, helper and web processes"
+ps -eo pid,ppid,stat,etime,cmd | grep -E "[l]inux-wallpaperengine|[w]eb-helper|[g]nome-helper" | cut -c1-170
+echo "== sockets to the compositor and their peers"
+sudo ss -xp 2>/dev/null | grep -E "wayland|lwe-gnome" | cut -c1-200
+echo "== extension state"
+gdbus call --session --dest org.linuxwallpaperengine.Shell --object-path /org/linuxwallpaperengine/Shell --method org.linuxwallpaperengine.Shell.GetState 2>&1 | cut -c1-400
+' </dev/null

+ 15 - 0
tools/linuxvm/ghost_loop.sh

@@ -0,0 +1,15 @@
+#!/bin/bash
+# ghost_loop.sh <vm> <tries> [extension.js] - ghost_run.sh again and again (tags try1, try2, ...) until a run has a failing
+# check or the tries are used up; the same environment variables as ghost_run.sh. A frozen wallpaper after the engine stopped
+# (GNOME 46) shows up as the failing hotswap frame check, it needs several full runs to appear.
+HERE=$(cd "$(dirname "$0")" && pwd)
+vm=$1 tries=$2 ext=$3
+[ -n "$vm" ] && [ -n "$tries" ] || { sed -n '2,4p' "$0"; exit 2; }
+root=${LWE_REPORT_ROOT:-$HERE/reports/ghost}
+for n in $(seq 1 "$tries"); do
+    "$HERE/ghost_run.sh" "$vm" "try$n" "$ext"
+    if grep -q '^FAIL' "$root/$vm-try$n/$vm/checks.txt" 2>/dev/null; then
+        echo "$(date +%T) $vm try$n has a failing check, the loop stops" >> "$root/runs.log"
+        break
+    fi
+done

+ 43 - 0
tools/linuxvm/ghost_run.sh

@@ -0,0 +1,43 @@
+#!/bin/bash
+# ghost_run.sh <vm> <tag> [extension.js] - one full release_check of a GNOME VM with a different GNOME Shell extension than
+# the one on its golden disk (the repo's, or a debug_extension.py build): the extension goes onto the VM's overlay, which is
+# thrown away at the end, so the golden disk stays as it is. The Shell's LWE-DBG journal lines (debug builds), a final
+# screenshot and the release_check report land in <report root>/<vm>-<tag>/, a summary line in <report root>/runs.log.
+#   LWE_CANDIDATE      the unpacked candidate dir (with lwe-hints/), required
+#   LWE_ENGINE_TARBALL the candidate's tarball, required
+#   LWE_APP_DEB        we_manager's .deb, for profiles with WEM=deb
+#   LWE_APP_DIR        we_manager's unpacked app, for the others
+#   LWE_REPORT_ROOT    default reports/ghost
+HERE=$(cd "$(dirname "$0")" && pwd)
+vm=$1 tag=$2
+[ -n "$vm" ] && [ -n "$tag" ] || { sed -n '2,3p' "$0"; exit 2; }
+ext=${3:-$HERE/../../gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/extension.js}
+root=${LWE_REPORT_ROOT:-$HERE/reports/ghost}
+out=$root/$vm-$tag
+lv() { "$HERE/linuxvm.sh" "$@"; }
+sshv() { lv ssh "$vm" "$@" </dev/null; }
+uuid=linux-wallpaperengine@wallpaperenginelover.github.io
+
+if grep -q '^WEM=deb' "$HERE/profiles/$vm.sh"; then app=$LWE_APP_DEB; else app=$LWE_APP_DIR; fi
+[ -n "$LWE_CANDIDATE" ] && [ -n "$LWE_ENGINE_TARBALL" ] && [ -n "$app" ] || { echo "LWE_CANDIDATE, LWE_ENGINE_TARBALL and the app of this profile's kind are required"; exit 2; }
+
+mkdir -p "$out"
+lv fresh "$vm" >/dev/null 2>&1
+lv start "$vm" >/dev/null 2>&1
+for _ in $(seq 60); do sshv true 2>/dev/null && break; sleep 5; done
+lv scp "$vm" "$ext" dbg-extension.js >/dev/null 2>&1
+sshv "cp ~/dbg-extension.js ~/.local/share/gnome-shell/extensions/$uuid/extension.js"
+sshv 'sync; sudo systemctl poweroff' >/dev/null 2>&1
+sleep 25
+lv stop "$vm" >/dev/null 2>&1
+sleep 5
+
+KEEP_VM=1 REPORT_DIR=$out "$HERE/release_check.sh" --vm "$vm" --no-overlay --candidate "$LWE_CANDIDATE" --app "$app" \
+    --engine-tarball "$LWE_ENGINE_TARBALL" > "$out.out" 2>&1
+sshv "journalctl -b --no-pager -o short-monotonic 2>/dev/null | grep -E 'LWE-DBG|stack_position|Buggy client'" > "$out/shell-debug.log" 2>&1
+lv shot "$vm" "$out/final.png" >/dev/null 2>&1
+sshv 'sudo systemctl poweroff' >/dev/null 2>&1
+sleep 20
+lv stop "$vm" >/dev/null 2>&1
+lv fresh "$vm" >/dev/null 2>&1
+echo "$(date +%T) $vm $tag: $(grep -c . "$out/shell-debug.log") debug lines, $(grep -c '^FAIL' "$out/$vm/checks.txt") FAIL, $(grep -c 'hiding orphan' "$out/shell-debug.log") orphans hidden" >> "$root/runs.log"

+ 201 - 7
tools/linuxvm/guest_test.sh

@@ -8,7 +8,12 @@
 #                 host asks the host instead (COSMIC's portal asks for permission on every call): the script creates
 #                 $SHOT_FILE.want and waits for $SHOT_FILE, host_shots.sh takes the picture through the VM's display
 #   WALLPAPERS    ids to run, default: scene with parallax, scene with particles, two web items
-#   SETTLE        seconds to wait for the first frames (default 25)
+#   SETTLE        seconds to wait for the first frames (default 25), the checks that do not compare frames at a fixed time
+#                 go on as soon as the engine says it draws (a few seconds more, web pages need longer)
+#   ONLY          space separated check groups to run (wallpapers behavior video cycle automute multi), default all
+#   MINIMIZE_CMD  minimizes the test window (X11): the engine paused by a fullscreen window must resume once it is hidden
+#   MULTI_SHOT_CMD  screenshot command that captures every monitor (the VM was started with a second output): turns on
+#                 the multi monitor check, the wallpaper must show on both screens
 # resolved: the engine's command line shows the real path (/var/home on Fedora Atomic systems)
 LWE_DIR=$(realpath "${LWE_DIR:-$HOME/lwe}")
 ENGINE=$LWE_DIR/lwe-hints/linux-wallpaperengine
@@ -19,6 +24,18 @@ mkdir -p "$OUT"
 rm -f "$OUT/done"
 status=0
 
+want() { [ -z "$ONLY" ] || [[ " $ONLY " == *" $1 "* ]]; }
+
+settle() {
+    local log=$1 id=$2 extra=6 waited=0 rest
+    if grep -qi '"type"[[:space:]]*:[[:space:]]*"web"' "$LWE_DIR/wp-$id/project.json" 2>/dev/null; then extra=16; fi
+    while [ "$waited" -lt "$SETTLE" ] && ! grep -q "drawing at scale" "$log" 2>/dev/null; do sleep 1; waited=$((waited + 1)); done
+    rest=$((SETTLE - waited))
+    [ "$rest" -gt "$extra" ] && rest=$extra
+    [ "$rest" -gt 0 ] && sleep "$rest"
+    return 0
+}
+
 pass() { echo "PASS $1"; }
 fail() { echo "FAIL $1"; status=1; }
 engine_pids() { pgrep -f "^$LWE_DIR/lwe-hints/linux-wallpaperengine.[b]in"; }
@@ -40,6 +57,8 @@ stop_engine() {
 }
 
 stop_engine
+total=0 bad_start=0
+if want wallpapers; then
 # the desktop without a wallpaper, the reference check_frame.py compares the others to
 sleep 2
 SHOT_FILE=$OUT/baseline.png
@@ -53,9 +72,10 @@ for id in $WALLPAPERS; do
     log=$OUT/engine-$id.log
     # shellcheck disable=SC2086
     (setsid nohup "$ENGINE" --assets-dir "$LWE_DIR/assets" $LWE_ARGS "$dir" > "$log" 2>&1 < /dev/null &)
-    sleep "$SETTLE"
+    settle "$log" "$id"
 
-    if engine_pids >/dev/null; then pass "$id: engine running after ${SETTLE}s"; else fail "$id: engine exited"; fi
+    total=$((total + 1))
+    if engine_pids >/dev/null; then pass "$id: engine running"; else fail "$id: engine exited"; bad_start=$((bad_start + 1)); fi
     if grep -qiE "segmentation|SIGSEGV|terminate called|Aborted|core dumped" "$log"; then fail "$id: crash text in the log"; else pass "$id: no crash text in the log"; fi
 
     SHOT_FILE=$OUT/shot-$id.png
@@ -66,6 +86,12 @@ for id in $WALLPAPERS; do
     if stop_engine; then pass "$id: engine stopped on SIGTERM"; else fail "$id: engine needed SIGKILL"; fi
     if pgrep -f "[l]inux-wallpaperengine-web-helper" >/dev/null; then fail "$id: web helper left behind"; else pass "$id: no web helper left behind"; fi
 done
+    if [ "$total" -gt 0 ] && [ "$bad_start" -eq "$total" ]; then
+        echo "FATAL: the engine did not stay running on any of the $total wallpapers, the other checks are skipped"
+        touch "$OUT/done"; exit 1
+    fi
+fi
+
 # the test window's own command line is the pattern: toolkits start helpers and detach, the shell's pid is not enough
 stop_fullscreen_window() {
     [ -n "$STOP_CMD" ] && pkill -f -- "^${STOP_CMD%% *}.*${STOP_CMD#* }" 2>/dev/null
@@ -104,8 +130,20 @@ pause_check() {
         echo "SKIP $label pause: the compositor has no window state detection"
     elif wait_for_log "$log" "Paused: windows" 45 "$paused_before"; then
         pass "$label pause: engine paused"
+        local minimized_resumed=0
+        if [ "$label" = fullscreen ] && [ -n "$MINIMIZE_CMD" ]; then
+            if command -v xdotool >/dev/null; then
+                eval "$MINIMIZE_CMD" > "$OUT/minimize.log" 2>&1
+                if wait_for_log "$log" "Resumed" 20 "$resumed_before"; then pass "$label pause: engine resumed once the window was minimized"; minimized_resumed=1
+                else fail "$label pause: still paused with the window minimized"; fi
+                resumed_before=$(grep -c "Resumed" "$log")
+            else
+                echo "SKIP $label pause: no xdotool to minimize the window"
+            fi
+        fi
         kill "$fs_pid" 2>/dev/null; stop_fullscreen_window
-        if wait_for_log "$log" "Resumed" 45 "$resumed_before"; then pass "$label pause: engine resumed"; else fail "$label pause: no resume after the window closed"; fi
+        if [ $minimized_resumed = 1 ]; then :
+        elif wait_for_log "$log" "Resumed" 45 "$resumed_before"; then pass "$label pause: engine resumed"; else fail "$label pause: no resume after the window closed"; fi
     else
         fail "$label pause: no pause within 45s of a $label window"
         {
@@ -131,15 +169,164 @@ pause_check() {
     sleep 3
 }
 
+hotswap_video_check() {
+    local A=3471294034 B=3818199837 ctl=$OUT/control-video pid
+    if [ ! -d "$LWE_DIR/wp-$A" ] || [ ! -d "$LWE_DIR/wp-$B" ]; then echo "SKIP hotswap video: wallpapers $A and $B missing"; return; fi
+    : > "$ctl"
+    # shellcheck disable=SC2086
+    (setsid nohup "$ENGINE" --assets-dir "$LWE_DIR/assets" $LWE_ARGS --control-file "$ctl" "$LWE_DIR/wp-$A" > "$OUT/engine-swapvideo.log" 2>&1 < /dev/null &)
+    sleep "$SETTLE"
+    pid=$(engine_pids | head -1)
+    if [ -z "$pid" ]; then fail "hotswap video: engine did not start"; return; fi
+    echo "path=$LWE_DIR/wp-$B" > "$ctl"
+    kill -USR1 "$pid"
+    sleep 20
+    SHOT_FILE=$OUT/swap-video.png; rm -f "$SHOT_FILE"; take_shot "$SHOT_FILE" "$OUT/swap-video.log"
+    stop_engine
+    # shellcheck disable=SC2086
+    (setsid nohup "$ENGINE" --assets-dir "$LWE_DIR/assets" $LWE_ARGS "$LWE_DIR/wp-$B" > "$OUT/engine-freshvideo.log" 2>&1 < /dev/null &)
+    sleep "$SETTLE"
+    SHOT_FILE=$OUT/fresh-video.png; rm -f "$SHOT_FILE"; take_shot "$SHOT_FILE" "$OUT/fresh-video.log"
+    stop_engine
+}
+
+peak_in() { awk -v a="$1" -v b="$2" '$1 >= a && $1 < b && $2 > m { m = $2 } END { print m + 0 }' "$OUT/audio-timeline.txt"; }
+
+automute_check() {
+    local id=3471294034 win_pid="" base muted back pmuted pback
+    if [ ! -d "$LWE_DIR/wp-$id" ]; then echo "SKIP automute: wallpaper $id missing"; return; fi
+    if ! command -v parec >/dev/null || ! command -v paplay >/dev/null || ! pactl info >/dev/null 2>&1; then
+        echo "SKIP automute: no pulse tools or server in this guest"; return
+    fi
+    cat > "$OUT/peak.py" <<'PY'
+import struct, subprocess, sys, time
+p = subprocess.Popen(["parec", "-d", "@DEFAULT_SINK@.monitor", "--format=s16le", "--rate=8000", "--channels=1",
+                      "--latency-msec=50"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
+t0 = time.time()
+while time.time() - t0 < float(sys.argv[1]):
+    d = p.stdout.read(800)
+    if not d:
+        break
+    s = struct.unpack("<%dh" % (len(d) // 2), d)
+    print("%.1f %d" % (time.time() - t0, max(abs(x) for x in s)), flush=True)
+p.kill()
+PY
+    python3 -c "
+import wave
+w = wave.open('$OUT/silence.wav', 'w'); w.setnchannels(2); w.setsampwidth(2); w.setframerate(44100)
+w.writeframes(b'\0' * 44100 * 4 * 12); w.close()"
+    # shellcheck disable=SC2086
+    (setsid nohup "$ENGINE" --assets-dir "$LWE_DIR/assets" $LWE_ARGS --automute "$LWE_DIR/wp-$id" > "$OUT/engine-automute.log" 2>&1 < /dev/null &)
+    sleep "$SETTLE"
+    python3 "$OUT/peak.py" 48 > "$OUT/audio-timeline.txt" 2>/dev/null &
+    local mon=$!
+    sleep 5
+    paplay "$OUT/silence.wav" &
+    sleep 17
+    if [ -n "$FULLSCREEN_CMD" ]; then
+        STOP_CMD=$FULLSCREEN_CMD; stop_fullscreen_window
+        eval "$FULLSCREEN_CMD" > "$OUT/automute-window.log" 2>&1 &
+        win_pid=$!
+        sleep 8
+        paplay "$OUT/silence.wav" &
+        sleep 18
+    else
+        sleep 26
+    fi
+    wait "$mon" 2>/dev/null
+    # a fullscreen window counts as sound for automute, the other app stopping can only be seen once the window is gone
+    kill "$win_pid" 2>/dev/null; stop_fullscreen_window; sleep 4; stop_engine
+    pkill -x paplay 2>/dev/null
+    base=$(peak_in 1 5)
+    if [ "$base" -lt 50 ]; then echo "SKIP automute: the wallpaper's music is not audible on this guest's default sink (peak $base)"; return; fi
+    muted=$(peak_in 8 16); back=$(peak_in 18 22)
+    if [ "$muted" -le 30 ]; then pass "automute: muted while another app plays (peak $muted, $base before)"; else fail "automute: not muted while another app plays (peak $muted)"; fi
+    if [ "$back" -gt $((base / 4)) ]; then pass "automute: music back within 5s of the other app stopping (peak $back)"; else fail "automute: music not back 1.5-5s after the other app stopped (peak $back)"; fi
+    if [ -n "$FULLSCREEN_CMD" ]; then
+        # the scene's own music is silent while the wallpaper is paused, so what is checked is the engine's state: the log
+        # lines of the second player come while the "Paused: windows" state holds
+        local log=$OUT/engine-automute.log paused_line started stopped
+        paused_line=$(grep -n "Paused: windows" "$log" | head -1 | cut -d: -f1)
+        started=$(grep -n "Automute: another app is playing" "$log" | tail -1 | cut -d: -f1)
+        stopped=$(grep -n "Automute: other apps stopped" "$log" | tail -1 | cut -d: -f1)
+        if [ -z "$paused_line" ]; then echo "SKIP automute while paused: the engine was not paused by the window"
+        elif [ "$(grep -c "Automute: another app is playing" "$log")" -ge 2 ] && [ "$started" -gt "$paused_line" ]; then pass "automute: another app's sound noticed while the wallpaper is paused"
+        else fail "automute: another app's sound not noticed while the wallpaper is paused"; fi
+        if [ -n "$paused_line" ] && [ -n "$stopped" ] && [ "$stopped" -gt "$started" ]; then pass "automute: the other app stopping noticed while the wallpaper is paused"
+        else fail "automute: the other app stopping not noticed while the wallpaper is paused"; fi
+    fi
+}
+
+hotswap_cycle_check() {
+    local order="1120596121 1367456719 1078208425 1111948150 834237690 1367456719 1120596121"
+    local ctl=$OUT/control-cycle log=$OUT/engine-cycle.log id pid n=0 swaps type helpers bad bad_before wait_s
+    for id in $order; do
+        if [ ! -d "$LWE_DIR/wp-$id" ]; then echo "SKIP hotswap cycle: wallpaper $id missing"; return; fi
+    done
+    : > "$ctl"
+    # shellcheck disable=SC2086
+    (setsid nohup "$ENGINE" --assets-dir "$LWE_DIR/assets" $LWE_ARGS --control-file "$ctl" "$LWE_DIR/wp-${order%% *}" > "$log" 2>&1 < /dev/null &)
+    settle "$log" "${order%% *}"
+    pid=$(engine_pids | head -1)
+    if [ -z "$pid" ]; then fail "hotswap cycle: engine did not start"; return; fi
+    for id in ${order#* }; do
+        n=$((n + 1))
+        if grep -qi '"type"[[:space:]]*:[[:space:]]*"web"' "$LWE_DIR/wp-$id/project.json"; then type=web; wait_s=20
+        elif grep -qi '"type"[[:space:]]*:[[:space:]]*"video"' "$LWE_DIR/wp-$id/project.json"; then type=video; wait_s=12
+        else type=scene; wait_s=12; fi
+        swaps=$(grep -c "Hotswapping wallpaper to" "$log")
+        bad_before=$(grep -ciE "terminate called|segmentation|fatal|exception" "$log")
+        echo "path=$LWE_DIR/wp-$id" > "$ctl"
+        kill -USR1 "$pid"
+        for _ in $(seq 40); do [ "$(grep -c "Hotswapping wallpaper to" "$log")" -gt "$swaps" ] && break; sleep 0.5; done
+        sleep "$wait_s"
+        if ! kill -0 "$pid" 2>/dev/null; then fail "hotswap cycle step $n ($type $id): the engine exited"; return; fi
+        if [ "$(grep -c "Hotswapping wallpaper to" "$log")" -le "$swaps" ]; then fail "hotswap cycle step $n ($type $id): no hotswap in the log"; stop_engine; return; fi
+        helpers=$(pgrep -fc "[l]inux-wallpaperengine-web-helper")
+        if [ "$type" = web ] && [ "$helpers" -eq 0 ]; then fail "hotswap cycle step $n ($type $id): no web host is running"; stop_engine; return; fi
+        if [ "$type" != web ] && [ "$helpers" -gt 0 ]; then sleep 8; helpers=$(pgrep -fc "[l]inux-wallpaperengine-web-helper")
+            if [ "$helpers" -gt 0 ]; then fail "hotswap cycle step $n ($type $id): $helpers web host processes left behind"; stop_engine; return; fi
+        fi
+        bad=$(grep -ciE "terminate called|segmentation|fatal|exception" "$log")
+        if [ "$bad" -gt "$bad_before" ]; then fail "hotswap cycle step $n ($type $id): $((bad - bad_before)) new error lines in the log"; stop_engine; return; fi
+        SHOT_FILE=$OUT/shot-cycle-$n-$id.png; rm -f "$SHOT_FILE"; take_shot "$SHOT_FILE" "$OUT/cycle-$n.log"
+        pass "hotswap cycle step $n: $type $id"
+    done
+    stop_engine
+}
+
+multi_monitor_check() {
+    local id=1111948150 w1 w2
+    [ -n "$MULTI_SHOT_CMD" ] || return
+    if ! command -v xrandr >/dev/null; then echo "SKIP multi monitor: no xrandr"; return; fi
+    for f in /sys/class/drm/card*-Virtual-2/status; do echo on | sudo tee "$f" >/dev/null 2>&1; done
+    sleep 2
+    w1=$(xrandr | sed -n 's/^Virtual-1 connected[^0-9]*\([0-9]*\)x[0-9]*+.*/\1/p' | head -1)
+    if [ -z "$w1" ] || ! xrandr | grep -q '^Virtual-2 connected'; then echo "SKIP multi monitor: the guest has no second output"; return; fi
+    xrandr --output Virtual-1 --auto --pos 0x0 --output Virtual-2 --auto --pos "${w1}x0"
+    sleep 4
+    w2=$(xrandr | sed -n 's/^Virtual-2 connected[^0-9]*\([0-9]*\)x[0-9]*+.*/\1/p' | head -1)
+    echo "$w1 $w2" > "$OUT/multi-geometry"
+    SHOT_FILE=$OUT/multi-baseline.png; rm -f "$SHOT_FILE"; eval "$MULTI_SHOT_CMD" > "$OUT/multi-baseline.log" 2>&1
+    # shellcheck disable=SC2086
+    (setsid nohup "$ENGINE" --assets-dir "$LWE_DIR/assets" --screen-root Virtual-1 --screen-root Virtual-2 "$LWE_DIR/wp-$id" > "$OUT/engine-multi.log" 2>&1 < /dev/null &)
+    settle "$OUT/engine-multi.log" "$id"
+    if engine_pids >/dev/null; then pass "multi monitor: engine running on two screens"; else fail "multi monitor: engine exited"; fi
+    SHOT_FILE=$OUT/multi-shot.png; rm -f "$SHOT_FILE"; eval "$MULTI_SHOT_CMD" > "$OUT/multi-shot.log" 2>&1
+    if [ -s "$SHOT_FILE" ] && [ -s "$OUT/multi-baseline.png" ]; then pass "multi monitor: screenshots of both screens taken"; else fail "multi monitor: no screenshot ($(head -c 120 "$OUT/multi-shot.log" | tr '\n' ' '))"; fi
+    stop_engine
+    xrandr --output Virtual-2 --off
+}
+
 # behaviour checks, BEHAVIOR=1: hotswap, pause on fullscreen, SIGKILL leaves no helper
-if [ "${BEHAVIOR:-0}" = 1 ]; then
+if [ "${BEHAVIOR:-0}" = 1 ] && want behavior; then
     A=${HOTSWAP_FROM:-1120596121}
     B=${HOTSWAP_TO:-1111948150}
     ctl=$OUT/control
     : > "$ctl"
     # shellcheck disable=SC2086
     (setsid nohup "$ENGINE" --assets-dir "$LWE_DIR/assets" $LWE_ARGS --control-file "$ctl" "$LWE_DIR/wp-$A" > "$OUT/engine-behavior.log" 2>&1 < /dev/null &)
-    sleep "$SETTLE"
+    settle "$OUT/engine-behavior.log" "$A"
     pid=$(engine_pids | head -1)
     if [ -z "$pid" ]; then fail "behavior: engine did not start"; else
         SHOT_FILE=$OUT/hot-before.png; rm -f "$SHOT_FILE"; take_shot "$SHOT_FILE" "$OUT/hot-before.log"
@@ -160,7 +347,7 @@ if [ "${BEHAVIOR:-0}" = 1 ]; then
     # SIGKILL: the web host must not outlive the engine
     # shellcheck disable=SC2086
     (setsid nohup "$ENGINE" --assets-dir "$LWE_DIR/assets" $LWE_ARGS "$LWE_DIR/wp-1078208425" > "$OUT/engine-kill.log" 2>&1 < /dev/null &)
-    sleep "$SETTLE"
+    settle "$OUT/engine-kill.log" 1078208425
     pid=$(engine_pids | head -1)
     helpers_before=$(pgrep -fc "[l]inux-wallpaperengine-web-helper")
     kill -9 "$pid" 2>/dev/null
@@ -171,5 +358,12 @@ if [ "${BEHAVIOR:-0}" = 1 ]; then
     else fail "SIGKILL: $helpers_after of $helpers_before web host processes left behind"; pkill -f "linux-wallpaperengine-web-helper"; fi
 fi
 
+if [ "${BEHAVIOR:-0}" = 1 ]; then
+    want video && hotswap_video_check
+    want cycle && hotswap_cycle_check
+    want automute && automute_check
+    want multi && multi_monitor_check
+fi
+
 touch "$OUT/done"
 exit $status

+ 59 - 0
tools/linuxvm/hover_check.py

@@ -0,0 +1,59 @@
+#!/usr/bin/env python3
+"""hover_check.py <pointer on Mon.png> <pointer on Sun.png> [<pointer on the dock.png> <pointer at the top.png>] - the calendar of workshop item 3599498791 enlarges the weekday
+under the pointer (its hover zones are cursorEnter scripts, the engine's cursor hit test). With the pointer on the Monday row
+the big label has to be the Monday one, with it on the Sunday row the Sunday one; the big label has about four times the
+bright pixels of a small one. The optional pair checks the dock, which magnifies the icons next to the pointer (that one follows
+the scripts' cursor world position): the icons 04 and 05 rise above the dock bar with the pointer on it and stay flat with the
+pointer at the top. Prints PASS or FAIL lines like check_frame.py. Screenshots are 1920x1080, the crops scale."""
+import sys
+
+from PIL import Image
+
+
+def zones(path):
+    """bright pixels in the narrow column of the Monday label and of the Sunday label"""
+    image = Image.open(path).convert("L")
+    sx, sy = image.width / 1920, image.height / 1080
+    pixels = image.load()
+
+    def count(y0, y1):
+        return sum(
+            1
+            for y in range(int(y0 * sy), int(y1 * sy))
+            for x in range(int(668 * sx), int(736 * sx))
+            if pixels[x, y] >= 200
+        )
+
+    return count(440, 468), count(610, 642)
+
+
+def dock_rise(path):
+    """bright pixels just above the dock bar over the icons 04 and 05"""
+    image = Image.open(path).convert("L")
+    sx, sy = image.width / 1920, image.height / 1080
+    pixels = image.load()
+    return sum(
+        1
+        for y in range(int(900 * sy), int(931 * sy))
+        for x in range(int(860 * sx), int(1061 * sx))
+        if pixels[x, y] >= 200
+    )
+
+
+def main():
+    mon_zone, sun_zone = zones(sys.argv[1])[0], zones(sys.argv[2])[1]
+    mon_other, sun_other = zones(sys.argv[1])[1], zones(sys.argv[2])[0]
+    ok_mon = mon_zone > 120 and mon_zone > 2 * mon_other
+    ok_sun = sun_zone > 120 and sun_zone > 2 * sun_other
+    print(("PASS" if ok_mon else "FAIL"), f"weekday hover: pointer on Monday, big label bright pixels Monday/Sunday {mon_zone}/{mon_other}")
+    print(("PASS" if ok_sun else "FAIL"), f"weekday hover: pointer on Sunday, big label bright pixels Sunday/Monday {sun_zone}/{sun_other}")
+    ok_dock = True
+    if len(sys.argv) >= 5:
+        near, far = dock_rise(sys.argv[3]), dock_rise(sys.argv[4])
+        ok_dock = near > 300 and far < 60
+        print(("PASS" if ok_dock else "FAIL"), f"dock zoom: bright pixels above the bar with the pointer on the dock/at the top {near}/{far}")
+    return 0 if ok_mon and ok_sun and ok_dock else 1
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 2 - 2
tools/linuxvm/linuxvm.sh

@@ -10,7 +10,7 @@
 #                         opensuse-tumbleweed, opensuse-leap-16), 60G overlay
 #   create-iso <vm> <iso> blank 60G disk that boots images/<iso>.iso (a distro installer, e.g. linuxmint-22.3-cinnamon);
 #                         remove <vm>/boot.iso after installing. Such a VM has no cloud-init, ssh needs setting up by hand
-#   start <vm>            boots it (LINUXVM_CPUS, LINUXVM_MEM, LINUXVM_SIZE=WxH for the display)
+#   start <vm>            boots it (LINUXVM_CPUS, LINUXVM_MEM, LINUXVM_SIZE=WxH for the display); LINUXVM_OUTPUTS=2 gives the guest a second monitor (Virtual-2, enable it with xrandr)
 #   desktop <vm>          boots it in a window on the container's display (GTK, GL, host PipeWire audio, shared
 #                         clipboard with spice-vdagent in the guest) to use it like a normal desktop; same as
 #                         LINUXVM_DISPLAY=window start. Stop a headless run of the VM first
@@ -140,7 +140,7 @@ start)
         $([ -f "$dir/seed.iso" ] && echo -drive file="$dir/seed.iso",media=cdrom,if=none,id=seed,readonly=on -device ide-cd,drive=seed) \
         $([ -e "$dir/boot.iso" ] && echo -drive file="$dir/boot.iso",media=cdrom,if=none,id=boot,readonly=on -device ide-cd,drive=boot,bootindex=1) \
         -nic user,model=virtio-net-pci,hostfwd=tcp:127.0.0.1:"$(port "$vm")"-:22 \
-        -device virtio-vga-gl,xres="${size%x*}",yres="${size#*x}" \
+        -device virtio-vga-gl,xres="${size%x*}",yres="${size#*x}",max_outputs="${LINUXVM_OUTPUTS:-1}" \
         "${display[@]}" "${extra[@]}" \
         -device qemu-xhci -device usb-tablet \
         $([ -f "$dir/qemu-extra" ] && cat "$dir/qemu-extra") \

+ 13 - 2
tools/linuxvm/maximize_kde.sh

@@ -7,9 +7,20 @@ trap 'kill $terminal 2>/dev/null' EXIT
 sleep 4
 script=$(mktemp /tmp/lwe-maximize-XXXXXX.js)
 echo 'workspace.activeWindow.setMaximize(true, true);' > "$script"
-id=$(gdbus call --session --dest org.kde.KWin --object-path /Scripting --method org.kde.kwin.Scripting.loadScript "$script" lwe-maximize-test | tr -dc '0-9')
+# KWin 6.4 hands a new script the id of a loaded one after any script was unloaded (it numbers by count), "run" then
+# starts that one again: load under more names until the id is a free one
+live=$(gdbus introspect --session --dest org.kde.KWin --object-path /Scripting | grep -o 'node Script[0-9]*' | tr -dc '0-9\n')
+names=()
+for attempt in 0 1 2 3; do
+    name=lwe-maximize-test-$attempt
+    id=$(gdbus call --session --dest org.kde.KWin --object-path /Scripting --method org.kde.kwin.Scripting.loadScript "$script" "$name" | tr -dc '0-9')
+    names+=("$name")
+    echo "$live" | grep -qx "$id" || break
+done
 gdbus call --session --dest org.kde.KWin --object-path "/Scripting/Script$id" --method org.kde.kwin.Script.run >/dev/null
 sleep 2
-gdbus call --session --dest org.kde.KWin --object-path /Scripting --method org.kde.kwin.Scripting.unloadScript lwe-maximize-test >/dev/null
+for name in "${names[@]}"; do
+    gdbus call --session --dest org.kde.KWin --object-path /Scripting --method org.kde.kwin.Scripting.unloadScript "$name" >/dev/null
+done
 rm -f "$script"
 wait $terminal

+ 36 - 0
tools/linuxvm/pointer_check.sh

@@ -0,0 +1,36 @@
+#!/bin/bash
+# pointer_check.sh <vm> [screen] [shot dir] - which way does the pointer's y go on this VM's output? Runs workshop item
+# 3599498791 (its calendar enlarges the weekday under the pointer, hover zones driven by the engine's cursor hit test), puts the
+# pointer on the Monday row and on the Sunday row of the calendar and checks the enlarged label with hover_check.py, and with the pointer on the dock and at the top that the dock icons magnify (the scripts' cursor world position). The two
+# screenshots stay in <shot dir> (default /tmp/pointer-check-<vm>). Prints PASS|FAIL lines.
+# Needs the VM running with the session up (sessenv), the wallpaper and the engine in ~/lwe (prep_guest.sh, release_check.sh),
+# a 1920x1080 display, and the pointer reachable through QMP (usb-tablet).
+HERE=$(cd "$(dirname "$0")" && pwd)
+vm=$1 screen=${2:-Virtual-1} out=${3:-/tmp/pointer-check-$vm}
+mkdir -p "$out"
+lv() { "$HERE/linuxvm.sh" "$@"; }
+sshv() { lv ssh "$vm" "$@" </dev/null; }
+if ! sshv '[ -d ~/lwe/wp-3599498791 ]'; then lv scp "$vm" "${LINUXVM:-$HOME/.local/share/linuxvm}/payload/wp-3599498791" lwe/; fi
+sshv 'pkill -f "[l]inux-wallpaperengine.bin"; pkill -x we-manager; true'
+sshv 'pkill -f "[x]fce4-display-settings"; pkill -f "[u]pdate-manager"; pkill -f "[r]elease-upgrader"; pkill -f "[u]pdate-notifier"; pkill -x cachyos-hello; pkill -f "[e]os-welcome|[m]x-welcome|[g]aruda-welcome|[m]anjaro-hello|[m]int-welcome|[z]orin-welcome|[p]op-welcome|[m]intupdate|[m]intUpdate|[m]intreport|[m]intwelcome"; true'
+# SteamOS starts Steam's sign-in window at login
+sshv 'pkill -x steam; pkill -f "[s]teamwebhelper"; true'
+sshv ". ~/sessenv; (setsid ${WEM_LAUNCH:-} nohup ~/lwe/lwe-hints/linux-wallpaperengine --assets-dir ~/lwe/assets $LWE_ARGS_EXTRA --screen-root $screen ~/lwe/wp-3599498791 > /tmp/pointer-check.log 2>&1 < /dev/null &)"
+for _ in $(seq 60); do sshv 'grep -q "drawing at scale" /tmp/pointer-check.log' && break; sleep 2; done
+sleep 30
+# welcome apps start late on some distributions, once more now that the engine runs
+sshv 'pkill -f "[x]fce4-display-settings"; pkill -f "[u]pdate-manager"; pkill -f "[r]elease-upgrader"; pkill -f "[u]pdate-notifier"; pkill -x cachyos-hello; pkill -f "[e]os-welcome|[m]x-welcome|[g]aruda-welcome|[m]anjaro-hello|[m]int-welcome|[z]orin-welcome|[p]op-welcome|[m]intupdate|[m]intUpdate|[m]intreport|[m]intwelcome"; true'
+# a welcome window that survives its process name (EndeavourOS): close it by title
+sshv '. ~/sessenv; wmctrl -c "Welcome" 2>/dev/null; wmctrl -c "Plugin loading failure" 2>/dev/null; for w in $(xdotool search --name "^Welcome" 2>/dev/null); do xdotool windowclose $w; done; true'
+if ! sshv 'pgrep -f "[l]inux-wallpaperengine.bin" >/dev/null'; then echo "FAIL weekday hover: the engine did not stay running on 3599498791"; exit 1; fi
+for spot in mon:713,451 sun:714,625 dock:960,1010 top:960,60; do
+    name=${spot%%:*} xy=${spot#*:}
+    sshv '. ~/sessenv; wmctrl -c "Welcome" 2>/dev/null; wmctrl -c "Plugin loading failure" 2>/dev/null; for w in $(xdotool search --name "^Welcome" 2>/dev/null); do xdotool windowclose $w; done; true'
+    lv pointer "$vm" "${xy%,*}" "${xy#*,}" >/dev/null 2>&1
+    sleep 1
+    lv pointer "$vm" "$(( ${xy%,*} + 2 ))" "$(( ${xy#*,} + 1 ))" >/dev/null 2>&1
+    sleep 10
+    lv shot "$vm" "$out/hover-$name.png"
+done
+sshv 'pkill -f "[l]inux-wallpaperengine.bin"; true'
+python3 -I "$HERE/hover_check.py" "$out/hover-mon.png" "$out/hover-sun.png" "$out/hover-dock.png" "$out/hover-top.png"

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

@@ -0,0 +1,6 @@
+VM=arch-hypr
+SCREEN=Virtual-1
+SHOT_CMD='grim $SHOT_FILE'
+FULLSCREEN_CMD='kitty --start-as=fullscreen'
+WEM=app
+PREP='(setsid nohup systemd-inhibit --what=idle:sleep --who=lwe-test --why=test sleep 100000 >/dev/null 2>&1 &)'

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

@@ -4,3 +4,6 @@ SHOT_CMD=host
 FULLSCREEN_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,fullscreen; wait"'
 WEM=app
 PREP='xset s off -dpms; pkill -f "[x]fce4-screensaver"; pkill -f "[x]fce4-power-manager"; true'
+MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'
+MULTI=1
+MULTI_SHOT_CMD='xfce4-screenshooter -f -s $SHOT_FILE'

+ 8 - 0
tools/linuxvm/profiles/cachyos-hypr.sh

@@ -0,0 +1,8 @@
+VM=cachyos-hypr
+SCREEN=Virtual-1
+SHOT_CMD='grim $SHOT_FILE'
+FULLSCREEN_CMD='kitty --start-as=fullscreen'
+WEM=app
+PREP='pkill -x cachyos-hello; pkill -x gcr-prompter; (setsid nohup systemd-inhibit --what=idle:sleep --who=lwe-test --why=test sleep 100000 >/dev/null 2>&1 &)'
+# Hyprland: layer shell, maximized windows do not pause by default (wlroots rule), so no MAXIMIZE_CMD
+# the CachyOS Hello window and the keyring prompt open on every login and tile over the whole screen: PREP closes them

+ 1 - 1
tools/linuxvm/profiles/cachyos-kde.sh

@@ -4,4 +4,4 @@ SHOT_CMD=host
 FULLSCREEN_CMD='konsole --fullscreen'
 MAXIMIZE_CMD='~/lwe/maximize_kde.sh'
 WEM=app
-PREP='(setsid nohup kde-inhibit --power --screenSaver sleep 100000 >/dev/null 2>&1 &)'
+PREP='pkill -x cachyos-hello; (setsid nohup kde-inhibit --power --screenSaver sleep 100000 >/dev/null 2>&1 &)'

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

@@ -4,3 +4,6 @@ SHOT_CMD=host
 FULLSCREEN_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,fullscreen; wait"'
 WEM=deb
 PREP='xset s off -dpms; pkill -f "[x]fce4-screensaver"; pkill -f "[x]fce4-power-manager"; true'
+MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'
+MULTI=1
+MULTI_SHOT_CMD='xfce4-screenshooter -f -s $SHOT_FILE'

+ 6 - 0
tools/linuxvm/profiles/elementary.sh

@@ -0,0 +1,6 @@
+VM=elementary
+SCREEN=Virtual-1
+SHOT_CMD=host
+FULLSCREEN_CMD='python3 ~/lwe/fullscreen_window.py'
+MAXIMIZE_CMD='python3 ~/lwe/fullscreen_window.py maximize'
+WEM=deb

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

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

+ 7 - 0
tools/linuxvm/profiles/endeavouros.sh

@@ -0,0 +1,7 @@
+VM=endeavouros
+SCREEN=Virtual-1
+SHOT_CMD=host
+FULLSCREEN_CMD='konsole --fullscreen'
+MAXIMIZE_CMD='~/lwe/maximize_kde.sh'
+WEM=app
+PREP='(setsid nohup kde-inhibit --power --screenSaver sleep 100000 >/dev/null 2>&1 &)'

+ 7 - 0
tools/linuxvm/profiles/garuda-kde.sh

@@ -0,0 +1,7 @@
+VM=garuda-kde
+SCREEN=Virtual-1
+SHOT_CMD=host
+FULLSCREEN_CMD='konsole --fullscreen'
+MAXIMIZE_CMD='~/lwe/maximize_kde.sh'
+WEM=app
+PREP='(setsid nohup kde-inhibit --power --screenSaver sleep 100000 >/dev/null 2>&1 &)'

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

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

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

@@ -0,0 +1,9 @@
+VM=mint-cinnamon
+SCREEN=Virtual-1
+SHOT_CMD='gnome-screenshot -f $SHOT_FILE'
+FULLSCREEN_CMD='python3 ~/lwe/fullscreen_window.py'
+WEM=deb
+MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'
+MULTI=1
+MULTI_SHOT_CMD='gnome-screenshot -f $SHOT_FILE'
+PREP='pkill -f "[m]intupdate"; pkill -x mintreport; true'

+ 9 - 0
tools/linuxvm/profiles/mint22-2.sh

@@ -0,0 +1,9 @@
+VM=mint22-2
+SCREEN=Virtual-1
+SHOT_CMD='gnome-screenshot -f $SHOT_FILE'
+FULLSCREEN_CMD='python3 ~/lwe/fullscreen_window.py'
+WEM=deb
+MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'
+MULTI=1
+MULTI_SHOT_CMD='gnome-screenshot -f $SHOT_FILE'
+PREP='pkill -f "[m]intupdate"; pkill -x mintreport; true'

+ 9 - 0
tools/linuxvm/profiles/mx-xfce.sh

@@ -0,0 +1,9 @@
+VM=mx-xfce
+SCREEN=Virtual-1
+SHOT_CMD=host
+FULLSCREEN_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,fullscreen; wait"'
+WEM=deb
+PREP='pkill -f "[m]x-welcome"; xset s off -dpms; pkill -f "[x]fce4-screensaver"; pkill -f "[x]fce4-power-manager"; true'
+MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'
+MULTI=1
+MULTI_SHOT_CMD='xfce4-screenshooter -f -s $SHOT_FILE'

+ 3 - 0
tools/linuxvm/profiles/opensuse-xfce.sh

@@ -4,3 +4,6 @@ SHOT_CMD=host
 FULLSCREEN_CMD='bash -c "xterm -T lwe-fullscreen-test -e sleep 100000 & sleep 2; wmctrl -r lwe-fullscreen-test -b add,fullscreen; wait"'
 WEM=app
 PREP='xset s off -dpms; pkill -f "[x]fce4-screensaver"; pkill -f "[x]fce4-power-manager"; true'
+MINIMIZE_CMD='xdotool search --name lwe-fullscreen-test windowminimize %@'
+MULTI=1
+MULTI_SHOT_CMD='xfce4-screenshooter -f -s $SHOT_FILE'

+ 8 - 0
tools/linuxvm/profiles/steamos.sh

@@ -0,0 +1,8 @@
+VM=steamos
+SCREEN=Virtual-1
+SHOT_CMD=host
+FULLSCREEN_CMD='konsole --fullscreen'
+MAXIMIZE_CMD='~/lwe/maximize_kde.sh'
+WEM=app
+PREP='(setsid nohup kde-inhibit --power --screenSaver sleep 100000 >/dev/null 2>&1 &)'
+WEM_LAUNCH='systemd-run --user --scope -q'

+ 6 - 0
tools/linuxvm/profiles/zorin-gnome.sh

@@ -0,0 +1,6 @@
+VM=zorin-gnome
+SCREEN=Virtual-1
+SHOT_CMD=host
+FULLSCREEN_CMD='python3 ~/lwe/fullscreen_window.py'
+MAXIMIZE_CMD='python3 ~/lwe/fullscreen_window.py maximize'
+WEM=deb

+ 11 - 1
tools/linuxvm/qtype.sh

@@ -1,6 +1,6 @@
 #!/bin/bash
 # qtype.sh <vm> <us|de> <text> - types text into a VM one key at a time through QMP (`linuxvm.sh type` drops characters
-# under load). Letters, digits and  . - / : ; _ + = @ space are mapped for the given guest keyboard layout; "ret" as the
+# under load). Letters, digits and  . - / : ; _ + = @ | < > ~ & $ ( ) ' \" space are mapped for the given guest keyboard layout; "ret" as the
 # whole text presses Enter. For the German layout y and z are swapped, - is the slash key, : is shift-dot, / is shift-7.
 HERE=$(cd "$(dirname "$0")" && pwd)
 vm=$1 layout=$2 text=$3
@@ -22,6 +22,16 @@ for ((i = 0; i < ${#text}; i++)); do
     =) [ "$layout" = de ] && k shift-0 || k equal ;;
     +) [ "$layout" = de ] && k bracket_right || k shift-equal ;;
     @) [ "$layout" = de ] && k alt_r-q || k shift-2 ;;
+    '|') [ "$layout" = de ] && k alt_r-less || k shift-backslash ;;
+    '>') [ "$layout" = de ] && k shift-less || k shift-dot ;;
+    '<') [ "$layout" = de ] && k less || k shift-comma ;;
+    '~') [ "$layout" = de ] && k alt_r-bracket_right || k shift-grave_accent ;;
+    '&') [ "$layout" = de ] && k shift-6 || k shift-7 ;;
+    '$') [ "$layout" = de ] && k shift-4 || k shift-4 ;;
+    '(') [ "$layout" = de ] && k shift-8 || k shift-9 ;;
+    ')') [ "$layout" = de ] && k shift-9 || k shift-0 ;;
+    "'") [ "$layout" = de ] && k shift-backslash || k apostrophe ;;
+    '"') [ "$layout" = de ] && k shift-2 || k shift-apostrophe ;;
     *) echo "qtype: no mapping for '$c'" >&2; exit 1 ;;
     esac
 done

+ 74 - 15
tools/linuxvm/release_check.sh

@@ -12,7 +12,7 @@
 #   --no-overlay     run on the VM's disk as it is (a VM without a golden disk is run like this anyway)
 # A profile (profiles/<vm>.sh) sets: VM, SCREEN (as --screen-root names it), SHOT_CMD (command with $SHOT_FILE, or
 # host), FULLSCREEN_CMD / MAXIMIZE_CMD (open a fullscreen / maximized window), WEM (deb | app | none, how we_manager is installed), WEM_FLAGS,
-# LOGIN_PASSWORD (typed at a greeter without autologin), PREP (guest command run once the session is up, e.g. keeps the screen from locking), EXTRA (function name run last,
+# WEM_LAUNCH (prefix of the we_manager start line, e.g. `systemd-run --user --scope -q` where an ssh session's end kills the app), LOGIN_PASSWORD (typed at a greeter without autologin), PREP (guest command run once the session is up, e.g. keeps the screen from locking), EXTRA (function name run last,
 # gets the VM name; prints PASS/FAIL lines).
 HERE=$(cd "$(dirname "$0")" && pwd)
 LINUXVM=${LINUXVM:-$HOME/.local/share/linuxvm}
@@ -49,7 +49,21 @@ wait_off() {
     lv kill "$VM"; sleep 2
 }
 
-# run the checks of one VM, results as PASS/FAIL/SKIP lines on stdout
+# the guest_test.sh group a result line belongs to, empty when unknown (the whole run is repeated then)
+group_of() {
+    case $1 in
+    *"hotswap cycle"*|*"/shot-cycle-"*) echo cycle ;;
+    *"hotswap video"*) echo video ;;
+    *"multi monitor"*|*"first monitor"*|*"second monitor"*) echo multi ;;
+    *automute*) echo automute ;;
+    *"behavior:"*|*"hotswap:"*|*"fullscreen pause"*|*"maximized pause"*|*SIGKILL*|*"/hot-before.png"*|*"/hot-after.png"*) echo behavior ;;
+    *"baseline screenshot"*|*"/shot-"[0-9]*".png"*) echo wallpapers ;;
+    *) if [[ $1 =~ ^(PASS|FAIL|SKIP)\ [0-9]{8,10}: ]]; then echo wallpapers; fi ;;
+    esac
+}
+
+runs() { [ -z "$ONLY" ] || [[ " $ONLY " == *" $1 "* ]]; }
+
 run_checks() {
     local out=/tmp/lwe-test
     lv scp "$VM" "$HERE/guest_test.sh" lwe/guest_test.sh
@@ -58,7 +72,7 @@ run_checks() {
     sshv "rm -rf $out; mkdir -p $out"
     local shots=""
     if [ "$SHOT_CMD" = host ]; then "$HERE/host_shots.sh" "$VM" "$out" 900 >/dev/null 2>&1 & shots=$!; fi
-    sshv ". ~/sessenv; BEHAVIOR=1 SETTLE=${SETTLE:-25} LWE_ARGS='--screen-root $SCREEN' SHOT_CMD='$SHOT_CMD' FULLSCREEN_CMD='$FULLSCREEN_CMD' MAXIMIZE_CMD='$MAXIMIZE_CMD' ~/lwe/guest_test.sh"
+    sshv ". ~/sessenv; BEHAVIOR=1 ONLY='$ONLY' SETTLE=${SETTLE:-25} LWE_ARGS='--screen-root $SCREEN' SHOT_CMD='$SHOT_CMD' FULLSCREEN_CMD='$FULLSCREEN_CMD' MAXIMIZE_CMD='$MAXIMIZE_CMD' MINIMIZE_CMD='$MINIMIZE_CMD' MULTI_SHOT_CMD='$MULTI_SHOT_CMD' ~/lwe/guest_test.sh"
     [ -n "$shots" ] && wait "$shots"
     local local_dir=$report/$VM/shots
     mkdir -p "$local_dir"
@@ -66,23 +80,39 @@ run_checks() {
         -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR "lab@127.0.0.1:$out/*" "$local_dir/" 2>/dev/null
     local shot
     if [ -f "$local_dir/baseline.png" ]; then
-        for shot in "$local_dir"/shot-*.png; do [ -f "$shot" ] && python3 -I "$HERE/check_frame.py" --baseline "$local_dir/baseline.png" "$shot"; done
+        if runs wallpapers; then
+            for shot in "$local_dir"/shot-[0-9]*.png; do [ -f "$shot" ] && python3 -I "$HERE/check_frame.py" --baseline "$local_dir/baseline.png" "$shot"; done
+        fi
+        if runs cycle; then
+            for shot in "$local_dir"/shot-cycle-*.png; do [ -f "$shot" ] && python3 -I "$HERE/check_frame.py" --baseline "$local_dir/baseline.png" "$shot"; done
+        fi
     fi
-    [ -f "$local_dir/hot-before.png" ] && python3 -I "$HERE/check_frame.py" --differ "$local_dir/hot-before.png" "$local_dir/hot-after.png"
+    runs video && [ -f "$local_dir/fresh-video.png" ] && [ -f "$local_dir/swap-video.png" ] \
+        && python3 -I "$HERE/check_frame.py" --similar "$local_dir/fresh-video.png" "$local_dir/swap-video.png" 14 \
+        | sed 's/^\(PASS\|FAIL\) /\1 hotswap video: /'
+    if runs multi && [ -f "$local_dir/multi-geometry" ] && [ -f "$local_dir/multi-shot.png" ]; then
+        read -r w1 w2 < "$local_dir/multi-geometry"
+        split=$(python3 -c "print($w1 / ($w1 + $w2))")
+        python3 -I "$HERE/check_frame.py" --crop "0,$split" --baseline "$local_dir/multi-baseline.png" "$local_dir/multi-shot.png" \
+            | sed 's/^\(PASS\|FAIL\) /\1 first monitor: /'
+        python3 -I "$HERE/check_frame.py" --crop "$split,1" --baseline "$local_dir/multi-baseline.png" "$local_dir/multi-shot.png" \
+            | sed 's/^\(PASS\|FAIL\) /\1 second monitor: /'
+    fi
+    runs behavior && [ -f "$local_dir/hot-before.png" ] && python3 -I "$HERE/check_frame.py" --differ "$local_dir/hot-before.png" "$local_dir/hot-after.png"
     return 0
 }
 
 for VM in "${vms[@]}"; do
-    unset WEM_FLAGS LOGIN_PASSWORD SCREEN SHOT_CMD FULLSCREEN_CMD MAXIMIZE_CMD WEM WEM_FLAGS PREP EXTRA SETTLE
+    unset POINTER WEM_FLAGS WEM_LAUNCH LOGIN_PASSWORD SCREEN SHOT_CMD FULLSCREEN_CMD MAXIMIZE_CMD MINIMIZE_CMD MULTI MULTI_SHOT_CMD WEM WEM_FLAGS PREP EXTRA SETTLE
     # shellcheck disable=SC1090
     . "$HERE/profiles/$VM.sh" || { echo "no profile for $VM"; continue; }
-    export WEM_FLAGS   # the we_manager scripts add them to its command line (COSMIC)
+    export WEM_FLAGS WEM_LAUNCH   # the we_manager scripts add them to its command line (COSMIC)
     mkdir -p "$report/$VM"
     log=$report/$VM/run.log
     echo "== $VM $(date +%T)"
     {
         if [ "$overlay" = 1 ] && [ -f "$LINUXVM/vms/$VM/golden.qcow2" ]; then lv fresh "$VM"; fi
-        lv start "$VM"
+        LINUXVM_OUTPUTS=${MULTI:+2} lv start "$VM"
         ready=0 logged_in=0
         for _ in $(seq 60); do
             # a greeter without autologin (COSMIC): type the password once the VM answers
@@ -100,23 +130,52 @@ for VM in "${vms[@]}"; do
                 sshv "rm -rf ~/lwe/lwe-hints.new"
                 lv scp "$VM" "$candidate/lwe-hints" lwe/lwe-hints.new && sshv "rm -rf ~/lwe/lwe-hints && mv ~/lwe/lwe-hints.new ~/lwe/lwe-hints"
             fi
+            for wp in wp-3471294034 wp-3818199837 wp-1367456719; do
+                sshv "[ -d ~/lwe/$wp ]" || lv scp "$VM" "$LINUXVM/payload/$wp" lwe/
+            done
             sleep 20
-            run_checks > "$report/$VM/checks.txt" 2>&1
-            if grep -q '^FAIL' "$report/$VM/checks.txt"; then
-                echo "retrying the failed checks once"
+            ONLY="" run_checks > "$report/$VM/checks.txt" 2>&1
+            fatal=0
+            if grep -q '^FATAL' "$report/$VM/checks.txt"; then
+                fatal=1
+                echo "FATAL, the rest of the run for $VM is skipped"
+            elif grep -q '^FAIL' "$report/$VM/checks.txt"; then
+                retry="" full=0
+                while IFS= read -r line; do
+                    g=$(group_of "$line")
+                    if [ -z "$g" ]; then full=1; elif [[ " $retry " != *" $g "* ]]; then retry="$retry $g"; fi
+                done < <(grep '^FAIL' "$report/$VM/checks.txt")
+                [ $full = 1 ] && retry=""
+                echo "retrying the failed checks once (groups:${retry:- all})"
                 sshv "pkill -f '[l]inux-wallpaperengine' 2>/dev/null; true"; sleep 5
                 cp "$report/$VM/checks.txt" "$report/$VM/checks-first.txt"
-                run_checks > "$report/$VM/checks.txt" 2>&1
+                ONLY="${retry# }" run_checks > "$report/$VM/checks-retry.txt" 2>&1
+                if [ -z "$retry" ]; then cp "$report/$VM/checks-retry.txt" "$report/$VM/checks.txt"; else
+                    while IFS= read -r line; do
+                        g=$(group_of "$line")
+                        [ -n "$g" ] && [[ " $retry " == *" $g "* ]] || echo "$line"
+                    done < "$report/$VM/checks-first.txt" > "$report/$VM/checks.txt"
+                    cat "$report/$VM/checks-retry.txt" >> "$report/$VM/checks.txt"
+                fi
+            fi
+            if [ $fatal = 0 ] && [ "${POINTER:-1}" = 1 ]; then
+                "$HERE/pointer_check.sh" "$VM" "$SCREEN" "$report/$VM/shots" > "$report/$VM/pointer.txt" 2>&1
+                if grep -q '^FAIL' "$report/$VM/pointer.txt"; then
+                    cp "$report/$VM/pointer.txt" "$report/$VM/pointer-first.txt"
+                    "$HERE/pointer_check.sh" "$VM" "$SCREEN" "$report/$VM/shots" > "$report/$VM/pointer.txt" 2>&1
+                fi
+                grep -E '^(PASS|FAIL|SKIP)' "$report/$VM/pointer.txt" >> "$report/$VM/checks.txt"
             fi
-            if [ -n "$app" ] && [ "${WEM:-none}" != none ]; then
+            if [ $fatal = 0 ] && [ -n "$app" ] && [ "${WEM:-none}" != none ]; then
                 # with the candidate's engine tarball the update check installs it (as a v99 release), we_manager's own
                 # checks then run on it instead of the last published engine
                 {
+                    [ -n "$tarball" ] && ENGINE_TARBALL=$tarball "$HERE/clean_install_check.sh" "$VM" "$app"
                     ENGINE_TARBALL=$tarball "$HERE/update_check.sh" "$VM" "$app"
                     SKIP_ENGINE_INSTALL=${tarball:+1} "$HERE/wem_check.sh" "$VM" "$app" "$SCREEN"
                 } > "$report/$VM/wem.txt" 2>&1
             fi
-            [ -n "$EXTRA" ] && $EXTRA "$VM" > "$report/$VM/extra.txt" 2>&1
+            [ $fatal = 0 ] && [ -n "$EXTRA" ] && $EXTRA "$VM" > "$report/$VM/extra.txt" 2>&1
             sshv "cat /tmp/lwe-test/engine-*.log 2>/dev/null | tail -n 200" > "$report/$VM/engine-tail.log" 2>&1
         fi
         if [ -n "$KEEP_VM" ]; then echo "KEEP_VM set: $VM stays up for a look"; else
@@ -125,7 +184,7 @@ for VM in "${vms[@]}"; do
         fi
     } > "$log" 2>&1
     pass=$(cat "$report/$VM"/{checks,wem,extra}.txt 2>/dev/null | grep -c '^PASS')
-    failed=$(cat "$report/$VM"/{checks,wem,extra}.txt 2>/dev/null | grep '^FAIL'; grep '^FAIL' "$log")
+    failed=$(cat "$report/$VM"/{checks,wem,extra}.txt 2>/dev/null | grep -E '^(FAIL|FATAL)'; grep -E '^(FAIL|FATAL)' "$log")
     {
         echo; echo "## $VM"
         if [ -z "$failed" ]; then echo "$pass checks passed."; else

+ 31 - 1
tools/linuxvm/sessenv.sh

@@ -4,7 +4,7 @@
 # Usage: ./sessenv.sh; . ~/sessenv
 vars="XDG_RUNTIME_DIR DBUS_SESSION_BUS_ADDRESS WAYLAND_DISPLAY DISPLAY XAUTHORITY XDG_SESSION_TYPE XDG_CURRENT_DESKTOP \
 XDG_SESSION_DESKTOP XDG_SESSION_ID HYPRLAND_INSTANCE_SIGNATURE KDE_SESSION_VERSION KDE_FULL_SESSION DESKTOP_SESSION"
-for name in plasmashell gsd-xsettings cosmic-panel Hyprland cinnamon xfce4-session xdg-desktop-portal; do
+for name in plasmashell gsd-xsettings gnome-shell cosmic-panel Hyprland cinnamon xfce4-session xdg-desktop-portal; do
     pid=$(pgrep -u "$(id -u)" -x "$name" | head -1)
     [ -n "$pid" ] && break
 done
@@ -14,5 +14,35 @@ for v in $vars; do
     value=$(tr '\0' '\n' < "/proc/$pid/environ" | sed -n "s/^$v=//p" | head -1)
     [ -n "$value" ] && echo "export $v=\"$value\"" >> ~/sessenv
 done
+for v in $vars; do
+    [ "$name" = Hyprland ] || break
+    grep -q "^export $v=" ~/sessenv && continue
+    value=$(systemctl --user show-environment 2>/dev/null | sed -n "s/^$v=//p" | head -1)
+    [ -n "$value" ] && { echo "export $v=\"$value\"" >> ~/sessenv; continue; }
+    for client in quickshell noctalia-shell kitty waybar; do
+        cpid=$(pgrep -u "$(id -u)" -x "$client" | head -1)
+        [ -n "$cpid" ] || continue
+        value=$(tr '\0' '\n' < "/proc/$cpid/environ" | sed -n "s/^$v=//p" | head -1)
+        [ -n "$value" ] && { echo "export $v=\"$value\"" >> ~/sessenv; break; }
+    done
+done
+if [ "$name" = Hyprland ] && ! grep -q HYPRLAND_INSTANCE_SIGNATURE ~/sessenv; then
+    # under uwsm the compositor's own environment lacks the signature, its socket directory has it
+    sig=$(ls -t "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/hypr" 2>/dev/null | head -1)
+    [ -n "$sig" ] && echo "export HYPRLAND_INSTANCE_SIGNATURE=\"$sig\"" >> ~/sessenv
+fi
+if [ "$name" = Hyprland ] && ! grep -q '^export XDG_SESSION_TYPE="wayland"' ~/sessenv; then
+    # started from a tty login (no display manager) the session type is "tty"
+    sed -i '/^export XDG_SESSION_TYPE=/d' ~/sessenv
+    echo 'export XDG_SESSION_TYPE="wayland"' >> ~/sessenv
+fi
+if [ "$name" = gnome-shell ]; then
+    # the shell's own environment lacks the display variables, its clients and the user manager have them
+    for v in WAYLAND_DISPLAY DISPLAY XAUTHORITY; do
+        grep -q "^export $v=" ~/sessenv && continue
+        value=$(systemctl --user show-environment 2>/dev/null | sed -n "s/^$v=//p" | head -1)
+        [ -n "$value" ] && echo "export $v=\"$value\"" >> ~/sessenv
+    done
+fi
 echo "session of $name (pid $pid):"
 cat ~/sessenv

+ 22 - 12
tools/linuxvm/update_check.sh

@@ -22,16 +22,20 @@ if [ -z "$deb" ]; then
     for candidate in "$(dirname "$app")"/*.deb "$(dirname "$app")"/../*.deb; do [ -f "$candidate" ] && deb=$candidate && break; done
 fi
 engine=${ENGINE_TARBALL:-$HOME/.local/share/distro-rootfs/out/linux-wallpaperengine-kde-portable-x86_64.tar.gz}
-[ -f "$deb" ] || { echo "no .deb to serve as the new app release (APP_DEB)"; exit 2; }
-python3 "$HERE/bump_deb.py" "$deb" "$work/we-manager_0.9.9_amd64.deb" 0.9.9
+app_release=()
+if [ -f "$deb" ]; then
+    python3 "$HERE/bump_deb.py" "$deb" "$work/we-manager_0.9.9_amd64.deb" 0.9.9
+    app_release=(--release "WallpaperEngineLover/we_manager=v0.9.9:$work/we-manager_0.9.9_amd64.deb")
+else
+    echo "SKIP app update: no .deb to serve as the new app release (APP_DEB), only the engine update is checked"
+fi
 cp "$engine" "$work/linux-wallpaperengine-kde-portable-x86_64.tar.gz"
 cp "$engine" "$work/linux-wallpaperengine-generic-portable-x86_64.tar.gz"
 mkdir -p "$work/certs"
-python3 "$HERE/fake_github.py" "$work/certs" \
-    --release "WallpaperEngineLover/we_manager=v0.9.9:$work/we-manager_0.9.9_amd64.deb" \
-    --release "WallpaperEngineLover/linux-wallpaperengine-kde=$engine_tag:$work/linux-wallpaperengine-kde-portable-x86_64.tar.gz,$work/linux-wallpaperengine-generic-portable-x86_64.tar.gz" \
-    > "$work/fake.log" 2>&1 &
-fake=$!
+. "$HERE/fake_github_lib.sh"
+fgh_start "$vm" "$work" \
+    "${app_release[@]}" \
+    --release "WallpaperEngineLover/linux-wallpaperengine-kde=$engine_tag:$work/linux-wallpaperengine-kde-portable-x86_64.tar.gz,$work/linux-wallpaperengine-generic-portable-x86_64.tar.gz"
 trap 'kill $fake 2>/dev/null; rm -rf "$work"' EXIT
 sleep 3
 kill -0 $fake 2>/dev/null || { cat "$work/fake.log"; echo "fake_github did not start (port 443?)"; exit 2; }
@@ -46,16 +50,22 @@ fi
 sshv 'grep -q "api.github.com" /etc/hosts || echo "10.0.2.2 api.github.com" | sudo tee -a /etc/hosts >/dev/null
 sudo mkdir -p /etc/polkit-1/rules.d
 printf "polkit.addRule(function(action, subject) { if (subject.user == \"lab\") return polkit.Result.YES; });\n" | sudo tee /etc/polkit-1/rules.d/49-lab-test.rules >/dev/null
-pkill -f "[w]e-manager" 2>/dev/null; true'
+pkill -f "[w]e-manager" 2>/dev/null; for _ in $(seq 20); do pgrep -f "[w]e-manager" >/dev/null || break; sleep 1; done; true'
 sleep 2
-if [[ $app == *.deb ]]; then start="we-manager ${WEM_FLAGS:-}"; else start="~/wem/$(basename "$app")/we-manager --no-sandbox ${WEM_FLAGS:-}"; fi
-sshv ". ~/sessenv; export NODE_EXTRA_CA_CERTS=\$HOME/wem/fake-ca.pem; (setsid nohup $start --remote-debugging-port=9222 > ~/wem/app-update.log 2>&1 </dev/null &); sleep 25"
+if [[ $app == *.deb ]]; then
+    "$HERE/linuxvm.sh" scp "$vm" "$app" wem/app.deb
+    sshv 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-downgrades ./wem/app.deb >/tmp/wem-deb.log 2>&1'
+fi
+if [[ $app == *.deb ]]; then start="${WEM_LAUNCH:-} we-manager ${WEM_FLAGS:-}"; else start="${WEM_LAUNCH:-} ~/wem/$(basename "$app")/we-manager --no-sandbox ${WEM_FLAGS:-}"; fi
+sshv ". ~/sessenv; export NODE_EXTRA_CA_CERTS=\$HOME/wem/fake-ca.pem; (setsid nohup $start --remote-debugging-port=9222 > ~/wem/app-update.log 2>&1 </dev/null &); for _ in \$(seq 40); do grep -q 'DevTools listening' ~/wem/app-update.log 2>/dev/null && break; sleep 1; done; sleep 8"
 [ "$(sshv 'pgrep -fc "[w]e-manager"')" -gt 0 ] && pass "we_manager starts" || { fail "we_manager did not start: $(sshv 'tail -3 ~/wem/app-update.log')"; exit 1; }
 
 out=$(cdp 'window.electronAPI.updates.setChecks({app: true, engine: true})' 1500)
 out=$(cdp 'window.electronAPI.updates.check()' 2500); echo "     $out" | tr '\n' ' ' | cut -c1-600; echo
 kind=$(echo "$out" | grep -o '"appInstall": "[^"]*"' | cut -d'"' -f4)
-echo "$out" | grep -q '"version": "0.9.9"\|"version": "v0.9.9"' && pass "app update 0.9.9 offered (install kind $kind)" || fail "app update not offered"
+if [ -f "$deb" ]; then
+    echo "$out" | grep -q '"version": "0.9.9"\|"version": "v0.9.9"' && pass "app update 0.9.9 offered (install kind $kind)" || fail "app update not offered"
+fi
 if echo "$out" | grep -q "$engine_tag"; then pass "engine update $engine_tag offered"
 elif echo "$out" | grep -q '"engineInstall": null'; then echo "SKIP engine update offer: no engine installed through we_manager on this VM yet"
 else fail "engine update not offered"; fi
@@ -71,5 +81,5 @@ fi
 out=$(sshv ". ~/sessenv; cd ~/wem; timeout 400 python3 cdp.py 'window.electronAPI.lwe.installPrebuilt()' 2>&1 | cut -c1-300")
 if echo "$out" | grep -q '"installed": true'; then pass "engine update installed through the prebuilt install: $(echo "$out" | grep -o '"version": "[^"]*"')"; else fail "engine update failed: $out"; fi
 grep -c "GET" "$work/fake.log" | xargs -I{} echo "     {} requests reached the fake api.github.com"
-sshv 'pkill -f "[w]e-manager" 2>/dev/null; sudo rm -f /etc/polkit-1/rules.d/49-lab-test.rules; sudo sed -i "/api.github.com/d" /etc/hosts; true'
+sshv 'pkill -f "[w]e-manager" 2>/dev/null; for _ in $(seq 20); do pgrep -f "[w]e-manager" >/dev/null || break; sleep 1; done; sudo rm -f /etc/polkit-1/rules.d/49-lab-test.rules; sudo sed -i "/api.github.com/d" /etc/hosts; true'
 exit $status

+ 14 - 8
tools/linuxvm/wem_check.sh

@@ -14,17 +14,17 @@ pass() { echo "PASS $1"; }
 fail() { echo "FAIL $1"; status=1; }
 cdp() { sshv ". ~/sessenv; cd ~/wem; timeout ${CDP_TIMEOUT:-90} python3 cdp.py \"$1\" 2>&1 | cut -c1-600"; }
 
-sshv 'mkdir -p ~/wem; pkill -f "[w]em/.*we-manager" 2>/dev/null; true'
+sshv 'mkdir -p ~/wem; pkill -f "[w]em/.*we-manager" 2>/dev/null; pkill -f "[w]e-manager" 2>/dev/null; for _ in $(seq 20); do pgrep -f "[w]e-manager" >/dev/null || break; sleep 1; done; true'
 "$HERE/linuxvm.sh" scp "$vm" "$HERE/cdp.py" wem/cdp.py
 if [[ $app == *.deb ]]; then
     "$HERE/linuxvm.sh" scp "$vm" "$app" wem/app.deb
-    if sshv 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y ./wem/app.deb >/tmp/wem-deb.log 2>&1'; then pass "the .deb installs"; else fail "the .deb did not install: $(sshv 'tail -3 /tmp/wem-deb.log')"; fi
-    start="we-manager ${WEM_FLAGS:-}"
+    if sshv 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-downgrades ./wem/app.deb >/tmp/wem-deb.log 2>&1'; then pass "the .deb installs"; else fail "the .deb did not install: $(sshv 'tail -3 /tmp/wem-deb.log')"; fi
+    start="${WEM_LAUNCH:-} we-manager ${WEM_FLAGS:-}"
 else
     tar -C "$(dirname "$app")" -cf - "$(basename "$app")" | ssh -i "$HOME/.local/share/linuxvm/id_ed25519" \
         -p "$(cat "$HOME/.local/share/linuxvm/vms/$vm/port")" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
         -o LogLevel=ERROR lab@127.0.0.1 'mkdir -p ~/wem && tar -C ~/wem -xf -'
-    start="~/wem/$(basename "$app")/we-manager --no-sandbox ${WEM_FLAGS:-}"
+    start="${WEM_LAUNCH:-} ~/wem/$(basename "$app")/we-manager --no-sandbox ${WEM_FLAGS:-}"
 fi
 
 # a Steam library like a real user has: the Wallpaper Engine assets and the workshop items
@@ -32,8 +32,8 @@ sshv 'mkdir -p ~/.steam/steam/steamapps/common/wallpaper_engine ~/.steam/steam/s
 ln -sfn ~/lwe/assets ~/.steam/steam/steamapps/common/wallpaper_engine/assets
 for id in 1120596121 1078208425; do d=~/.steam/steam/steamapps/workshop/content/431960/$id; [ -L $d ] && rm $d; [ -d $d ] || cp -al ~/lwe/wp-$id $d; done'  # copies: the library scan skips symlinked folders
 
-sshv ". ~/sessenv; (setsid nohup $start --remote-debugging-port=9222 > ~/wem/app.log 2>&1 </dev/null &); sleep 25"
-[ "$(sshv 'pgrep -fc "[w]e-manager"')" -gt 0 ] && pass "we_manager starts" || { fail "we_manager did not start: $(sshv 'tail -3 ~/wem/app.log')"; exit 1; }
+sshv ". ~/sessenv; (setsid nohup $start --remote-debugging-port=9222 > ~/wem/app.log 2>&1 </dev/null &); for _ in \$(seq 40); do grep -q 'DevTools listening' ~/wem/app.log 2>/dev/null && break; sleep 1; done; sleep 8"
+[ "$(sshv 'pgrep -fc "[w]e-manager"')" -gt 0 ] && sshv "grep -q 'DevTools listening' ~/wem/app.log" && pass "we_manager starts" || { fail "we_manager did not start: $(sshv 'tail -3 ~/wem/app.log')"; exit 1; }
 
 out=$(cdp 'window.electronAPI.lwe.detectDistro()'); echo "     distro: $out"
 out=$(cdp 'window.electronAPI.lwe.prebuiltTarget()')
@@ -47,17 +47,23 @@ if [ -z "$SKIP_ENGINE_INSTALL" ]; then
     if echo "$out" | grep -q '"installed": true'; then pass "engine installed from the release: $(echo "$out" | grep -o '"version": "[^"]*"')"; else fail "engine install failed: $out"; fi
 fi
 
+if [ -n "$SKIP_ENGINE_INSTALL" ] && ! sshv 'test -x ~/.local/share/linux-wallpaperengine-kde/linux-wallpaperengine'; then
+    # a read-only system skips the clean install and the update check has nothing to update: put the candidate where the install would
+    sshv 'mkdir -p ~/.local/share && rm -rf ~/.local/share/linux-wallpaperengine-kde && cp -a ~/lwe/lwe-hints ~/.local/share/linux-wallpaperengine-kde'
+    echo "     no engine was installed through we_manager here, copied the candidate into ~/.local/share/linux-wallpaperengine-kde"
+fi
+
 launch() { cdp "window.electronAPI.lwe.launch('$HOME_STEAM/$1', {screen: '$screen'})"; }
 HOME_STEAM=$(sshv 'echo $HOME')/.steam/steam/steamapps/workshop/content/431960
 for id in 1120596121 1078208425; do
-    out=$(launch "$id"); sleep 30
+    out=$(launch "$id"); sleep 15
     engines=$(sshv 'pgrep -fc "/[l]inux-wallpaperengine(\.bin)? "')
     if echo "$out" | grep -q '"running": true' && [ "$engines" -gt 0 ]; then pass "$id launched from we_manager ($engines engine processes)"; else fail "$id did not launch: $out"; fi
     cdp 'window.electronAPI.lwe.stop()' >/dev/null; sleep 5
     left=$(sshv 'echo $(pgrep -fc "/[l]inux-wallpaperengine(\.bin)? ") $(pgrep -fc "[w]eb-helper")')
     [ "$left" = "0 0" ] && pass "$id: stop leaves nothing behind" || fail "$id: after stop engines/helpers: $left"
 done
-launch 1078208425 >/dev/null; sleep 25
+launch 1078208425 >/dev/null; sleep 12
 cdp 'window.electronAPI.lwe.killAll()' >/dev/null; sleep 6
 left=$(sshv 'echo $(pgrep -fc "/[l]inux-wallpaperengine(\.bin)? ") $(pgrep -fc "[w]eb-helper")')
 [ "$left" = "0 0" ] && pass "kill all leaves nothing behind" || fail "after kill all engines/helpers: $left"