Files

111 lines
4.9 KiB
Python

"""KDE Plasma's window manager (KWin) on Wayland: which windows there are, where, and which is active.
A Wayland program can't see other programs' windows. KWin can run a small script for us (org.kde.kwin.Scripting
over D-Bus), and the script calls back on our D-Bus connection with the list. Used for window capture on a
Wayland session: to find a game's native Wayland window by its process, title or class, to tell it from an
XWayland one, and to know where it is so the engine's picture can sit over it (framegen/window_portal.py).
Checked on Plasma 6.8 Wayland. Needs the `jeepney` package. Other desktops: `available()` is False.
"""
from __future__ import annotations
import json
import os
import tempfile
from dataclasses import dataclass
SCRIPT = """
const out = [];
for (const w of workspace.windowList()) {
if (!w.normalWindow) continue;
const f = w.frameGeometry; // a window's screencast holds its title bar too
// No XWayland flag: KWin 6.8's windows have no windowId (it is undefined for XWayland windows too, checked), so
// the engine tells XWayland windows by the X server's own client list (window_portal.x_client_pids).
out.push({pid: w.pid, caption: w.caption, cls: w.resourceClass, x: f.x, y: f.y, w: f.width, h: f.height,
active: w === workspace.activeWindow, minimized: w.minimized, output: w.output ? w.output.name : "", id: String(w.internalId)});
}
callDBus("%s", "/summit/kwin", "org.summit.KWinReport", "windows", JSON.stringify(out));
"""
@dataclass(frozen=True)
class KWindow:
pid: int
caption: str
cls: str
x: int
y: int
w: int
h: int
active: bool
x11: bool # always False: KWin 6.8 can't say (see SCRIPT); window_portal.native_candidates asks the X server
minimized: bool
output: str # the monitor it is on, e.g. "DP-1"
id: str # KWin's own id for it (stays the same while it's open)
def parse(text: str) -> list[KWindow]:
"""The script's JSON as KWindows (pure: unit tested)."""
out = []
for d in json.loads(text):
try:
out.append(KWindow(int(d.get("pid") or 0), str(d.get("caption") or ""), str(d.get("cls") or "").lower(),
int(d["x"]), int(d["y"]), int(d["w"]), int(d["h"]), bool(d.get("active")),
bool(d.get("x11")), bool(d.get("minimized")), str(d.get("output") or ""),
str(d.get("id") or "")))
except (KeyError, TypeError, ValueError):
continue
return out
def available(env=os.environ) -> bool:
return "kde" in env.get("XDG_CURRENT_DESKTOP", "").lower() and bool(env.get("WAYLAND_DISPLAY"))
class KWin:
"""One D-Bus connection to KWin; windows() runs the script once (about 10 ms) and returns what it reported."""
def __init__(self) -> None:
from jeepney.io.blocking import open_dbus_connection
self.conn = open_dbus_connection(bus="SESSION")
self._n = 0
def windows(self, timeout: float = 3.0) -> list[KWindow]:
from jeepney import DBusAddress, MatchRule, new_method_call, new_method_return
scripting = DBusAddress("/Scripting", bus_name="org.kde.KWin", interface="org.kde.kwin.Scripting")
self._n += 1
name = f"summit-windows-{os.getpid()}-{self._n}"
fd, path = tempfile.mkstemp(prefix="summit-kwin-", suffix=".js")
try:
with os.fdopen(fd, "w") as f:
f.write(SCRIPT % self.conn.unique_name)
reply = self.conn.send_and_get_reply(new_method_call(scripting, "loadScript", "ss", (path, name)), timeout=timeout)
if reply.header.message_type.name == "error":
raise RuntimeError(f"KWin would not load the script: {reply.body}")
sid = reply.body[0]
rule = MatchRule(type="method_call", path="/summit/kwin")
with self.conn.filter(rule) as q:
script = DBusAddress(f"/Scripting/Script{sid}", bus_name="org.kde.KWin", interface="org.kde.kwin.Script")
self.conn.send_and_get_reply(new_method_call(script, "run"), timeout=timeout)
msg = self.conn.recv_until_filtered(q, timeout=timeout)
self.conn.send(new_method_return(msg))
return parse(msg.body[0])
finally:
try:
self.conn.send_and_get_reply(new_method_call(scripting, "unloadScript", "s", (name,)), timeout=timeout)
except Exception: # noqa: BLE001 - cleaning up
pass
os.unlink(path)
def close(self) -> None:
try:
self.conn.close()
except Exception: # noqa: BLE001
pass
def as_xwindows(windows: list[KWindow]):
"""KWin's windows in window_x11's form, so window_x11.pick() chooses among them by the same rules ("pid:N",
"class:NAME", part of a title); xid is the index in `windows`."""
from .window_x11 import XWindow
return [XWindow(i, w.caption, w.cls, w.pid, w.w, w.h) for i, w in enumerate(windows)]