session.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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. userlands = ("native", "fedora", "arch")
  24. # downloaded by setup
  25. requires = ()
  26. sysbus = False
  27. desktop = ""
  28. def __init__(self, size=(1920, 1080), outputs=1):
  29. self.size = tuple(size)
  30. self.outputs = outputs
  31. self.dir = BASE / self.short
  32. self.run_dir = self.dir / "run"
  33. self.home = self.dir / "home"
  34. self.userland = None
  35. self.pids = []
  36. self.session_env = {}
  37. # more variables of the session (a compositor's IPC socket), and facts about it that are not variables
  38. self.extra = {}
  39. self.info = {}
  40. # ----- lookup
  41. @classmethod
  42. def of(cls, name, **options):
  43. try:
  44. return KINDS[name](**options)
  45. except KeyError:
  46. raise SystemExit(f"unknown session {name}, one of: {', '.join(KINDS)}")
  47. @classmethod
  48. def load(cls, name):
  49. session = cls.of(name)
  50. state = json.loads((session.dir / "state.json").read_text())
  51. session.userland = Userland(state["userland"])
  52. session.pids = state["pids"]
  53. session.session_env = state["session_env"]
  54. session.extra = state["extra"]
  55. session.info = state["info"]
  56. session.size = tuple(state["size"])
  57. session.outputs = state["outputs"]
  58. return session
  59. @classmethod
  60. def available(cls):
  61. """userland name or None per session name, whether it can be started here"""
  62. result = {}
  63. for name, kind in KINDS.items():
  64. try:
  65. result[name] = Userland.pick(*kind.needs, prefer=kind.userlands).name
  66. if not all(Path(path).exists() for path in kind.requires):
  67. result[name] = None
  68. except RuntimeError:
  69. result[name] = None
  70. return result
  71. def is_running(self):
  72. state = self.dir / "state.json"
  73. if not state.exists():
  74. return False
  75. pids = json.loads(state.read_text())["pids"]
  76. return bool(pids) and os.path.exists(f"/proc/{pids[0]}")
  77. # ----- lifecycle
  78. def start(self):
  79. if self.is_running():
  80. return self
  81. self.stop()
  82. shutil.rmtree(self.dir, ignore_errors=True)
  83. self.run_dir.mkdir(parents=True, mode=0o700)
  84. self.home.mkdir(parents=True)
  85. self.userland = Userland.pick(*self.needs, prefer=self.userlands)
  86. try:
  87. self._start_bus()
  88. if self.sysbus:
  89. self._start_system_bus()
  90. self._launch()
  91. except BaseException:
  92. self.stop()
  93. raise
  94. self._save()
  95. return self
  96. def stop(self):
  97. if self.dir.exists() and (self.dir / "state.json").exists():
  98. self.pids = json.loads((self.dir / "state.json").read_text())["pids"]
  99. terminate(list(reversed(self.pids)))
  100. if self.dir.exists():
  101. kill_with_runtime_dir(self.run_dir)
  102. self.pids = []
  103. state = self.dir / "state.json"
  104. if state.exists():
  105. state.unlink()
  106. def _save(self):
  107. (self.dir / "state.json").write_text(json.dumps({
  108. "userland": self.userland.name, "pids": self.pids, "session_env": self.session_env, "extra": self.extra, "info": self.info,
  109. "size": self.size, "outputs": self.outputs,
  110. }))
  111. (self.dir / "env").write_text(self.shell_exports())
  112. # ----- environments
  113. def env(self):
  114. """for the programs that run in the session's userland"""
  115. env = {
  116. "XDG_RUNTIME_DIR": str(self.run_dir),
  117. "DBUS_SESSION_BUS_ADDRESS": f"unix:path={self.run_dir}/bus",
  118. "HOME": str(self.home),
  119. "XDG_CONFIG_HOME": str(self.home / ".config"),
  120. "XDG_DATA_HOME": str(self.home / ".local/share"),
  121. "XDG_CACHE_HOME": str(self.home / ".cache"),
  122. "XDG_STATE_HOME": str(self.home / ".local/state"),
  123. }
  124. address = self.run_dir / "system-bus-address"
  125. if address.exists():
  126. env["DBUS_SYSTEM_BUS_ADDRESS"] = address.read_text().strip()
  127. env.update(self.session_env)
  128. env.update(self.extra)
  129. return env
  130. def client_env(self):
  131. """for programs under test, started on the caller's side: only what finds this session"""
  132. env = {
  133. key: value for key, value in self.env().items()
  134. if key in ("XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP",
  135. "WAYLAND_DISPLAY", "DISPLAY", "KDE_FULL_SESSION", "KDE_SESSION_VERSION")
  136. }
  137. env.update(self.extra)
  138. # never the desktop's audio server, a sandbox sees it
  139. env["PULSE_SERVER"] = "unix:/nonexistent"
  140. env["PIPEWIRE_REMOTE"] = "/nonexistent"
  141. return env
  142. def shell_exports(self):
  143. env = self.client_env()
  144. lines = [f"export {key}={value}" for key, value in env.items()]
  145. unset = [key for key in KDE_VARIABLES if key not in env]
  146. return "\n".join(lines + [f"unset {' '.join(unset)}"]) + "\n"
  147. # ----- running programs
  148. def spawn(self, name, argv, env=None, userland=None):
  149. """a long running program of the session, logged to <dir>/<name>.log"""
  150. userland = userland or self.userland
  151. process = userland.spawn(argv, {**self.env(), **(env or {})}, self.dir / f"{name}.log")
  152. self.pids.append(process.pid)
  153. return process
  154. def run(self, argv, env=None, timeout=60):
  155. """a short program in the session's userland, its CompletedProcess"""
  156. return self.userland.run(argv, {**self.env(), **(env or {})}, timeout=timeout)
  157. def client(self, argv, log=None, env=None):
  158. """a program under test on the caller's side, in the session's environment"""
  159. base = {"PATH": os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", "/tmp"), "LANG": "C.UTF-8"}
  160. out = open(log or self.dir / "client.log", "ab")
  161. return subprocess.Popen(
  162. argv, env={**base, **self.client_env(), **(env or {})}, stdout=out, stderr=subprocess.STDOUT,
  163. stdin=subprocess.DEVNULL, start_new_session=True,
  164. )
  165. def shot(self, path):
  166. """screenshot to path, taken in the session's userland"""
  167. scratch = self.dir / "shot.png"
  168. scratch.unlink(missing_ok=True)
  169. self._shot(scratch)
  170. shutil.copyfile(scratch, path)
  171. def _shot(self, path):
  172. raise Unsupported(f"no screenshot method for {self.name} yet")
  173. def output_names(self):
  174. """the outputs a program can be told to use with --screen-root"""
  175. if "WAYLAND_DISPLAY" in self.session_env:
  176. # the socket is reachable from the caller's side too, and not every userland has wayland-info (Arch's)
  177. userland = Userland("native") if Userland("native").has("wayland-info") else self.userland
  178. out = userland.run(["wayland-info"], self.env()).stdout
  179. names = []
  180. for block in re.split(r"(?=^interface: )", out, flags=re.M):
  181. if block.startswith("interface: 'wl_output'"):
  182. names += [name.strip() for name in re.findall(r"^\s+name: (.+)$", block, re.M)]
  183. return names
  184. return self._x_outputs()
  185. def _x_outputs(self):
  186. return []
  187. def windows(self):
  188. return []
  189. # ----- buses
  190. def _start_bus(self):
  191. self.spawn("dbus", ["dbus-daemon", "--session", "--nofork", "--nopidfile", f"--address=unix:path={self.run_dir}/bus"])
  192. wait_for("the session bus", (self.run_dir / "bus").exists, 15)
  193. def _start_system_bus(self):
  194. """stand-ins for the systemd services Cinnamon and GNOME need at startup"""
  195. self.spawn("sysbus", ["python3", str(REPO / "tools/desktops/fake_system.py"), str(self.run_dir / "system-bus-address")])
  196. wait_for("the fake system bus", lambda: (self.run_dir / "system-bus-address").exists(), 30)
  197. def _bus_name(self, name):
  198. reply = self.run(["dbus-send", "--session", "--print-reply", "--dest=org.freedesktop.DBus", "/org/freedesktop/DBus",
  199. "org.freedesktop.DBus.NameHasOwner", f"string:{name}"])
  200. return "boolean true" in reply.stdout
  201. def _launch(self):
  202. raise NotImplementedError
  203. # ----- shared helpers
  204. def _socket(self, pattern):
  205. for path in sorted(glob.glob(str(self.run_dir / pattern))):
  206. if not path.endswith(".lock"):
  207. return path
  208. return None
  209. def wait_socket(self, pattern, timeout=40):
  210. return wait_for(f"{pattern} in {self.run_dir}", lambda: self._socket(pattern), timeout)
  211. class Wlroots(Session):
  212. """sway, labwc, wayfire and river on wlroots' headless backend"""
  213. program = ""
  214. def _wlroots_env(self):
  215. env = {
  216. "WLR_BACKENDS": "headless", "WLR_LIBINPUT_NO_DEVICES": "1", "WLR_HEADLESS_OUTPUTS": str(self.outputs),
  217. # nothing here may reach the desktop's session or take its GPU
  218. "LIBSEAT_BACKEND": "seatd", "SEATD_SOCK": "/nonexistent",
  219. }
  220. for key in ("WLR_RENDER_DRM_DEVICE", "WLR_RENDERER"):
  221. if key in os.environ:
  222. env[key] = os.environ[key]
  223. return env
  224. def _config(self):
  225. return []
  226. def _launch(self):
  227. argv = [self.program, *self._config()]
  228. self.spawn(self.program, argv, self._wlroots_env())
  229. socket = self.wait_socket("wayland-[0-9]*")
  230. self.session_env.update({
  231. "WAYLAND_DISPLAY": os.path.basename(socket), "XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": self.desktop,
  232. })
  233. self._ready()
  234. def _ready(self):
  235. # wlroots' headless outputs start at 1280x720
  236. width, height = self.size
  237. for index in range(1, self.outputs + 1):
  238. self.run(["wlr-randr", "--output", f"HEADLESS-{index}", "--custom-mode", f"{width}x{height}"],
  239. {"WAYLAND_DISPLAY": self.session_env["WAYLAND_DISPLAY"]})
  240. def _shot(self, path):
  241. result = self.run(["grim", str(path)])
  242. if result.returncode != 0:
  243. raise RuntimeError(f"grim failed: {result.stderr.strip()}")
  244. class Sway(Wlroots):
  245. name, short, program, desktop = "sway", "s", "sway", "sway"
  246. needs = ("sway", "swaymsg", "grim")
  247. def _config(self):
  248. width, height = self.size
  249. (self.dir / "sway.conf").write_text(
  250. f"output * resolution {width}x{height}\nxwayland disable\ndefault_border none\nswaybg_command -\n"
  251. )
  252. return ["-c", str(self.dir / "sway.conf")]
  253. def _ready(self):
  254. self.extra["SWAYSOCK"] = wait_for("sway's IPC socket", lambda: self._socket("sway-ipc.*.sock"), 30)
  255. class Labwc(Wlroots):
  256. name, short, program, desktop = "labwc", "l", "labwc", "labwc"
  257. needs = ("labwc", "wlr-randr", "grim")
  258. def _config(self):
  259. config = self.dir / "config"
  260. config.mkdir()
  261. # the compositors that run as a window of this one fill its output
  262. (config / "rc.xml").write_text(
  263. '<?xml version="1.0"?>\n<labwc_config>\n <windowRules>\n'
  264. + "".join(
  265. f' <windowRule identifier="{app}"><action name="ToggleFullscreen"/></windowRule>\n'
  266. for app in ("Hyprland", "niri", "cosmic-comp")
  267. )
  268. + " </windowRules>\n</labwc_config>\n"
  269. )
  270. return ["-C", str(config)]
  271. class Wayfire(Wlroots):
  272. name, short, program, desktop = "wayfire", "w", "wayfire", "wayfire"
  273. needs = ("wayfire", "wlr-randr", "grim")
  274. class River(Wlroots):
  275. name, short, program, desktop = "river", "r", "river", "river"
  276. needs = ("river", "wlr-randr", "grim")
  277. def _config(self):
  278. init = self.dir / "init"
  279. init.write_text("#!/bin/sh\n")
  280. init.chmod(0o755)
  281. return ["-c", str(init)]
  282. class Nested(Session):
  283. """Hyprland, niri and COSMIC have no headless backend (they would take the GPU through DRM), they run as a window
  284. of a headless labwc"""
  285. program = ""
  286. def _launch(self):
  287. if Labwc().is_running():
  288. parent = Session.load("labwc")
  289. else:
  290. parent = Labwc(self.size, 1).start()
  291. parent.info["implicit"] = True
  292. parent._save()
  293. socket = f"{parent.run_dir}/{parent.session_env['WAYLAND_DISPLAY']}"
  294. argv, env = self._command()
  295. self.spawn(self.program, argv, {"WAYLAND_DISPLAY": socket, "LIBSEAT_BACKEND": "seatd", "SEATD_SOCK": "/nonexistent", **env})
  296. self.session_env.update({"XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": self.desktop})
  297. self._wait()
  298. def _command(self):
  299. return [self.program], {}
  300. def _wait(self):
  301. self.session_env["WAYLAND_DISPLAY"] = os.path.basename(self.wait_socket("wayland-[0-9]*"))
  302. def stop(self):
  303. super().stop()
  304. # the labwc they run in goes with the last of them, unless it was started on its own
  305. labwc = Labwc()
  306. if labwc.is_running() and Session.load("labwc").info.get("implicit") and not any(
  307. kind().is_running() for kind in (Hyprland, Niri, Cosmic)
  308. ):
  309. labwc.stop()
  310. def _shot(self, path):
  311. result = self.run(["grim", str(path)])
  312. if result.returncode != 0:
  313. raise RuntimeError(f"grim failed: {result.stderr.strip()}")
  314. class Hyprland(Nested):
  315. name, short, program, desktop = "hyprland", "h", "Hyprland", "Hyprland"
  316. needs = ("Hyprland", "hyprctl", "grim")
  317. def _command(self):
  318. width, height = self.size
  319. lines = [f"monitor = HEADLESS-{i}, {width}x{height}@60, {width * (i - 1)}x0, 1" for i in range(1, self.outputs + 1)]
  320. (self.dir / "hyprland.conf").write_text("\n".join(lines + ["misc { disable_hyprland_logo = true }", "debug { disable_logs = false }"]) + "\n")
  321. return [self.program, "--config", str(self.dir / "hyprland.conf")], {}
  322. def _wait(self):
  323. super()._wait()
  324. signature = wait_for("Hyprland's IPC socket", lambda: self._socket("hypr/*/.socket.sock"), 30)
  325. self.extra["HYPRLAND_INSTANCE_SIGNATURE"] = os.path.basename(os.path.dirname(signature))
  326. for _ in range(self.outputs):
  327. self.run(["hyprctl", "output", "create", "headless"], self.extra)
  328. class Niri(Nested):
  329. name, short, program, desktop = "niri", "n", "niri", "niri"
  330. needs = ("niri", "grim")
  331. def _command(self):
  332. (self.dir / "niri.kdl").write_text("")
  333. return [self.program, "--config", str(self.dir / "niri.kdl")], {}
  334. def _wait(self):
  335. super()._wait()
  336. self.extra["NIRI_SOCKET"] = wait_for("niri's IPC socket", lambda: self._socket("niri.*.sock"), 30)
  337. class Cosmic(Nested):
  338. name, short, program, desktop = "cosmic", "c", "cosmic-comp", "COSMIC"
  339. needs = ("cosmic-comp", "grim")
  340. class Kde(Session):
  341. """KWin's virtual backend, plasmashell paints nothing on it yet"""
  342. name, short, desktop = "kde", "k", "KDE"
  343. needs = ("kwin_wayland", "kscreen-doctor")
  344. sysbus = True
  345. def _launch(self):
  346. width, height = self.size
  347. env = {
  348. "XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "KDE", "KDE_FULL_SESSION": "true", "KDE_SESSION_VERSION": "6",
  349. "QT_QPA_PLATFORM": "wayland", "KWIN_SCREENSHOT_NO_PERMISSION_CHECKS": "1",
  350. # for kwin_fake_input.c
  351. "KWIN_WAYLAND_NO_PERMISSION_CHECKS": "1",
  352. }
  353. self.session_env.update(env)
  354. self.spawn("kwin", ["kwin_wayland", "--virtual", "--width", str(width), "--height", str(height),
  355. "--output-count", str(self.outputs), "--socket", "lwe-kde", "--no-lockscreen",
  356. "--xwayland"], env)
  357. self.session_env["WAYLAND_DISPLAY"] = "lwe-kde"
  358. self.wait_socket("lwe-kde")
  359. wait_for("KWin on the session bus", lambda: self._bus_name("org.kde.KWin"), 40)
  360. def pointer(self, *commands):
  361. """KWin's pointer through fake input: "move", x, y (logical, global), "down"/"up", evdev button"""
  362. tool = self.dir / "kwin_fake_input"
  363. if not tool.exists():
  364. build = self.dir / "fake-input"
  365. build.mkdir(exist_ok=True)
  366. xml = "/usr/share/plasma-wayland-protocols/fake-input.xml"
  367. for mode, out in (("client-header", "fake-input-client-protocol.h"), ("private-code", "fake-input.c")):
  368. subprocess.run(["wayland-scanner", mode, xml, str(build / out)], check=True)
  369. subprocess.run(["cc", "-o", str(tool), str(REPO / "tools/desktops/kwin_fake_input.c"), str(build / "fake-input.c"),
  370. f"-I{build}", "-lwayland-client", "-lm"], check=True)
  371. result = self.run([str(tool), *map(str, commands)])
  372. if result.returncode != 0:
  373. raise RuntimeError(f"kwin_fake_input: {result.stderr.strip()}")
  374. def _shot(self, path):
  375. result = self.run(["python3", str(REPO / "tools/desktops/kwin_shot.py"), str(path)])
  376. if result.returncode != 0:
  377. raise RuntimeError(f"kwin_shot failed: {result.stderr.strip()}")
  378. class KdeDual(Kde):
  379. """KWin's virtual backend with two outputs, for what happens per output"""
  380. name, short = "kde-dual", "k2"
  381. def __init__(self, size=(1280, 720), outputs=2):
  382. super().__init__(size, outputs)
  383. class Gnome(Session):
  384. """GNOME Shell as a headless Wayland display server"""
  385. name, short, desktop = "gnome", "g", "GNOME"
  386. needs = ("gnome-shell",)
  387. sysbus = True
  388. # lab extension enables unsafe mode for Screenshot/Eval; the build's copy has the helper in it
  389. EXTENSIONS = (REPO / "tools/desktops/gnome-lab-extension/lwe-lab@desktops.test",
  390. Path(os.environ.get("LWE_BUILD_OUTPUT", REPO / "build/output"))
  391. / "gnome-shell-extension/linux-wallpaperengine@wallpaperenginelover.github.io")
  392. # (uuid, folder to link, or None if installed in the userland)
  393. extra_extensions = ()
  394. # put on ~/Desktop, a trailing / makes a folder
  395. desktop_files = ()
  396. def _install_extensions(self):
  397. target = self.home / ".local/share/gnome-shell/extensions"
  398. target.mkdir(parents=True, exist_ok=True)
  399. for source in self.EXTENSIONS:
  400. (target / source.name).symlink_to(source)
  401. for uuid, folder in self.extra_extensions:
  402. if folder is not None:
  403. (target / uuid).symlink_to(folder)
  404. for name in self.desktop_files:
  405. path = self.home / "Desktop" / name
  406. path.parent.mkdir(parents=True, exist_ok=True)
  407. if name.endswith("/"):
  408. path.mkdir(exist_ok=True)
  409. else:
  410. path.write_text("lab\n")
  411. uuids = ", ".join([f"'{source.name}'" for source in self.EXTENSIONS] + [f"'{uuid}'" for uuid, _ in self.extra_extensions])
  412. for key, value in (("enabled-extensions", f"[{uuids}]"), ("disable-user-extensions", "false")):
  413. result = self.run(["gsettings", "set", "org.gnome.shell", key, value])
  414. if result.returncode != 0:
  415. raise RuntimeError(f"gsettings {key}: {result.stderr.strip()}")
  416. def _launch(self):
  417. width, height = self.size
  418. env = {"XDG_SESSION_TYPE": "wayland", "XDG_CURRENT_DESKTOP": "GNOME", "XDG_SESSION_DESKTOP": "gnome",
  419. "GNOME_SHELL_SESSION_MODE": "user"}
  420. self.session_env.update(env)
  421. self._install_extensions()
  422. monitors = [arg for _ in range(self.outputs) for arg in ("--virtual-monitor", f"{width}x{height}")]
  423. # no Xwayland, mutter could pick the real desktop's display number
  424. self.spawn("shell", ["gnome-shell", "--headless", "--wayland", "--no-x11", *monitors, "--wayland-display",
  425. "lwe-gnome"], env)
  426. self.session_env["WAYLAND_DISPLAY"] = "lwe-gnome"
  427. self.wait_socket("lwe-gnome")
  428. wait_for("the lab extension", self._unsafe_mode, 40)
  429. wait_for("the overview to close", lambda: self.eval("Main.overview.hide(); Main.overview.visible") == "false", 20)
  430. def _unsafe_mode(self):
  431. reply = self.eval("global.context.unsafe_mode")
  432. return reply == "true"
  433. def eval(self, script):
  434. """runs JS inside the Shell (unsafe mode only), its JSON result or None"""
  435. result = self.run(["gdbus", "call", "--session", "--dest", "org.gnome.Shell", "--object-path", "/org/gnome/Shell",
  436. "--method", "org.gnome.Shell.Eval", script], timeout=20)
  437. found = re.match(r"\((true|false), '(.*)'\)$", result.stdout.strip(), re.S)
  438. if not found or found.group(1) != "true":
  439. return None
  440. return found.group(2)
  441. def _shot(self, path):
  442. result = self.run(["gdbus", "call", "--session", "--dest", "org.gnome.Shell", "--object-path",
  443. "/org/gnome/Shell/Screenshot", "--method", "org.gnome.Shell.Screenshot.Screenshot",
  444. "false", "false", str(path)], timeout=30)
  445. if "(true," not in result.stdout:
  446. raise RuntimeError(f"Shell screenshot failed: {result.stdout.strip()} {result.stderr.strip()}")
  447. class Gnome46(Gnome):
  448. """GNOME Shell 46 from the Ubuntu 24.04 rootfs (setup gnome46): no Meta.Window.set_type, the helper path"""
  449. name, short, desktop = "gnome46", "g4", "GNOME"
  450. userlands = ("gnome46",)
  451. class Gnome45(Gnome):
  452. """GNOME Shell 45 (Ubuntu 23.10): no desktop windows for Wayland clients, the wallpaper is a bottom layer window"""
  453. name, short, desktop = "gnome45", "g5", "GNOME"
  454. userlands = ("gnome45",)
  455. class Gnome47(Gnome):
  456. """GNOME Shell 47 (Ubuntu 24.10), the helper path"""
  457. name, short, desktop = "gnome47", "g7", "GNOME"
  458. userlands = ("gnome47",)
  459. class Gnome48(Gnome):
  460. """GNOME Shell 48 (Ubuntu 25.04), the helper path"""
  461. name, short, desktop = "gnome48", "g8", "GNOME"
  462. userlands = ("gnome48",)
  463. class Gnome49(Gnome):
  464. """GNOME Shell 49 (Fedora 43), the first with Meta.Window.set_type"""
  465. name, short, desktop = "gnome49", "g9", "GNOME"
  466. userlands = ("gnome49",)
  467. # DING for GNOME 50 comes from `setup ding`
  468. DING_DIR = Path.home() / ".local/share/lwe-lab/ding50/ding@rastersoft.com"
  469. class GnomeDing(Gnome):
  470. """GNOME 50 with Desktop Icons NG, whose desktop window shares the desktop layer with the wallpaper's"""
  471. name, short = "gnome-ding", "gd"
  472. extra_extensions = (("ding@rastersoft.com", DING_DIR),)
  473. desktop_files = ("notes.txt", "todo.txt", "Pictures/")
  474. requires = (DING_DIR,)
  475. class Gnome46Ding(Gnome46):
  476. """GNOME 46 with Ubuntu's Desktop Icons NG package"""
  477. name, short = "gnome46-ding", "g4d"
  478. extra_extensions = (("ding@rastersoft.com", None),)
  479. desktop_files = GnomeDing.desktop_files
  480. class Gnome45Ding(Gnome45):
  481. """GNOME 45 with Ubuntu's Desktop Icons NG, both windows in the bottom layer"""
  482. name, short = "gnome45-ding", "g5d"
  483. extra_extensions = (("ding@rastersoft.com", None),)
  484. desktop_files = GnomeDing.desktop_files
  485. class X11(Session):
  486. """a desktop environment or window manager on an X server of its own"""
  487. server = "xvfb"
  488. components = ()
  489. command = ()
  490. env_extra = {}
  491. desktop_window = ""
  492. ready_timeout = 90
  493. # the panels and the desktop need a moment after their windows exist before they have painted
  494. settle = 0
  495. @property
  496. def display(self):
  497. return int(self.info["display"])
  498. def _launch(self):
  499. self.info["display"] = str(self._free_display())
  500. self._start_server()
  501. env = {"DISPLAY": f":{self.display}", "XDG_SESSION_TYPE": "x11", "XDG_CURRENT_DESKTOP": self.desktop or "X-Generic", **self.env_extra}
  502. self.session_env.update(env)
  503. if self.command:
  504. self.spawn("session", list(self.command), env)
  505. else:
  506. for index, argv in enumerate(self.components):
  507. self.spawn(f"component{index}", list(argv), env)
  508. if index == 0:
  509. wait_for("the window manager", self._wm_name, 30)
  510. wait_for("the window manager", self._wm_name, self.ready_timeout)
  511. if self.desktop_window:
  512. wait_for("the desktop window", lambda: re.search(self.desktop_window, self._wmctrl("-lx")), self.ready_timeout)
  513. time.sleep(self.settle)
  514. def _free_display(self):
  515. taken = set()
  516. host = os.environ.get("DISPLAY", "")
  517. if host.startswith(":"):
  518. taken.add(int(host[1:].split(".")[0] or 0))
  519. unix = Path("/proc/net/unix").read_text()
  520. for number in range(100, 200):
  521. lock = f"/tmp/.X{number}-lock"
  522. rootfs_locks = [root / f"tmp/.X{number}-lock" for root in (Path(p) for p in self._rootfs_paths())]
  523. if (number in taken or Path(lock).exists() or f"/tmp/.X11-unix/X{number}" in unix
  524. or any(path.exists() for path in rootfs_locks)):
  525. continue
  526. return number
  527. raise RuntimeError("no free X display")
  528. def _rootfs_paths(self):
  529. from .runner import ROOTFS
  530. return [path for path in ROOTFS.values() if path.is_dir()]
  531. def _start_server(self):
  532. display = f":{self.display}"
  533. width, height = self.size
  534. # the real server, /usr/bin/Xorg is a wrapper that only lets console users start it
  535. xorg = next((p for p in ("/usr/libexec/Xorg", "/usr/lib/xorg/Xorg") if self.userland.exists(p)), None) \
  536. if self.server == "xorg" else None
  537. if xorg:
  538. (self.dir / "xorg.conf").write_text(
  539. 'Section "Device"\n Identifier "dummy"\n Driver "dummy"\n VideoRam 256000\nEndSection\n'
  540. 'Section "Monitor"\n Identifier "mon"\n HorizSync 5-1000\n VertRefresh 5-200\n'
  541. 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'
  542. 'EndSection\nSection "Screen"\n Identifier "screen0"\n Device "dummy"\n Monitor "mon"\n DefaultDepth 24\n'
  543. f' SubSection "Display"\n Depth 24\n Modes "{width}x{height}_60"\n Virtual {width} {height}\n EndSubSection\nEndSection\n'
  544. 'Section "ServerFlags"\n Option "DontVTSwitch" "true"\n Option "AutoAddDevices" "false"\n'
  545. ' Option "AutoEnableDevices" "false"\n Option "AutoAddGPU" "false"\nEndSection\n'
  546. )
  547. # a real refresh rate: muffin and mutter turn Xvfb's mode down
  548. self.spawn("xserver", [xorg, display, "-config", str(self.dir / "xorg.conf"), "-configdir", "/nonexistent", "-noreset",
  549. "-nolisten", "tcp", "-ac", "+extension", "GLX", "-logfile", str(self.dir / "Xorg.log")])
  550. else:
  551. self.spawn("xserver", ["Xvfb", display, "-screen", "0", f"{width}x{height}x24", "-ac", "+extension", "GLX", "+render", "-noreset"])
  552. wait_for("the X server", lambda: self._x(["xprop", "-root"]).returncode == 0, 30)
  553. def _x(self, argv):
  554. return self.run(argv, {"DISPLAY": f":{self.display}"})
  555. def _wmctrl(self, flag):
  556. return self._x(["wmctrl", flag]).stdout
  557. def _wm_name(self):
  558. out = self._wmctrl("-m")
  559. match = re.search(r"^Name: (.+)$", out, re.M)
  560. return match.group(1) if match else None
  561. def windows(self):
  562. """(window id, class, title) of the managed windows"""
  563. windows = []
  564. for line in self._wmctrl("-lx").splitlines():
  565. parts = line.split(None, 4)
  566. if len(parts) >= 3:
  567. windows.append((parts[0], parts[2], parts[4] if len(parts) > 4 else ""))
  568. return windows
  569. def _x_outputs(self):
  570. return re.findall(r"^(\S+) connected", self._x(["xrandr", "--query"]).stdout, re.M)
  571. def _shot(self, path):
  572. result = self._x(["import", "-window", "root", str(path)])
  573. if result.returncode != 0:
  574. raise RuntimeError(f"import failed: {result.stderr.strip()}")
  575. def x11(name, short, desktop="", server="xvfb", needs=(), sysbus=False, **attrs):
  576. return type(name.capitalize(), (X11,), {"name": name, "short": short, "desktop": desktop, "server": server,
  577. "needs": needs, "sysbus": sysbus, **attrs})
  578. Xfce = x11("xfce", "x1", "XFCE", "xorg", ("xfce4-session", "xfwm4", "xfdesktop", "wmctrl", "import"), True,
  579. command=("xfce4-session",), desktop_window="xfdesktop", settle=4)
  580. Cinnamon = x11("cinnamon", "x2", "X-Cinnamon", "xorg", ("cinnamon-session", "cinnamon", "nemo-desktop", "wmctrl", "import"), True,
  581. command=("cinnamon-session",), desktop_window="nemo-desktop",
  582. env_extra={"GDK_BACKEND": "x11", "LIBGL_ALWAYS_SOFTWARE": "1"}, settle=12)
  583. Mate = x11("mate", "x3", "MATE", "xorg", ("mate-session", "marco", "caja", "wmctrl", "import"), True,
  584. command=("mate-session",), desktop_window="Caja", settle=4)
  585. Lxqt = x11("lxqt", "x4", "LXQt", "xorg", ("openbox", "pcmanfm-qt", "lxqt-panel", "wmctrl", "import"), False,
  586. components=(("openbox",), ("pcmanfm-qt", "--desktop", "--profile=lxqt"), ("lxqt-panel",)),
  587. desktop_window="pcmanfm", env_extra={"QT_QPA_PLATFORM": "xcb"}, settle=3)
  588. WINDOW_MANAGERS = {
  589. "i3": ("i3", "-c", "/etc/i3/config"), "openbox": ("openbox",), "bspwm": ("bspwm",), "awesome": ("awesome",),
  590. "icewm": ("icewm",), "fluxbox": ("fluxbox",), "herbstluftwm": ("herbstluftwm",),
  591. }
  592. WM_CLASSES = [
  593. x11(name, f"w{index}", "", "xvfb", (argv[0], "wmctrl", "import"), False, components=(argv,))
  594. for index, (name, argv) in enumerate(WINDOW_MANAGERS.items())
  595. ]
  596. KINDS = {
  597. kind.name: kind
  598. 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)
  599. }