session.py 34 KB

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