session.py 37 KB

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