소스 검색

gnome should be fine now

UwU 1 개월 전
부모
커밋
85ebc97f01
29개의 변경된 파일과 371개의 추가작업 그리고 211개의 파일을 삭제
  1. 3 1
      CMakeLists.txt
  2. 17 0
      gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io/extension.js
  3. 1 0
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  4. 32 62
      src/WallpaperEngine/Desktop/GnomeShell.cpp
  5. 1 0
      src/WallpaperEngine/Desktop/GnomeShell.h
  6. 23 44
      src/WallpaperEngine/Desktop/KWinScript.cpp
  7. 4 2
      src/WallpaperEngine/Desktop/KWinScript.h
  8. 72 0
      src/WallpaperEngine/Desktop/SessionBus.cpp
  9. 15 0
      src/WallpaperEngine/Desktop/SessionBus.h
  10. 1 3
      src/WallpaperEngine/Desktop/WindowState.cpp
  11. 4 0
      src/WallpaperEngine/Desktop/WindowState.h
  12. 3 19
      src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp
  13. 9 1
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp
  14. 2 0
      src/WallpaperEngine/Input/Drivers/WaylandMouseInput.h
  15. 0 3
      src/WallpaperEngine/Render/Drivers/Detectors/GnomeFullScreenDetector.cpp
  16. 44 29
      src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.cpp
  17. 4 1
      src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.h
  18. 2 34
      src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp
  19. 12 7
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  20. 2 0
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.h
  21. 2 0
      src/WallpaperEngine/Render/Drivers/VideoDriver.h
  22. 51 0
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp
  23. 4 0
      src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h
  24. 20 1
      tests/desktops/test_gnome.py
  25. 22 0
      tests/desktops/test_kde.py
  26. 3 1
      tools/desktops/__main__.py
  27. 2 0
      tools/desktops/rootfs-ubuntu-kde5.txt
  28. 1 0
      tools/desktops/runner.py
  29. 15 3
      tools/desktops/session.py

+ 3 - 1
CMakeLists.txt

@@ -426,6 +426,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Desktop/WindowState.cpp
     src/WallpaperEngine/Desktop/KWinScript.h
     src/WallpaperEngine/Desktop/KWinScript.cpp
+    src/WallpaperEngine/Desktop/SessionBus.h
+    src/WallpaperEngine/Desktop/SessionBus.cpp
     src/WallpaperEngine/Media/ThumbnailPalette.h
     src/WallpaperEngine/Media/ThumbnailPalette.cpp
 
