session.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. """Headless sessions of every desktop environment and compositor, private to the caller.
  2. Each Session owns a directory under BASE: a runtime dir with the Wayland socket, the session bus and the compositor's
  3. own sockets, a home, the logs and state.json. Programs of the session run in its userland (see runner.py), the
  4. programs under test (the engine, we_manager) run on the caller's side with client_env().
  5. """
  6. import glob
  7. import json
  8. import os
  9. import re
  10. import shutil
  11. import subprocess
  12. import time
  13. from pathlib import Path
  14. from .runner import BASE, REPO, Userland, kill_with_runtime_dir, terminate, wait_for
  15. KDE_VARIABLES = ("DISPLAY", "DESKTOP_SESSION", "XDG_SESSION_DESKTOP", "KDE_FULL_SESSION")
  16. class Unsupported(Exception):
  17. pass
  18. class Session:
  19. name = ""
  20. # short, Hyprland's IPC socket path has to fit in 108 bytes
  21. short = ""
  22. needs = ()
  23. sysbus = False
  24. desktop = ""
  25. def __init__(self, size=(1920, 1080), outputs=1):
  26. self.size = tuple(size)
  27. self.outputs = outputs
  28. self.dir = BASE / self.short
  29. self.run_dir = self.dir / "run"
  30. self.home = self.dir / "home"
  31. self.userland = None
  32. self.pids = []
  33. self.session_env = {}
  34. # more variables of the session (a compositor's IPC socket), and facts about it that are not variables
  35. self.extra = {}
  36. self.info = {}
  37. # ----- lookup
  38. @classmethod
  39. def of(cls, name, **options):
  40. try:
  41. return KINDS[name](**options)
  42. except KeyError:
  43. raise SystemExit(f"unknown session {name}, one of: {', '.join(KINDS)}")
  44. @classmethod
  45. def load(cls, name):
  46. session = cls.of(name)
  47. state = json.loads((session.dir / "state.json").read_text())
  48. session.userland = Userland(state["userland"])
  49. session.pids = state["pids"]
  50. session.session_env = state["session_env"]
  51. session.extra = state["extra"]
  52. session.info = state["info"]
  53. session.size = tuple(state["size"])
  54. session.outputs = state["outputs"]
  55. return session
  56. @classmethod
  57. def available(cls):
  58. """userland name or None per session name, whether it can be started here"""
  59. result = {}
  60. for name, kind in KINDS.items():
  61. try:
  62. result[name] = Userland.pick(*kind.needs).name
  63. except RuntimeError:
  64. result[name] = None
  65. return result
  66. def is_running(self):
  67. state = self.dir / "state.json"
  68. if not state.exists():
  69. return False
  70. pids = json.loads(state.read_text())["pids"]
  71. return bool(pids) and os.path.exists(f"/proc/{pids[0]}")
  72. # ----- lifecycle
  73. def start(self):
  74. if self.is_running():
  75. return self
  76. self.stop()
  77. shutil.rmtree(self.dir, ignore_errors=True)
  78. self.run_dir.mkdir(parents=True, mode=0o700)
  79. self.home.mkdir(parents=True)
  80. self.userland = Userland.pick(*self.needs)
  81. try:
  82. self._start_bus()
  83. if self.sysbus:
  84. self._start_system_bus()
  85. self._launch()
  86. except BaseException:
  87. self.stop()
  88. raise
  89. self._save()
  90. return self
  91. def stop(self):
  92. if self.dir.exists() and (self.dir / "state.json").exists():
  93. self.pids = json.loads((self.dir / "state.json").read_text())["pids"]
  94. terminate(list(reversed(self.pids)))
  95. if self.dir.exists():
  96. kill_with_runtime_dir(self.run_dir)
  97. self.pids = []
  98. state = self.dir / "state.json"
  99. if state.exists():
  100. state.unlink()
  101. def _save(self):
  102. (self.dir / "state.json").write_text(json.dumps({
  103. "userland": self.userland.name, "pids": self.pids, "session_env": self.session_env, "extra": self.extra, "info": self.info,
  104. "size": self.size, "outputs": self.outputs,
  105. }))
  106. (self.dir / "env").write_text(self.shell_exports())
  107. # ----- environments
  108. def env(self):
  109. """for the programs that run in the session's userland"""
  110. env = {
  111. "XDG_RUNTIME_DIR": str(self.run_dir),
  112. "DBUS_SESSION_BUS_ADDRESS": f"unix:path={self.run_dir}/bus",
  113. "HOME": str(self.home),
  114. "XDG_CONFIG_HOME": str(self.home / ".config"),
  115. "XDG_DATA_HOME": str(self.home / ".local/share"),
  116. "XDG_CACHE_HOME": str(self.home / ".cache"),
  117. "XDG_STATE_HOME": str(self.home / ".local/state"),
  118. }
  119. address = self.run_dir / "system-bus-address"
  120. if address.exists():
  121. env["DBUS_SYSTEM_BUS_ADDRESS"] = address.read_text().strip()
  122. env.update(self.session_env)
  123. env.update(self.extra)
  124. return env
  125. def client_env(self):
  126. """for programs under test, started on the caller's side: only what finds this session"""
  127. env = {
  128. key: value for key, value in self.env().items()
  129. if key in ("XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP",
  130. "WAYLAND_DISPLAY", "DISPLAY", "KDE_FULL_SESSION", "KDE_SESSION_VERSION")
  131. }
  132. env.update(self.extra)
  133. # never the desktop's audio server, a sandbox sees it
  134. env["PULSE_SERVER"] = "unix:/nonexistent"
  135. env["PIPEWIRE_REMOTE"] = "/nonexistent"
  136. return env
  137. def shell_exports(self):
  138. env = self.client_env()
  139. lines = [f"export {key}={value}" for key, value in env.items()]
  140. unset = [key for key in KDE_VARIABLES if key not in env]
  141. return "\n".join(lines + [f"unset {' '.join(unset)}"]) + "\n"
  142. # ----- running programs
  143. def spawn(self, name, argv, env=None, userland=None):
  144. """a long running program of the session, logged to <dir>/<name>.log"""
  145. userland = userland or self.userland
  146. process = userland.spawn(argv, {**self.env(), **(env or {})}, self.dir / f"{name}.log")
  147. self.pids.append(process.pid)
  148. return process
  149. def run(self, argv, env=None, timeout=60):
  150. """a short program in the session's userland, its CompletedProcess"""
  151. return self.userland.run(argv, {**self.env(), **(env or {})}, timeout=timeout)
  152. def client(self, argv, log=None, env=None):
  153. """a program under test on the caller's side, in the session's environment"""
  154. base = {"PATH": os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", "/tmp"), "LANG": "C.UTF-8"}
  155. out = open(log or self.dir / "client.log", "ab")
  156. return subprocess.Popen(
  157. argv, env={**base, **self.client_env(), **(env or {})}, stdout=out, stderr=subprocess.STDOUT,
  158. stdin=subprocess.DEVNULL, start_new_session=True,
  159. )
  160. def shot(self, path):
  161. """screenshot to path, taken in the session's userland"""
  162. scratch = self.dir / "shot.png"
  163. scratch.unlink(missing_ok=True)
  164. self._shot(scratch)
  165. shutil.copyfile(scratch, path)
  166. def _shot(self, path):
  167. raise Unsupported(f"no screenshot method for {self.name} yet")
  168. def output_names(self):
  169. """the outputs a program can be told to use with --screen-root"""
  170. if "WAYLAND_DISPLAY" in self.session_env:
  171. # the socket is reachable from the caller's side too, and not every userland has wayland-info (Arch's)
  172. userland = Userland("native") if Userland("native").has("wayland-info") else self.userland
  173. out = userland.run(["wayland-info"], self.env()).stdout
  174. names = []
  175. for block in re.split(r"(?=^interface: )", out, flags=re.M):
  176. if block.startswith("interface: 'wl_output'"):
  177. names += [name.strip() for name in re.findall(r"^\s+name: (.+)$", block, re.M)]
  178. return names
  179. return self._x_outputs()
  180. def _x_outputs(self):
  181. return []
  182. def windows(self):
  183. return []
  184. # ----- buses
  185. def _start_bus(self):
  186. self.spawn("dbus", ["dbus-daemon", "--session", "--nofork", "--nopidfile", f"--address=unix:path={self.run_dir}/bus"])
  187. wait_for("the session bus", (self.run_dir / "bus").exists, 15)
  188. def _start_system_bus(self):
  189. """stand-ins for the systemd services Cinnamon and GNOME need at startup"""
  190. self.spawn("sysbus", ["python3", str(REPO / "tools/desktops/fake_system.py"), str(self.run_dir / "system-bus-address")])
  191. wait_for("the fake system bus", lambda: (self.run_dir / "system-bus-address").exists(), 30)
  192. def _bus_name(self, name):
  193. reply = self.run(["dbus-send", "--session", "--print-reply", "--dest=org.freedesktop.DBus", "/org/freedesktop/DBus",
  194. "org.freedesktop.DBus.NameHasOwner", f"string:{name}"])
  195. return "boolean true" in reply.stdout
  196. def _launch(self):
  197. raise NotImplementedError
  198. # ----- shared helpers
  199. def _socket(self, pattern):
  200. for path in sorted(glob.glob(str(self.run_dir / pattern))):
  201. if not path.endswith(".lock"):
  202. return path
  203. return None
  204. def wait_socket(self, pattern, timeout=40):
  205. return wait_for(f"{pattern} in {self.run_dir}", lambda: self._socket(pattern), timeout)
  206. class Wlroots(Session):
  207. """sway, labwc, wayfire and river on wlroots' headless backend"""
  208. program = ""
  209. def _wlroots_env(self):
  210. env = {
  211. "WLR_BACKENDS": "headless", "WLR_LIBINPUT_NO_DEVICES": "1", "WLR_HEADLESS_OUTPUTS": str(self.outputs),
  212. # nothing here may reach the desktop's session or take its GPU
  213. "LIBSEAT_BACKEND": "seatd", "SEATD_SOCK": "/nonexistent",
  214. }
  215. for key in ("WLR_RENDER_DRM_DEVICE", "WLR_RENDERER"):
  216. if key in os.environ:
  217. env[key] = os.environ[key]
  218. return env
  219. def _config(self):
  220. return []
  221. def _launch(self):
  222. argv = [self.program, *self._config()]
  223. self.spawn(self.program, argv, self._wlroots_env())
  224. socket = self.wait_socket("wayland-[0-9]*")
  225. self.session_env.update({
  226. "WAYLAND_DISPLAY": os.path.basename(socket), "XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": self.desktop,
  227. })
  228. self._ready()
  229. def _ready(self):
  230. # wlroots' headless outputs start at 1280x720
  231. width, height = self.size
  232. for index in range(1, self.outputs + 1):
  233. self.run(["wlr-randr", "--output", f"HEADLESS-{index}", "--custom-mode", f"{width}x{height}"],
  234. {"WAYLAND_DISPLAY": self.session_env["WAYLAND_DISPLAY"]})
  235. def _shot(self, path):
  236. result = self.run(["grim", str(path)])
  237. if result.returncode != 0:
  238. raise RuntimeError(f"grim failed: {result.stderr.strip()}")
  239. class Sway(Wlroots):
  240. name, short, program, desktop = "sway", "s", "sway", "sway"
  241. needs = ("sway", "swaymsg", "grim")
  242. def _config(self):
  243. width, height = self.size
  244. (self.dir / "sway.conf").write_text(
  245. f"output * resolution {width}x{height}\nxwayland disable\ndefault_border none\nswaybg_command -\n"
  246. )
  247. return ["-c", str(self.dir / "sway.conf")]
  248. def _ready(self):
  249. self.extra["SWAYSOCK"] = wait_for("sway's IPC socket", lambda: self._socket("sway-ipc.*.sock"), 30)
  250. class Labwc(Wlroots):
  251. name, short, program, desktop = "labwc", "l", "labwc", "labwc"
  252. needs = ("labwc", "wlr-randr", "grim")
  253. def _config(self):
  254. config = self.dir / "config"
  255. config.mkdir()
  256. # the compositors that run as a window of this one fill its output
  257. (config / "rc.xml").write_text(
  258. '<?xml version="1.0"?>\n<labwc_config>\n <windowRules>\n'
  259. + "".join(
  260. f' <windowRule identifier="{app}"><action name="ToggleFullscreen"/></windowRule>\n'
  261. for app in ("Hyprland", "niri", "cosmic-comp")
  262. )
  263. + " </windowRules>\n</labwc_config>\n"
  264. )
  265. return ["-C", str(config)]
  266. class Wayfire(Wlroots):
  267. name, short, program, desktop = "wayfire", "w", "wayfire", "wayfire"
  268. needs = ("wayfire", "wlr-randr", "grim")
  269. class River(Wlroots):
  270. name, short, program, desktop = "river", "r", "river", "river"
  271. needs = ("river", "wlr-randr", "grim")
  272. def _config(self):
  273. init = self.dir / "init"
  274. init.write_text("#!/bin/sh\n")
  275. init.chmod(0o755)
  276. return ["-c", str(init)]
  277. class Nested(Session):
  278. """Hyprland, niri and COSMIC have no headless backend (they would take the GPU through DRM), they run as a window
  279. of a headless labwc"""
  280. program = ""
  281. def _launch(self):
  282. if Labwc().is_running():
  283. parent = Session.load("labwc")
  284. else:
  285. parent = Labwc(self.size, 1).start()
  286. parent.info["implicit"] = True
  287. parent._save()
  288. socket = f"{parent.run_dir}/{parent.session_env['WAYLAND_DISPLAY']}"
  289. argv, env = self._command()
  290. self.spawn(self.program, argv, {"WAYLAND_DISPLAY": socket, "LIBSEAT_BACKEND": "seatd", "SEATD_SOCK": "/nonexistent", **env})
  291. self.session_env.update({"XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": self.desktop})
  292. self._wait()
  293. def _command(self):
  294. return [self.program], {}
  295. def _wait(self):
  296. self.session_env["WAYLAND_DISPLAY"] = os.path.basename(self.wait_socket("wayland-[0-9]*"))
  297. def stop(self):
  298. super().stop()
  299. # the labwc they run in goes with the last of them, unless it was started on its own
  300. labwc = Labwc()
  301. if labwc.is_running() and Session.load("labwc").info.get("implicit") and not any(
  302. kind().is_running() for kind in (Hyprland, Niri, Cosmic)
  303. ):
  304. labwc.stop()
  305. def _shot(self, path):
  306. result = self.run(["grim", str(path)])
  307. if result.returncode != 0:
  308. raise RuntimeError(f"grim failed: {result.stderr.strip()}")
  309. class Hyprland(Nested):
  310. name, short, program, desktop = "hyprland", "h", "Hyprland", "Hyprland"
  311. needs = ("Hyprland", "hyprctl", "grim")
  312. def _command(self):
  313. width, height = self.size
  314. lines = [f"monitor = HEADLESS-{i}, {width}x{height}@60, {width * (i - 1)}x0, 1" for i in range(1, self.outputs + 1)]
  315. (self.dir / "hyprland.conf").write_text("\n".join(lines + ["misc { disable_hyprland_logo = true }", "debug { disable_logs = false }"]) + "\n")
  316. return [self.program, "--config", str(self.dir / "hyprland.conf")], {}
  317. def _wait(self):
  318. super()._wait()
  319. signature = wait_for("Hyprland's IPC socket", lambda: self._socket("hypr/*/.socket.sock"), 30)
  320. self.extra["HYPRLAND_INSTANCE_SIGNATURE"] = os.path.basename(os.path.dirname(signature))
  321. for _ in range(self.outputs):
  322. self.run(["hyprctl", "output", "create", "headless"], self.extra)
  323. class Niri(Nested):
  324. name, short, program, desktop = "niri", "n", "niri", "niri"
  325. needs = ("niri", "grim")
  326. def _command(self):
  327. (self.dir / "niri.kdl").write_text("")
  328. return [self.program, "--config", str(self.dir / "niri.kdl")], {}
  329. def _wait(self):
  330. super()._wait()
  331. self.extra["NIRI_SOCKET"] = wait_for("niri's IPC socket", lambda: self._socket("niri.*.sock"), 30)
  332. class Cosmic(Nested):
  333. name, short, program, desktop = "cosmic", "c", "cosmic-comp", "COSMIC"
  334. needs = ("cosmic-comp", "grim")
  335. class Kde(Session):
  336. """KWin's virtual backend, plasmashell paints nothing on it yet"""
  337. name, short, desktop = "kde", "k", "KDE"
  338. needs = ("kwin_wayland", "kscreen-doctor")
  339. sysbus = True
  340. def _launch(self):
  341. width, height = self.size
  342. env = {
  343. "XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "KDE", "KDE_FULL_SESSION": "true", "KDE_SESSION_VERSION": "6",
  344. "QT_QPA_PLATFORM": "wayland", "KWIN_SCREENSHOT_NO_PERMISSION_CHECKS": "1",
  345. }
  346. self.session_env.update(env)
  347. self.spawn("kwin", ["kwin_wayland", "--virtual", "--width", str(width), "--height", str(height),
  348. "--socket", "lwe-kde", "--no-lockscreen", "--xwayland"], env)
  349. self.session_env["WAYLAND_DISPLAY"] = "lwe-kde"
  350. self.wait_socket("lwe-kde")
  351. wait_for("KWin on the session bus", lambda: self._bus_name("org.kde.KWin"), 40)
  352. def _shot(self, path):
  353. result = self.run(["python3", str(REPO / "tools/desktops/kwin_shot.py"), str(path)])
  354. if result.returncode != 0:
  355. raise RuntimeError(f"kwin_shot failed: {result.stderr.strip()}")
  356. class Gnome(Session):
  357. """GNOME Shell as a headless Wayland display server"""
  358. name, short, desktop = "gnome", "g", "GNOME"
  359. needs = ("gnome-shell",)
  360. sysbus = True
  361. def _launch(self):
  362. width, height = self.size
  363. env = {"XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "GNOME", "XDG_SESSION_DESKTOP": "gnome",
  364. "GNOME_SHELL_SESSION_MODE": "user"}
  365. self.session_env.update(env)
  366. self.spawn("shell", ["gnome-shell", "--headless", "--wayland", "--virtual-monitor", f"{width}x{height}",
  367. "--wayland-display", "lwe-gnome"], env)
  368. self.session_env["WAYLAND_DISPLAY"] = "lwe-gnome"
  369. self.wait_socket("lwe-gnome")
  370. # mutter picks the first free X display and says which, it can be the number of the desktop's own display
  371. log = self.dir / "shell.log"
  372. found = wait_for("Xwayland", lambda: re.search(r"public X11 display :(\d+)", log.read_text()) if log.exists() else None, 30)
  373. self.info["xwayland_display"] = found.group(1)
  374. def _shot(self, path):
  375. raise Unsupported("GNOME Shell only hands out screenshots to its own tools, capturing needs ScreenCast over PipeWire")
  376. class X11(Session):
  377. """a desktop environment or window manager on an X server of its own"""
  378. server = "xvfb"
  379. components = ()
  380. command = ()
  381. env_extra = {}
  382. desktop_window = ""
  383. ready_timeout = 90
  384. # the panels and the desktop need a moment after their windows exist before they have painted
  385. settle = 0
  386. @property
  387. def display(self):
  388. return int(self.info["display"])
  389. def _launch(self):
  390. self.info["display"] = str(self._free_display())
  391. self._start_server()
  392. env = {"DISPLAY": f":{self.display}", "XDG_SESSION_TYPE": "x11", "XDG_CURRENT_DESKTOP": self.desktop or "X-Generic", **self.env_extra}
  393. self.session_env.update(env)
  394. if self.command:
  395. self.spawn("session", list(self.command), env)
  396. else:
  397. for index, argv in enumerate(self.components):
  398. self.spawn(f"component{index}", list(argv), env)
  399. if index == 0:
  400. wait_for("the window manager", self._wm_name, 30)
  401. wait_for("the window manager", self._wm_name, self.ready_timeout)
  402. if self.desktop_window:
  403. wait_for("the desktop window", lambda: re.search(self.desktop_window, self._wmctrl("-lx")), self.ready_timeout)
  404. time.sleep(self.settle)
  405. def _free_display(self):
  406. taken = set()
  407. host = os.environ.get("DISPLAY", "")
  408. if host.startswith(":"):
  409. taken.add(int(host[1:].split(".")[0] or 0))
  410. unix = Path("/proc/net/unix").read_text()
  411. for number in range(100, 200):
  412. lock = f"/tmp/.X{number}-lock"
  413. rootfs_locks = [root / f"tmp/.X{number}-lock" for root in (Path(p) for p in self._rootfs_paths())]
  414. if (number in taken or Path(lock).exists() or f"/tmp/.X11-unix/X{number}" in unix
  415. or any(path.exists() for path in rootfs_locks)):
  416. continue
  417. return number
  418. raise RuntimeError("no free X display")
  419. def _rootfs_paths(self):
  420. from .runner import ROOTFS
  421. return [path for path in ROOTFS.values() if path.is_dir()]
  422. def _start_server(self):
  423. display = f":{self.display}"
  424. width, height = self.size
  425. # the real server, /usr/bin/Xorg is a wrapper that only lets console users start it
  426. xorg = next((p for p in ("/usr/libexec/Xorg", "/usr/lib/xorg/Xorg") if self.userland.exists(p)), None) \
  427. if self.server == "xorg" else None
  428. if xorg:
  429. (self.dir / "xorg.conf").write_text(
  430. 'Section "Device"\n Identifier "dummy"\n Driver "dummy"\n VideoRam 256000\nEndSection\n'
  431. 'Section "Monitor"\n Identifier "mon"\n HorizSync 5-1000\n VertRefresh 5-200\n'
  432. f' Modeline "{width}x{height}_60" 173.00 {width} {width + 128} {width + 328} {width + 656} {height} {height + 3} {height + 8} {height + 40} -hsync +vsync\n'
  433. 'EndSection\nSection "Screen"\n Identifier "screen0"\n Device "dummy"\n Monitor "mon"\n DefaultDepth 24\n'
  434. f' SubSection "Display"\n Depth 24\n Modes "{width}x{height}_60"\n Virtual {width} {height}\n EndSubSection\nEndSection\n'
  435. 'Section "ServerFlags"\n Option "DontVTSwitch" "true"\n Option "AutoAddDevices" "false"\n'
  436. ' Option "AutoEnableDevices" "false"\n Option "AutoAddGPU" "false"\nEndSection\n'
  437. )
  438. # a real refresh rate: muffin and mutter turn Xvfb's mode down
  439. self.spawn("xserver", [xorg, display, "-config", str(self.dir / "xorg.conf"), "-configdir", "/nonexistent", "-noreset",
  440. "-nolisten", "tcp", "-ac", "+extension", "GLX", "-logfile", str(self.dir / "Xorg.log")])
  441. else:
  442. self.spawn("xserver", ["Xvfb", display, "-screen", "0", f"{width}x{height}x24", "-ac", "+extension", "GLX", "+render", "-noreset"])
  443. wait_for("the X server", lambda: self._x(["xprop", "-root"]).returncode == 0, 30)
  444. def _x(self, argv):
  445. return self.run(argv, {"DISPLAY": f":{self.display}"})
  446. def _wmctrl(self, flag):
  447. return self._x(["wmctrl", flag]).stdout
  448. def _wm_name(self):
  449. out = self._wmctrl("-m")
  450. match = re.search(r"^Name: (.+)$", out, re.M)
  451. return match.group(1) if match else None
  452. def windows(self):
  453. """(window id, class, title) of the managed windows"""
  454. windows = []
  455. for line in self._wmctrl("-lx").splitlines():
  456. parts = line.split(None, 4)
  457. if len(parts) >= 3:
  458. windows.append((parts[0], parts[2], parts[4] if len(parts) > 4 else ""))
  459. return windows
  460. def _x_outputs(self):
  461. return re.findall(r"^(\S+) connected", self._x(["xrandr", "--query"]).stdout, re.M)
  462. def _shot(self, path):
  463. result = self._x(["import", "-window", "root", str(path)])
  464. if result.returncode != 0:
  465. raise RuntimeError(f"import failed: {result.stderr.strip()}")
  466. def x11(name, short, desktop="", server="xvfb", needs=(), sysbus=False, **attrs):
  467. return type(name.capitalize(), (X11,), {"name": name, "short": short, "desktop": desktop, "server": server,
  468. "needs": needs, "sysbus": sysbus, **attrs})
  469. Xfce = x11("xfce", "x1", "XFCE", "xorg", ("xfce4-session", "xfwm4", "xfdesktop", "wmctrl", "import"), True,
  470. command=("xfce4-session",), desktop_window="xfdesktop", settle=4)
  471. Cinnamon = x11("cinnamon", "x2", "X-Cinnamon", "xorg", ("cinnamon-session", "cinnamon", "nemo-desktop", "wmctrl", "import"), True,
  472. command=("cinnamon-session",), desktop_window="nemo-desktop",
  473. env_extra={"GDK_BACKEND": "x11", "LIBGL_ALWAYS_SOFTWARE": "1"}, settle=12)
  474. Mate = x11("mate", "x3", "MATE", "xorg", ("mate-session", "marco", "caja", "wmctrl", "import"), True,
  475. command=("mate-session",), desktop_window="Caja", settle=4)
  476. Lxqt = x11("lxqt", "x4", "LXQt", "xorg", ("openbox", "pcmanfm-qt", "lxqt-panel", "wmctrl", "import"), False,
  477. components=(("openbox",), ("pcmanfm-qt", "--desktop", "--profile=lxqt"), ("lxqt-panel",)),
  478. desktop_window="pcmanfm", env_extra={"QT_QPA_PLATFORM": "xcb"}, settle=3)
  479. WINDOW_MANAGERS = {
  480. "i3": ("i3", "-c", "/etc/i3/config"), "openbox": ("openbox",), "bspwm": ("bspwm",), "awesome": ("awesome",),
  481. "icewm": ("icewm",), "fluxbox": ("fluxbox",), "herbstluftwm": ("herbstluftwm",),
  482. }
  483. WM_CLASSES = [
  484. x11(name, f"w{index}", "", "xvfb", (argv[0], "wmctrl", "import"), False, components=(argv,))
  485. for index, (name, argv) in enumerate(WINDOW_MANAGERS.items())
  486. ]
  487. KINDS = {
  488. kind.name: kind
  489. for kind in (Sway, Labwc, Wayfire, River, Hyprland, Niri, Cosmic, Kde, Gnome, Xfce, Cinnamon, Mate, Lxqt, *WM_CLASSES)
  490. }