session.py 37 KB

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