@@ -880,7 +882,7 @@ install(TARGETS linux-wallpaperengine-lib
 
 # Install everything else from the output directory (CEF resources, helper binaries, etc.)
 # but exclude the files already handled by install(TARGETS) above.
-install(DIRECTORY ${TARGET_OUTPUT_DIRECTORY}/ DESTINATION .
+install(DIRECTORY ${TARGET_OUTPUT_DIRECTORY}/ DESTINATION . USE_SOURCE_PERMISSIONS
     PATTERN "linux-wallpaperengine" EXCLUDE
     PATTERN "linux-wallpaperengine-web-helper" EXCLUDE
     PATTERN "liblinux-wallpaperengine-lib.so" EXCLUDE

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

@@ -93,6 +93,8 @@ const SUPPORTED = CAN_SET_TYPE || CAN_HIDE;
 const HELPER = 'linux-wallpaperengine-gnome-helper';
 // icon extensions using a bottom-layer normal window (DING on Ubuntu 46, its Gtk4 fork)
 const DESKTOP_ICON_APPS = ['com.rastersoft.ding', 'com.desktop.ding'];
+// windows can move under a still pointer, re-pick after this long
+const PICK_INTERVAL_US = 250000;
 
 function isMaximized(window) {
     const flags = window.get_maximize_flags ? window.get_maximize_flags() : window.get_maximized();
@@ -125,7 +127,10 @@ export default class WallpaperEngineExtension extends Extension {
         this._displaySignals = [
             global.display.connect('window-created', (_display, window) => this._watch(window)),
             global.display.connect('notify::focus-window', () => this._queueState()),
+            // a window moved to another monitor keeps its size
+            global.display.connect('window-entered-monitor', () => this._queueState()),
             global.display.connect('restacked', () => {
+                this._pickStale = true;
                 this._pruneWallpapers();
                 this._keepBelowDesktopWindows();
                 this._queueState();
@@ -148,6 +153,9 @@ export default class WallpaperEngineExtension extends Extension {
         this._leftDown = false;
         this._leftForwarded = false;
         this._pointerOverDesktop = false;
+        this._pickStale = true;
+        this._pickX = this._pickY = -1;
+        this._pickTime = 0;
         this._paintSignal = global.stage.connect('after-paint', () => this._pollLeftButton());
 
         this._overviewClones = new Map();
@@ -520,8 +528,17 @@ export default class WallpaperEngineExtension extends Extension {
         }
     }
 
+    // runs every frame, a pick walks the whole stage
     _updatePointerOverDesktop() {
         const [x, y] = global.get_pointer();
+        const now = GLib.get_monotonic_time();
+        if (!this._pickStale && x === this._pickX && y === this._pickY && now - this._pickTime < PICK_INTERVAL_US)
+            return;
+
+        this._pickStale = false;
+        this._pickX = x;
+        this._pickY = y;
+        this._pickTime = now;
         this._pointerOverDesktop = this._overOtherDesktopWindow(x, y);
     }
 

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

@@ -2649,6 +2649,7 @@ void WallpaperApplication::render () {
 
     if (this->m_isPaused) {
 	usleep (FULLSCREEN_CHECK_WAIT_TIME);
+	m_videoDriver->dispatchWhilePaused ();
 	if (this->m_fullScreenDetector->anythingFullscreen () && this->m_context.state.general.keepRunning) {
 	    return;
 	}

+ 32 - 62
src/WallpaperEngine/Desktop/GnomeShell.cpp

@@ -1,10 +1,10 @@
 #include "GnomeShell.h"
+#include "SessionBus.h"
 
 #include "WallpaperEngine/Logging/Log.h"
 
 #include <cstdlib>
 #include <cstring>
-#include <filesystem>
 #include <optional>
 #include <poll.h>
 #include <string_view>
@@ -42,25 +42,7 @@ bool WallpaperEngine::Desktop::isGnomeSession () {
 }
 
 namespace {
-constexpr int CALL_TIMEOUT_MS = 2000;
-/** caps one frame's drain */
-constexpr int MAX_READS_PER_DISPATCH = 64;
-
-DBusMessage* call (DBusConnection* connection, DBusMessage* message, std::string& error) {
-    DBusError dbusError;
-    dbus_error_init (&dbusError);
-
-    DBusMessage* reply = dbus_connection_send_with_reply_and_block (connection, message, CALL_TIMEOUT_MS, &dbusError);
-    dbus_message_unref (message);
-
-    if (dbus_error_is_set (&dbusError)) {
-	error = dbusError.message;
-	dbus_error_free (&dbusError);
-	return nullptr;
-    }
-
-    return reply;
-}
+constexpr int HELPER_TIMEOUT_MS = 6000;
 
 bool readVariant (DBusMessageIter* iter, int type, void* value) {
     if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_VARIANT) {
@@ -162,21 +144,6 @@ GnomeShell::GnomeShell () {
 }
 
 namespace {
-std::string socketDirectory () {
-    std::string dir = std::getenv ("XDG_RUNTIME_DIR") ? std::getenv ("XDG_RUNTIME_DIR") : "/tmp";
-
-    if (const char* flatpakId = std::getenv ("FLATPAK_ID"); flatpakId && access ("/.flatpak-info", F_OK) == 0) {
-	const std::string appDir = dir + "/app/" + flatpakId;
-	std::error_code error;
-
-	if (std::filesystem::is_directory (appDir, error)) {
-	    dir = appDir;
-	}
-    }
-
-    return dir;
-}
-
 int receiveDescriptor (int connection) {
     char byte = 0;
     iovec data = { .iov_base = &byte, .iov_len = 1 };
@@ -207,7 +174,15 @@ int receiveDescriptor (int connection) {
 } // namespace
 
 int GnomeShell::openWaylandSocket () {
-    const std::string path = socketDirectory () + "/lwe-gnome-" + std::to_string (getpid ()) + ".sock";
+    const std::string directory = runtimeDirectory ();
+
+    // the extension only spawns a helper for a socket in the runtime folder
+    if (directory.empty ()) {
+	this->m_reason = "XDG_RUNTIME_DIR is not set";
+	return -1;
+    }
+
+    const std::string path = directory + "/lwe-gnome-" + std::to_string (getpid ()) + ".sock";
     sockaddr_un address = {};
     address.sun_family = AF_UNIX;
 
@@ -238,7 +213,7 @@ int GnomeShell::openWaylandSocket () {
     dbus_message_append_args (request, DBUS_TYPE_STRING, &pathArg, DBUS_TYPE_INVALID);
 
     std::string error;
-    DBusMessage* reply = call (this->m_connection, request, error);
+    DBusMessage* reply = callBlocking (this->m_connection, request, error);
     int fd = -1;
 
     if (reply == nullptr) {
@@ -247,7 +222,7 @@ int GnomeShell::openWaylandSocket () {
 	dbus_message_unref (reply);
 	pollfd waiting = { .fd = listener, .events = POLLIN, .revents = 0 };
 
-	if (poll (&waiting, 1, CALL_TIMEOUT_MS * 3) == 1) {
+	if (poll (&waiting, 1, HELPER_TIMEOUT_MS) == 1) {
 	    this->m_helperConnection = accept4 (listener, nullptr, nullptr, SOCK_CLOEXEC);
 	}
 
@@ -269,7 +244,11 @@ GnomeShell::~GnomeShell () {
     }
 
     if (this->m_connection != nullptr) {
-	dbus_connection_remove_filter (this->m_connection, &GnomeShell::filter, this);
+	// libdbus aborts on removing a filter that was never added
+	if (this->m_filterAdded) {
+	    dbus_connection_remove_filter (this->m_connection, &GnomeShell::filter, this);
+	}
+
 	dbus_connection_close (this->m_connection);
 	dbus_connection_unref (this->m_connection);
     }
@@ -298,7 +277,7 @@ bool GnomeShell::connect () {
     dbus_message_append_args (message, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
 
     std::string callError;
-    DBusMessage* reply = call (this->m_connection, message, callError);
+    DBusMessage* reply = callBlocking (this->m_connection, message, callError);
 
     if (reply == nullptr) {
 	this->m_reason = "the linux-wallpaperengine GNOME Shell extension is not running (" + callError + ")";
@@ -318,7 +297,12 @@ bool GnomeShell::connect () {
 
     dbus_bus_add_match (this->m_connection, signals.c_str (), nullptr);
     dbus_bus_add_match (this->m_connection, ownerChanges.c_str (), nullptr);
-    dbus_connection_add_filter (this->m_connection, &GnomeShell::filter, this, nullptr);
+    this->m_filterAdded = dbus_connection_add_filter (this->m_connection, &GnomeShell::filter, this, nullptr);
+
+    if (!this->m_filterAdded) {
+	this->m_reason = "out of memory adding a D-Bus filter";
+	return false;
+    }
 
     return true;
 }
@@ -334,7 +318,7 @@ bool GnomeShell::queryState () {
 	    message, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID
 	);
 
-	DBusMessage* reply = call (this->m_connection, message, error);
+	DBusMessage* reply = callBlocking (this->m_connection, message, error);
 
 	if (reply == nullptr) {
 	    this->m_reason = "the GNOME Shell extension did not answer (" + error + ")";
@@ -374,8 +358,9 @@ bool GnomeShell::queryState () {
 	dbus_message_unref (reply);
     }
 
-    DBusMessage* reply
-	= call (this->m_connection, dbus_message_new_method_call (BUS_NAME, OBJECT_PATH, INTERFACE, "GetState"), error);
+    DBusMessage* reply = callBlocking (
+	this->m_connection, dbus_message_new_method_call (BUS_NAME, OBJECT_PATH, INTERFACE, "GetState"), error
+    );
 
     if (reply == nullptr) {
 	this->m_reason = "the GNOME Shell extension did not answer GetState (" + error + ")";
@@ -404,24 +389,9 @@ void GnomeShell::dispatch () {
 	return;
     }
 
-    // a read pulls in ~2KB at most
-    for (int reads = 0; reads < MAX_READS_PER_DISPATCH; reads++) {
-	if (!dbus_connection_read_write (this->m_connection, 0)) {
-	    sLog.error ("The session bus connection to the GNOME Shell extension dropped");
-	    this->m_vanished = true;
-	    return;
-	}
-
-	bool dispatched = false;
-
-	while (dbus_connection_get_dispatch_status (this->m_connection) == DBUS_DISPATCH_DATA_REMAINS) {
-	    dbus_connection_dispatch (this->m_connection);
-	    dispatched = true;
-	}
-
-	if (!dispatched) {
-	    break;
-	}
+    if (!this->m_vanished && !drainBus (this->m_connection)) {
+	sLog.error ("The session bus connection to the GNOME Shell extension dropped");
+	this->m_vanished = true;
     }
 }
 

+ 1 - 0
src/WallpaperEngine/Desktop/GnomeShell.h

@@ -71,6 +71,7 @@ private:
     bool m_available = false;
     bool m_vanished = false;
     bool m_needsHelper = false;
+    bool m_filterAdded = false;
     bool m_desktopLeftDown = false;
     int m_helperConnection = -1;
     std::vector<Pointer> m_pointer;

+ 23 - 44
src/WallpaperEngine/Desktop/KWinScript.cpp

@@ -1,51 +1,20 @@
 #include "KWinScript.h"
+#include "SessionBus.h"
 
 #include "WallpaperEngine/Logging/Log.h"
 
 #include <cstdio>
-#include <cstdlib>
-#include <filesystem>
 #include <fstream>
-#include <unistd.h>
 
 using namespace WallpaperEngine::Desktop;
 
 namespace {
-constexpr int CALL_TIMEOUT_MS = 2000;
-
-std::string scriptDirectory () {
-    const char* runtimeDir = std::getenv ("XDG_RUNTIME_DIR");
-
-    if (runtimeDir == nullptr) {
-	return {};
-    }
-
-    std::string dir = runtimeDir;
-
-    // Flatpak shares only the app's runtime folder; FLATPAK_ID alone can be inherited
-    if (const char* flatpakId = std::getenv ("FLATPAK_ID");
-	flatpakId != nullptr && access ("/.flatpak-info", F_OK) == 0) {
-	const std::string appDir = dir + "/app/" + flatpakId;
-	std::error_code error;
-
-	if (std::filesystem::is_directory (appDir, error)) {
-	    dir = appDir;
-	}
-    }
-
-    return dir;
-}
-
 DBusMessage* callKWin (DBusConnection* connection, DBusMessage* call, const char* what) {
-    DBusError error;
-    dbus_error_init (&error);
-    DBusMessage* reply = dbus_connection_send_with_reply_and_block (connection, call, CALL_TIMEOUT_MS, &error);
-    dbus_message_unref (call);
-
-    if (dbus_error_is_set (&error)) {
-	sLog.error ("KWin script: ", what, ": ", error.message);
-	dbus_error_free (&error);
-	return nullptr;
+    std::string error;
+    DBusMessage* reply = callBlocking (connection, call, error);
+
+    if (reply == nullptr) {
+	sLog.error ("KWin script: ", what, ": ", error);
     }
 
     return reply;
@@ -54,7 +23,7 @@ DBusMessage* callKWin (DBusConnection* connection, DBusMessage* call, const char
 
 KWinScript::KWinScript (DBusConnection* connection, std::string pluginName, const std::string& source) :
     m_connection (connection), m_pluginName (std::move (pluginName)) {
-    const std::string dir = scriptDirectory ();
+    const std::string dir = runtimeDirectory ();
 
     if (dir.empty ()) {
 	sLog.error ("KWin script ", this->m_pluginName, ": XDG_RUNTIME_DIR is not set");
@@ -94,18 +63,28 @@ KWinScript::KWinScript (DBusConnection* connection, std::string pluginName, cons
 	return;
     }
 
-    const std::string object = "/Scripting/Script" + 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_registered = true;
 
-    if (DBusMessage* runReply = callKWin (this->m_connection, run, "run"); runReply != nullptr) {
-	dbus_message_unref (runReply);
+    // KWin 6 puts the script at /Scripting/Script<id>, KWin 5 at /<id>
+    std::string error;
+
+    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* reply = callBlocking (this->m_connection, run, error); reply != nullptr) {
+	    dbus_message_unref (reply);
+	    this->m_running = true;
+	    return;
+	}
     }
 
-    this->m_loaded = true;
+    sLog.error ("KWin script: run: ", error);
 }
 
 KWinScript::~KWinScript () {
-    if (this->m_loaded && this->m_connection != nullptr) {
+    if (this->m_registered && this->m_connection != nullptr) {
 	DBusMessage* unload
 	    = dbus_message_new_method_call ("org.kde.KWin", "/Scripting", "org.kde.kwin.Scripting", "unloadScript");
 	const char* nameArg = this->m_pluginName.c_str ();

+ 4 - 2
src/WallpaperEngine/Desktop/KWinScript.h

@@ -13,12 +13,14 @@ public:
     KWinScript (const KWinScript&) = delete;
     KWinScript& operator= (const KWinScript&) = delete;
 
-    [[nodiscard]] bool isLoaded () const { return this->m_loaded; }
+    /** loaded and started */
+    [[nodiscard]] bool isLoaded () const { return this->m_running; }
 
 private:
     DBusConnection* m_connection;
     std::string m_pluginName;
     std::string m_path;
-    bool m_loaded = false;
+    bool m_registered = false;
+    bool m_running = false;
 };
 } // namespace WallpaperEngine::Desktop

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

@@ -0,0 +1,72 @@
+#include "SessionBus.h"
+
+#include <cstdlib>
+#include <filesystem>
+#include <unistd.h>
+
+namespace {
+constexpr int CALL_TIMEOUT_MS = 2000;
+/** per-frame cap, a read pulls ~2KB at most */
+constexpr int MAX_READS_PER_DRAIN = 64;
+} // namespace
+
+std::string WallpaperEngine::Desktop::runtimeDirectory () {
+    const char* runtimeDir = std::getenv ("XDG_RUNTIME_DIR");
+
+    if (runtimeDir == nullptr) {
+	return {};
+    }
+
+    std::string dir = runtimeDir;
+
+    // Flatpak shares only the app's runtime folder; FLATPAK_ID alone can be inherited
+    if (const char* flatpakId = std::getenv ("FLATPAK_ID");
+	flatpakId != nullptr && access ("/.flatpak-info", F_OK) == 0) {
+	const std::string appDir = dir + "/app/" + flatpakId;
+	std::error_code error;
+
+	if (std::filesystem::is_directory (appDir, error)) {
+	    dir = appDir;
+	}
+    }
+
+    return dir;
+}
+
+DBusMessage*
+WallpaperEngine::Desktop::callBlocking (DBusConnection* connection, DBusMessage* call, std::string& error) {
+    DBusError dbusError;
+    dbus_error_init (&dbusError);
+
+    DBusMessage* reply = dbus_connection_send_with_reply_and_block (connection, call, CALL_TIMEOUT_MS, &dbusError);
+    dbus_message_unref (call);
+
+    if (dbus_error_is_set (&dbusError)) {
+	error = dbusError.message;
+	dbus_error_free (&dbusError);
+	return nullptr;
+    }
+
+    return reply;
+}
+
+bool WallpaperEngine::Desktop::drainBus (DBusConnection* connection) {
+    for (int reads = 0; reads < MAX_READS_PER_DRAIN; reads++) {
+	if (!dbus_connection_read_write (connection, 0)) {
+	    return false;
+	}
+
+	bool dispatched = false;
+
+	while (dbus_connection_get_dispatch_status (connection) == DBUS_DISPATCH_DATA_REMAINS) {
+	    dbus_connection_dispatch (connection);
+	    dispatched = true;
+	}
+
+	if (!dispatched) {
+	    break;
+	}
+    }
+
+    return true;
+}

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

@@ -0,0 +1,15 @@
+#pragma once
+
+#include <dbus/dbus.h>
+#include <string>
+
+namespace WallpaperEngine::Desktop {
+/** XDG_RUNTIME_DIR, inside a Flatpak the app's folder in it (the one the host shares); empty when unset */
+std::string runtimeDirectory ();
+
+/** Blocking call with a 2s timeout, takes ownership of call. Null with error set on failure */
+DBusMessage* callBlocking (DBusConnection* connection, DBusMessage* call, std::string& error);
+
+/** Reads and dispatches everything queued without blocking, false once the connection is gone */
+bool drainBus (DBusConnection* connection);
+} // namespace WallpaperEngine::Desktop

+ 1 - 3
src/WallpaperEngine/Desktop/WindowState.cpp

@@ -7,14 +7,12 @@
 
 using namespace WallpaperEngine::Desktop;
 
-namespace {
-bool containsIgnoringCase (const std::string& haystack, const std::string& needle) {
+bool WallpaperEngine::Desktop::containsIgnoringCase (std::string_view haystack, std::string_view needle) {
     return std::ranges::search (
 	       haystack, needle, [] (unsigned char a, unsigned char b) { return std::tolower (a) == std::tolower (b); }
 	   ).begin ()
 	!= haystack.end ();
 }
-} // namespace
 
 bool WallpaperEngine::Desktop::pausesAnyOf (
     const std::vector<WindowState>& windows, const std::vector<std::string>& outputs,

+ 4 - 0
src/WallpaperEngine/Desktop/WindowState.h

@@ -2,6 +2,7 @@
 
 #include <cstdint>
 #include <string>
+#include <string_view>
 #include <vector>
 
 namespace WallpaperEngine::Application {
@@ -24,6 +25,9 @@ struct WindowState {
     uint32_t flags = 0;
 };
 
+/** ASCII case-insensitive, for --fullscreen-pause-ignore-appid */
+bool containsIgnoringCase (std::string_view haystack, std::string_view needle);
+
 /** WE's per monitor pause: true when a pausing window is on one of outputs */
 bool pausesAnyOf (
     const std::vector<WindowState>& windows, const std::vector<std::string>& outputs,

+ 3 - 19
src/WallpaperEngine/Input/Drivers/KDECursorInput.cpp

@@ -1,5 +1,6 @@
 #include "KDECursorInput.h"
 
+#include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 #include <cstdio>
@@ -155,26 +156,9 @@ bool KDECursorInput::handleMethodCall (DBusMessage* message) {
 }
 
 std::optional<glm::dvec2> KDECursorInput::position () {
+    // KWin sends a call per cursor move, many per frame
     if (m_connection != nullptr) {
-	// KWin sends one call per cursor move, far more often than frames are drawn;
-	// read_write_dispatch only handles a single message and a read pulls in ~2KB at most,
-	// so keep reading and dispatching until the socket has nothing left
-	bool connected = true;
-	for (int reads = 0; connected && reads < 64; reads++) {
-	    connected = dbus_connection_read_write (m_connection, 0);
-
-	    bool dispatched = false;
-	    while (connected && dbus_connection_get_dispatch_status (m_connection) == DBUS_DISPATCH_DATA_REMAINS) {
-		dbus_connection_dispatch (m_connection);
-		dispatched = true;
-	    }
-
-	    if (!dispatched) {
-		break;
-	    }
-	}
-
-	if (!connected) {
+	if (!WallpaperEngine::Desktop::drainBus (m_connection)) {
 	    sLog.error ("KDE cursor input: DBus connection dropped unexpectedly");
 	    m_script.reset ();
 	    dbus_connection_unregister_object_path (m_connection, kObjectPath);

+ 9 - 1
src/WallpaperEngine/Input/Drivers/WaylandMouseInput.cpp

@@ -62,6 +62,7 @@ void WaylandMouseInput::update () {
     if (this->m_kdeCursor) {
 	if (const auto kdeCursor = this->m_kdeCursor->position (); kdeCursor.has_value ()) {
 	    this->m_globalCursor = kdeCursor;
+	    this->m_globalCursorFromX11 = false;
 	    return;
 	}
     }
@@ -74,9 +75,11 @@ void WaylandMouseInput::update () {
     this->m_lastGlobalCursorQuery = now;
 
     auto globalCursor = this->queryHyprlandCursorPosition ();
+    this->m_globalCursorFromX11 = false;
 #ifdef ENABLE_X11
     if (!globalCursor.has_value ()) {
 	globalCursor = this->queryX11CursorPosition ();
+	this->m_globalCursorFromX11 = globalCursor.has_value ();
     }
 #endif /* ENABLE_X11 */
     this->m_globalCursor = globalCursor;
@@ -115,7 +118,8 @@ WaylandMouseInput::positionOn (const WallpaperEngine::Render::Drivers::Output::W
 	return viewport.mousePos;
     }
 
-    if (this->m_globalCursor.has_value ()) {
+    // prefer this surface's own position over a stale XWayland one
+    if (this->m_globalCursor.has_value () && !(this->m_globalCursorFromX11 && viewport.pointerEntered)) {
 	const glm::dvec2 local = *this->m_globalCursor - glm::dvec2 (viewport.globalPosition);
 	return { local.x * scale, (viewport.size.y - local.y) * scale };
     }
@@ -133,6 +137,10 @@ glm::dvec2 WaylandMouseInput::position () const {
 }
 
 WallpaperEngine::Input::MouseClickStatus WaylandMouseInput::leftClick () const {
+    if (!this->m_waylandDriver.getApp ().getContext ().settings.mouse.enabled) {
+	return MouseClickStatus::Released;
+    }
+
     if (this->m_forwardedLeftDown) {
 	return MouseClickStatus::Clicked;
     }

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

@@ -49,6 +49,8 @@ private:
 
     /** logical global position */
     std::optional<glm::dvec2> m_globalCursor;
+    /** XWayland's position goes stale off X11 windows */
+    bool m_globalCursorFromX11 = false;
     std::chrono::steady_clock::time_point m_lastGlobalCursorQuery = {};
     std::chrono::steady_clock::time_point m_lastForwardedPoll = {};
     bool m_forwardedLeftDown = false;

+ 0 - 3
src/WallpaperEngine/Render/Drivers/Detectors/GnomeFullScreenDetector.cpp

@@ -15,9 +15,6 @@ bool GnomeFullScreenDetector::anythingFullscreen () const {
 	return false;
     }
 
-    // while paused the driver doesn't dispatch
-    gnomeShell->dispatch ();
-
     return Desktop::pausesAnyOf (
 	gnomeShell->windows (), this->m_driver.drawnOutputs (), this->getApplicationContext ()
     );

+ 44 - 29
src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.cpp

@@ -1,5 +1,6 @@
 #include "KDEWaylandFullScreenDetector.h"
 
+#include "WallpaperEngine/Desktop/SessionBus.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h"
 
@@ -79,12 +80,13 @@ bool KDEWaylandFullScreenDetector::initializeDBus () {
 
 // WE 2.8 rules (sub_14003D050 / sub_14003BBA0), same as the GNOME extension: visible, unminimized windows on the
 // current desktop; maximized marks its output, the active root window marks focused, and fullscreen if not
-// maximized and at least the output's size
+// maximized and at least the output's size. Show desktop and other activities hide windows. KWin 5: UNSUPPORTED
 std::string KDEWaylandFullScreenDetector::scriptSource () const {
     const std::string service = this->m_serviceName;
 
     return "const service = '" + service + "';\n" + "const objectPath = '" + kObjectPath + "';\n" + "const method = '"
-	+ kMethodName + "';\n" + "const enginePid = " + std::to_string (getpid ()) + ";\n" + R"(
+	+ kMethodName + "';\n" + "const enginePid = " + std::to_string (getpid ()) + ";\n" + "const unsupported = '"
+	+ kUnsupported + "';\n" + R"(
 const MAXIMIZE_FULL = 3;
 let last = '';
 
@@ -95,12 +97,15 @@ function rootOf(window) {
 }
 
 function counts(window) {
-    if (!window || window.deleted || !window.managed || window.minimized || window.pid === enginePid)
+    if (!window || window.deleted || !window.managed || window.minimized || window.hiddenByShowDesktop ||
+        window.pid === enginePid)
         return false;
     if (window.specialWindow || window.popupWindow || window.desktopWindow || window.dock)
         return false;
     if (!window.normalWindow && !window.dialog)
         return false;
+    if (window.activities.length > 0 && window.activities.indexOf(workspace.currentActivity) < 0)
+        return false;
     return window.onAllDesktops || window.desktops.indexOf(workspace.currentDesktop) >= 0;
 }
 
@@ -139,19 +144,32 @@ function watch(window) {
     window.maximizedChanged.connect(report);
     window.minimizedChanged.connect(report);
     window.outputChanged.connect(report);
-    window.frameGeometryChanged.connect(report);
     window.desktopsChanged.connect(report);
+    window.activitiesChanged.connect(report);
+    // connecting a missing signal kills the script
+    if (window.hiddenByShowDesktopChanged)
+        window.hiddenByShowDesktopChanged.connect(report);
+    // fires every frame while moving, only the active window's size matters
+    window.frameGeometryChanged.connect(() => {
+        if (window === rootOf(workspace.activeWindow))
+            report();
+    });
 }
 
-workspace.windowList().forEach(watch);
-workspace.windowAdded.connect(window => {
-    watch(window);
+if (typeof workspace.windowList === 'function') {
+    workspace.windowList().forEach(watch);
+    workspace.windowAdded.connect(window => {
+        watch(window);
+        report();
+    });
+    workspace.windowRemoved.connect(report);
+    workspace.windowActivated.connect(report);
+    workspace.currentDesktopChanged.connect(report);
+    workspace.currentActivityChanged.connect(report);
     report();
-});
-workspace.windowRemoved.connect(report);
-workspace.windowActivated.connect(report);
-workspace.currentDesktopChanged.connect(report);
-report();
+} else {
+    callDBus(service, objectPath, service, method, unsupported);
+}
 )";
 }
 
@@ -182,6 +200,14 @@ DBusHandlerResult KDEWaylandFullScreenDetector::handleMessage (DBusMessage* mess
 }
 
 bool KDEWaylandFullScreenDetector::applyWindows (const std::string& json) {
+    if (json == kUnsupported) {
+	sLog.error (
+	    "KDE window detection needs Plasma 6, wallpapers won't pause for maximized, fullscreen or focused windows"
+	);
+	this->m_windows.clear ();
+	return false;
+    }
+
     const auto parsed = nlohmann::json::parse (json, nullptr, false);
 
     if (!parsed.is_array ()) {
@@ -205,26 +231,15 @@ bool KDEWaylandFullScreenDetector::applyWindows (const std::string& json) {
 }
 
 void KDEWaylandFullScreenDetector::dispatch () const {
-    if (this->m_connection == nullptr) {
+    if (this->m_connection == nullptr || this->m_disconnected) {
 	return;
     }
 
-    // a read pulls in ~2KB at most
-    for (int reads = 0; reads < 64; reads++) {
-	if (!dbus_connection_read_write (this->m_connection, 0)) {
-	    break;
-	}
-
-	bool dispatched = false;
-
-	while (dbus_connection_get_dispatch_status (this->m_connection) == DBUS_DISPATCH_DATA_REMAINS) {
-	    dbus_connection_dispatch (this->m_connection);
-	    dispatched = true;
-	}
-
-	if (!dispatched) {
-	    break;
-	}
+    // a stale state could pause forever
+    if (!Desktop::drainBus (this->m_connection)) {
+	sLog.error ("KDE window detection: the session bus connection dropped, pausing for windows stops");
+	this->m_disconnected = true;
+	this->m_windows.clear ();
     }
 }
 

+ 4 - 1
src/WallpaperEngine/Render/Drivers/Detectors/KDEWaylandFullScreenDetector.h

@@ -45,11 +45,14 @@ private:
     mutable DBusConnection* m_connection = nullptr;
     std::string m_serviceName;
     std::unique_ptr<Desktop::KWinScript> m_script;
-    std::vector<Desktop::WindowState> m_windows;
+    mutable std::vector<Desktop::WindowState> m_windows;
+    mutable bool m_disconnected = false;
 
     static constexpr const char* kServiceName = "org.linuxwallpaperengine.WaylandDetector";
     static constexpr const char* kObjectPath = "/org/linuxwallpaperengine/WaylandDetector";
     static constexpr const char* kMethodName = "OnWindows";
+    /** the script's reply on KWin 5 */
+    static constexpr const char* kUnsupported = "UNSUPPORTED";
 };
 
 } // namespace WallpaperEngine::Render::Drivers::Detectors

+ 2 - 34
src/WallpaperEngine/Render/Drivers/Detectors/WaylandFullScreenDetector.cpp

@@ -6,6 +6,7 @@
 #include "WallpaperEngine/Desktop/KDESession.h"
 #endif
 
+#include "WallpaperEngine/Desktop/WindowState.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/Drivers/VideoFactories.h"
 #include "WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h"
@@ -13,44 +14,11 @@
 #include <cstdlib>
 #include <cstring>
 #include <string>
-#include <string_view>
 
 namespace WallpaperEngine::Render::Drivers::Detectors {
 
 namespace {
 
-    bool icontains (std::string_view haystack, std::string_view needle) {
-	if (needle.empty ()) {
-	    return true;
-	}
-	if (haystack.empty ()) {
-	    return false;
-	}
-
-	auto toLower = [] (unsigned char c) {
-	    if (c >= 'A' && c <= 'Z') {
-		return static_cast<unsigned char> (c - 'A' + 'a');
-	    }
-	    return c;
-	};
-
-	for (size_t i = 0; i + needle.size () <= haystack.size (); ++i) {
-	    bool match = true;
-	    for (size_t j = 0; j < needle.size (); ++j) {
-		if (toLower (static_cast<unsigned char> (haystack[i + j]))
-		    != toLower (static_cast<unsigned char> (needle[j]))) {
-		    match = false;
-		    break;
-		}
-	    }
-	    if (match) {
-		return true;
-	    }
-	}
-
-	return false;
-    }
-
     struct FullscreenState {
 	bool pending = false;
 	bool current = false;
@@ -111,7 +79,7 @@ namespace {
 		if (ignore.empty ()) {
 		    continue;
 		}
-		if (icontains (appId, ignore)) {
+		if (Desktop::containsIgnoringCase (appId, ignore)) {
 		    return false;
 		}
 	    }

+ 12 - 7
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp

@@ -62,12 +62,8 @@ handleXdgToplevelConfigure (void* data, xdg_toplevel*, int32_t width, int32_t he
     static_cast<WaylandOutputViewport*> (data)->pendingToplevelSize = { width, height };
 }
 
-static void handleXdgToplevelClose (void* data, xdg_toplevel*) {
-    const auto viewport = static_cast<WaylandOutputViewport*> (data);
-
-    viewport->closed = true;
-    viewport->rendering = false;
-}
+// ignored, a wallpaper closed by Alt+F4 (focusable on GNOME 45) would never come back
+static void handleXdgToplevelClose (void*, xdg_toplevel*) { }
 
 static void handleXdgToplevelBounds (void*, xdg_toplevel*, int32_t, int32_t) { }
 
@@ -97,6 +93,15 @@ static void geometry (
 static void mode (void* data, wl_output* output, uint32_t flags, int32_t width, int32_t height, int32_t refresh) {
     const auto viewport = static_cast<WaylandOutputViewport*> (data);
 
+    // a mode change alone sends a toplevel no new configure
+    if (viewport->xdgToplevel) {
+	if (viewport->initialized) {
+	    viewport->getDriver ()->getOutput ().reset ();
+	}
+
+	return;
+    }
+
     // physical pixels; logicalSize comes from xdg-output or the layer shell configure
     viewport->size = { width, height };
     viewport->viewport = { 0, 0, viewport->size.x * viewport->scale, viewport->size.y * viewport->scale };
@@ -551,7 +556,7 @@ void WaylandOutputViewport::setWantsPointerButtons (bool wants) {
 
 void WaylandOutputViewport::renderFrame () {
     // the driver frees closed viewports on its next pass
-    if (this->closed) {
+    if (this->closed || this->m_driver->isDispatchingWhilePaused ()) {
 	return;
     }
 

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

@@ -64,6 +64,8 @@ namespace Output {
 	org_kde_plasma_surface* plasmaSurface = nullptr;
 #endif
 	glm::dvec2 mousePos = { 0, 0 };
+	/** mousePos is valid */
+	bool pointerEntered = false;
 	WallpaperEngine::Input::MouseClickStatus leftClick = WallpaperEngine::Input::MouseClickStatus::Released;
 	WallpaperEngine::Input::MouseClickStatus rightClick = WallpaperEngine::Input::MouseClickStatus::Released;
 	/** empty input region, clicks go to the desktop below */

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

@@ -46,6 +46,8 @@ public:
      */
     [[nodiscard]] virtual bool isHDRAvailable () const { return false; }
     virtual void dispatchEventQueue () = 0;
+    /** Reads window events without drawing, used while paused */
+    virtual void dispatchWhilePaused () { }
     [[nodiscard]] WallpaperApplication& getApp () const;
     [[nodiscard]] Input::InputContext& getInputContext ();
 

+ 51 - 0
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.cpp

@@ -43,6 +43,7 @@ static void handlePointerEnter (
     }
 
     driver->viewportInFocus = viewport;
+    viewport->pointerEntered = true;
     viewport->mousePos = { wl_fixed_to_double (surface_x) * viewport->scale,
 			   (viewport->size.y - wl_fixed_to_double (surface_y)) * viewport->scale };
     wl_surface_set_buffer_scale (viewport->cursorSurface, viewport->scale);
@@ -781,6 +782,56 @@ void WaylandOpenGLDriver::dispatchEventQueue () {
     m_frameCounter++;
 }
 
+void WaylandOpenGLDriver::dispatchWhilePaused () {
+    // a visible paused wallpaper still gets pointer events, unread they overflow the socket
+    if (this->m_gnomeShell) {
+	this->m_gnomeShell->dispatch ();
+
+	if (this->m_gnomeShell->vanished ()) {
+	    m_requestedExit = true;
+	    return;
+	}
+    }
+
+    this->reapClosedOutputs ();
+
+    wl_display* display = m_waylandContext.display;
+    this->m_dispatchingWhilePaused = true;
+
+    while (wl_display_prepare_read (display) != 0) {
+	if (wl_display_dispatch_pending (display) == -1) {
+	    m_requestedExit = true;
+	    this->m_dispatchingWhilePaused = false;
+	    return;
+	}
+    }
+
+    wl_display_flush (display);
+
+    pollfd fd = { .fd = wl_display_get_fd (display), .events = POLLIN, .revents = 0 };
+
+    if (poll (&fd, 1, 0) > 0) {
+	if (wl_display_read_events (display) == -1) {
+	    m_requestedExit = true;
+	}
+    } else {
+	wl_display_cancel_read (display);
+    }
+
+    if (!m_requestedExit && wl_display_dispatch_pending (display) == -1) {
+	m_requestedExit = true;
+    }
+
+    this->m_dispatchingWhilePaused = false;
+
+    // callbacks that came in meanwhile are owed a frame, the watchdog draws it on resume
+    for (auto* o : this->m_screens) {
+	if (o->hasShellSurface () && o->frameCallback == nullptr) {
+	    o->lastSwap = {};
+	}
+    }
+}
+
 Output::Output& WaylandOpenGLDriver::getOutput () { return this->m_output; }
 
 float WaylandOpenGLDriver::getRenderTime () const {

+ 4 - 0
src/WallpaperEngine/Render/Drivers/WaylandOpenGLDriver.h

@@ -92,6 +92,9 @@ public:
     glm::ivec2 getFramebufferSize () const override;
     uint32_t getFrameCounter () const override;
     void dispatchEventQueue () override;
+    void dispatchWhilePaused () override;
+    /** frame callbacks don't draw while dispatchWhilePaused runs */
+    [[nodiscard]] bool isDispatchingWhilePaused () const { return this->m_dispatchingWhilePaused; }
     [[nodiscard]] void* getProcAddress (const char* name) const override;
     [[nodiscard]] void* getWaylandDisplay () const override;
     [[nodiscard]] bool isHDRAvailable () const override;
@@ -138,6 +141,7 @@ private:
 
     uint32_t m_frameCounter = 0;
     bool m_layerSurfacesReady = false;
+    bool m_dispatchingWhilePaused = false;
     ApplicationContext& m_context;
     std::unique_ptr<Desktop::GnomeShell> m_gnomeShell;
     WaylandMouseInput m_mouseInput;

+ 20 - 1
tests/desktops/test_gnome.py

@@ -173,7 +173,9 @@ def test_engine_stops_without_the_extension(gnome, engine, tmp_path):
         assert gnome.eval(f"!!{WALLPAPER}") == "false", "the wallpaper window outlived the extension"
 
         refused = _engine(gnome, engine, tmp_path / "refused.log")
-        assert refused.wait(20) != 0
+        code = refused.wait(20)
+        # a signal exit (abort) fails too
+        assert 0 < code < 128, f"the engine exited with {code} instead of an error"
         assert "without the GNOME Shell extension" in (tmp_path / "refused.log").read_text(errors="replace")
     finally:
         gnome.run(["gnome-extensions", "enable", UUID])
@@ -182,6 +184,23 @@ def test_engine_stops_without_the_extension(gnome, engine, tmp_path):
             process.wait(10)
 
 
+def test_wallpaper_survives_a_close_request(gnome, engine, tmp_path):
+    """Alt+F4 on a focused wallpaper (45 keeps it a normal window) must not remove it"""
+    log = tmp_path / "engine.log"
+    process = _engine(gnome, engine, log)
+    try:
+        time.sleep(8)
+        assert _renders(log), "the engine does not render on GNOME"
+        gnome.eval(f"{WALLPAPER}.delete(global.display.get_current_time_roundtrip()); 1")
+        time.sleep(2)
+        assert process.poll() is None, "the engine stopped on a close request"
+        assert gnome.eval(f"!!{WALLPAPER}") == "true", "the wallpaper window is gone"
+        assert _renders(log), "the wallpaper stopped rendering after a close request"
+    finally:
+        process.terminate()
+        process.wait(10)
+
+
 def test_overview_shows_the_live_wallpaper(gnome, engine, tmp_path):
     log = tmp_path / "engine.log"
     gnome.eval("Main.overview.show(); 1")

+ 22 - 0
tests/desktops/test_kde.py

@@ -91,3 +91,25 @@ def test_pause_is_per_output(desktop_factory, engine, tmp_path):
         for process in processes:
             process.terminate()
             process.wait(10)
+
+
+def test_plasma5(desktop_factory, engine, tmp_path):
+    """KWin 5.27 runs both scripts (/<id>, not /Scripting/Script<id>); the window script says it needs Plasma 6"""
+    kde5 = desktop_factory("kde5")
+    log = tmp_path / "engine.log"
+    process = _engine(kde5, engine, log, kde5.output_names()[0])
+    probe = None
+    try:
+        time.sleep(8)
+        assert _renders(log), "the engine does not render on Plasma 5"
+        text = log.read_text(errors="replace")
+        assert "could not load its KWin script" not in text
+        assert "KDE window detection needs Plasma 6" in text
+        probe = _window(kde5, "maximized")
+        time.sleep(4)
+        assert _renders(log), "a maximized window paused the wallpaper without window detection"
+    finally:
+        if probe is not None:
+            terminate([probe.pid])
+        process.terminate()
+        process.wait(10)

+ 3 - 1
tools/desktops/__main__.py

@@ -10,6 +10,7 @@ FEDORA_PACKAGES = REPO / "tools/desktops/rootfs-fedora.txt"
 ARCH_PACKAGES = REPO / "tools/desktops/rootfs-arch.txt"
 UBUNTU_PACKAGES = REPO / "tools/desktops/rootfs-ubuntu.txt"
 FEDORA_GNOME_PACKAGES = REPO / "tools/desktops/rootfs-fedora-gnome.txt"
+KDE5_PACKAGES = REPO / "tools/desktops/rootfs-ubuntu-kde5.txt"
 
 
 def _apt(archive):
@@ -49,6 +50,7 @@ def setup(which):
             ("45", "23.10", "old-releases"), ("46", "24.04", "archive"), ("47", "24.10", "old-releases"),
             ("48", "25.04", "archive"))},
         "gnome49": ("fedora:43", FEDORA_GNOME_PACKAGES, ["dnf", "install", "-y", "--setopt=install_weak_deps=False"]),
+        "kde5": ("ubuntu:24.04", KDE5_PACKAGES, _apt("archive")),
     }[which]
     root = ROOTFS[which]
     if not root.is_dir():
@@ -69,7 +71,7 @@ def main():
     sub = parser.add_subparsers(dest="command", required=True)
     sub.add_parser("list", help="the sessions and where each would run")
     sub.add_parser("setup", help="create the rootfs for sessions that are not installed natively").add_argument(
-        "which", choices=("fedora", "arch", "gnome45", "gnome46", "gnome47", "gnome48", "gnome49", "ding"))
+        "which", choices=("fedora", "arch", "gnome45", "gnome46", "gnome47", "gnome48", "gnome49", "kde5", "ding"))
     start = sub.add_parser("start", help="start a session")
     start.add_argument("name", choices=sorted(KINDS))
     start.add_argument("--size", default="1920x1080")

+ 2 - 0
tools/desktops/rootfs-ubuntu-kde5.txt

@@ -0,0 +1,2 @@
+kwin-wayland kscreen dbus dbus-x11 xwayland wayland-utils plasma-wayland-protocols
+gir1.2-gtk-4.0 python3-gi python3-dbus python3-dbusmock

+ 1 - 0
tools/desktops/runner.py

@@ -22,6 +22,7 @@ ROOTFS = {
     "gnome47": ROOTFS_DIR / "ubuntu-24.10-gnome",
     "gnome48": ROOTFS_DIR / "ubuntu-25.04-gnome",
     "gnome49": ROOTFS_DIR / "fedora-43-gnome",
+    "kde5": ROOTFS_DIR / "ubuntu-24.04-kde5",
 }
 BIN_DIRS = ("usr/bin", "usr/sbin", "usr/libexec", "bin", "sbin")
 SYSTEM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

+ 15 - 3
tools/desktops/session.py

@@ -420,12 +420,14 @@ class Kde(Session):
 
     name, short, desktop = "kde", "k", "KDE"
     needs = ("kwin_wayland", "kscreen-doctor")
+    plasma = "6"
+    xwayland = True
     sysbus = True
 
     def _launch(self):
         width, height = self.size
         env = {
-            "XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "KDE", "KDE_FULL_SESSION": "true", "KDE_SESSION_VERSION": "6",
+            "XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "KDE", "KDE_FULL_SESSION": "true", "KDE_SESSION_VERSION": self.plasma,
             "QT_QPA_PLATFORM": "wayland", "KWIN_SCREENSHOT_NO_PERMISSION_CHECKS": "1",
             # for kwin_fake_input.c
             "KWIN_WAYLAND_NO_PERMISSION_CHECKS": "1",
@@ -433,7 +435,7 @@ class Kde(Session):
         self.session_env.update(env)
         self.spawn("kwin", ["kwin_wayland", "--virtual", "--width", str(width), "--height", str(height),
                             "--output-count", str(self.outputs), "--socket", "lwe-kde", "--no-lockscreen",
-                            "--xwayland"], env)
+                            *(["--xwayland"] if self.xwayland else [])], env)
         self.session_env["WAYLAND_DISPLAY"] = "lwe-kde"
         self.wait_socket("lwe-kde")
         wait_for("KWin on the session bus", lambda: self._bus_name("org.kde.KWin"), 40)
@@ -468,6 +470,16 @@ class KdeDual(Kde):
         super().__init__(size, outputs)
 
 
+class Kde5(Kde):
+    """Plasma 5.27's KWin from the Ubuntu 24.04 rootfs (setup kde5): older scripting API"""
+
+    name, short = "kde5", "k5"
+    userlands = ("kde5",)
+    plasma = "5"
+    # KWin 5 quits without /tmp/.X11-unix for Xwayland, the rootfs has none
+    xwayland = False
+
+
 class Gnome(Session):
     """GNOME Shell as a headless Wayland display server"""
 
@@ -736,5 +748,5 @@ WM_CLASSES = [
 
 KINDS = {
     kind.name: kind
-    for kind in (Sway, Labwc, Wayfire, River, Hyprland, Niri, Cosmic, Kde, KdeDual, Gnome, Gnome45, Gnome46, Gnome47, Gnome48, Gnome49, GnomeDing, Gnome45Ding, Gnome46Ding, Xfce, Cinnamon, Mate, Lxqt, *WM_CLASSES)
+    for kind in (Sway, Labwc, Wayfire, River, Hyprland, Niri, Cosmic, Kde, KdeDual, Kde5, Gnome, Gnome45, Gnome46, Gnome47, Gnome48, Gnome49, GnomeDing, Gnome45Ding, Gnome46Ding, Xfce, Cinnamon, Mate, Lxqt, *WM_CLASSES)
 }