Files
anode/tests/test_replace.py
T

1443 lines
66 KiB
Python
Executable File

#!/usr/bin/env python3
"""Headless Xvfb tests for ANODE live X11 replacement and fastfetch DE/WM identity."""
import ctypes
import ctypes.util
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import time
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
BUILD = os.path.join(ROOT, "build")
DWM_BIN = os.path.join(BUILD, "dwm", "dwm")
REPLACE_BIN = os.path.join(ROOT, "scripts", "anode-replace")
libx11_name = ctypes.util.find_library("X11") or "libX11.so.6"
X11 = ctypes.CDLL(libx11_name)
Window = ctypes.c_ulong
Atom = ctypes.c_ulong
Display_p = ctypes.c_void_p
class XWindowAttributes(ctypes.Structure):
_fields_ = [
("x", ctypes.c_int), ("y", ctypes.c_int),
("width", ctypes.c_int), ("height", ctypes.c_int),
("border_width", ctypes.c_int), ("depth", ctypes.c_int),
("visual", ctypes.c_void_p), ("root", Window),
("class", ctypes.c_int), ("bit_gravity", ctypes.c_int),
("win_gravity", ctypes.c_int), ("backing_store", ctypes.c_int),
("backing_planes", ctypes.c_ulong), ("backing_pixel", ctypes.c_ulong),
("save_under", ctypes.c_int), ("colormap", ctypes.c_ulong),
("map_installed", ctypes.c_int), ("map_state", ctypes.c_int),
("all_event_masks", ctypes.c_long), ("your_event_mask", ctypes.c_long),
("do_not_propagate_mask", ctypes.c_long), ("override_redirect", ctypes.c_int),
("screen", ctypes.c_void_p),
]
X11.XOpenDisplay.argtypes = [ctypes.c_char_p]
X11.XOpenDisplay.restype = Display_p
X11.XCloseDisplay.argtypes = [Display_p]
X11.XDefaultRootWindow.argtypes = [Display_p]
X11.XDefaultRootWindow.restype = Window
X11.XDefaultScreen.argtypes = [Display_p]
X11.XDefaultScreen.restype = ctypes.c_int
X11.XInternAtom.argtypes = [Display_p, ctypes.c_char_p, ctypes.c_int]
X11.XInternAtom.restype = Atom
X11.XGetSelectionOwner.argtypes = [Display_p, Atom]
X11.XGetSelectionOwner.restype = Window
X11.XGetWindowProperty.argtypes = [
Display_p, Window, Atom, ctypes.c_long, ctypes.c_long, ctypes.c_int, Atom,
ctypes.POINTER(Atom), ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)),
]
X11.XGetWindowProperty.restype = ctypes.c_int
X11.XFree.argtypes = [ctypes.c_void_p]
X11.XFetchName.argtypes = [Display_p, Window, ctypes.POINTER(ctypes.c_char_p)]
X11.XFetchName.restype = ctypes.c_int
X11.XCreateSimpleWindow.argtypes = [
Display_p, Window, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint,
ctypes.c_uint, ctypes.c_ulong, ctypes.c_ulong,
]
X11.XCreateSimpleWindow.restype = Window
X11.XMapWindow.argtypes = [Display_p, Window]
X11.XUnmapWindow.argtypes = [Display_p, Window]
X11.XMoveResizeWindow.argtypes = [Display_p, Window, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint]
X11.XChangeProperty.argtypes = [
Display_p, Window, Atom, Atom, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
]
X11.XSendEvent.argtypes = [Display_p, Window, ctypes.c_int, ctypes.c_long, ctypes.c_void_p]
X11.XDestroyWindow.argtypes = [Display_p, Window]
X11.XGetWindowAttributes.argtypes = [Display_p, Window, ctypes.POINTER(XWindowAttributes)]
X11.XGetWindowAttributes.restype = ctypes.c_int
X11.XSync.argtypes = [Display_p, ctypes.c_int]
def get_win_prop_ulong_list(dpy, win, atom_name, max_items=64):
atom = X11.XInternAtom(dpy, atom_name.encode(), 0)
da = Atom()
di = ctypes.c_int()
n = ctypes.c_ulong()
dl = ctypes.c_ulong()
prop = ctypes.POINTER(ctypes.c_ubyte)()
rc = X11.XGetWindowProperty(
dpy, win, atom, 0, max_items, 0, 0,
ctypes.byref(da), ctypes.byref(di), ctypes.byref(n), ctypes.byref(dl), ctypes.byref(prop),
)
vals = []
if rc == 0 and prop and di.value == 32 and n.value >= 1:
arr = ctypes.cast(prop, ctypes.POINTER(ctypes.c_ulong))
vals = [int(arr[i]) for i in range(n.value)]
if prop:
X11.XFree(prop)
return vals
def send_ewmh_msg(dpy, root, win, atom_name, data_l):
class CMData(ctypes.Union):
_fields_ = [("b", ctypes.c_char * 20), ("s", ctypes.c_short * 10), ("l", ctypes.c_long * 5)]
class CMEvent(ctypes.Structure):
_fields_ = [
("type", ctypes.c_int), ("serial", ctypes.c_ulong), ("send_event", ctypes.c_int),
("display", Display_p), ("window", Window), ("message_type", Atom),
("format", ctypes.c_int), ("data", CMData),
]
ev = CMEvent()
ev.type = 33 # ClientMessage
ev.display = dpy
ev.window = win
ev.message_type = X11.XInternAtom(dpy, atom_name.encode(), 0)
ev.format = 32
for i, val in enumerate(data_l[:5]):
ev.data.l[i] = val
X11.XSendEvent(dpy, root, 0, (1 << 19) | (1 << 20), ctypes.byref(ev))
X11.XSync(dpy, 0)
def pick_display():
for d in range(70, 120):
if not os.path.exists(f"/tmp/.X{d}-lock") and not os.path.exists(f"/tmp/.X11-unix/X{d}"):
return f":{d}"
return ":95"
def wait_until(pred, timeout=6.0, interval=0.05):
end = time.monotonic() + timeout
while time.monotonic() < end:
res = pred()
if res:
return res
time.sleep(interval)
return None
def terminate(proc):
if proc and proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=2)
def get_win_prop_ulong(dpy, win, atom_name):
atom = X11.XInternAtom(dpy, atom_name.encode(), 0)
da = Atom()
di = ctypes.c_int()
n = ctypes.c_ulong()
dl = ctypes.c_ulong()
prop = ctypes.POINTER(ctypes.c_ubyte)()
rc = X11.XGetWindowProperty(
dpy, win, atom, 0, 1, 0, 0,
ctypes.byref(da), ctypes.byref(di), ctypes.byref(n), ctypes.byref(dl), ctypes.byref(prop),
)
val = None
if rc == 0 and prop and di.value == 32 and n.value >= 1:
val = int(ctypes.cast(prop, ctypes.POINTER(ctypes.c_ulong))[0])
if prop:
X11.XFree(prop)
return val
def get_win_prop_str(dpy, win, atom_name):
atom = X11.XInternAtom(dpy, atom_name.encode(), 0)
da = Atom()
di = ctypes.c_int()
n = ctypes.c_ulong()
dl = ctypes.c_ulong()
prop = ctypes.POINTER(ctypes.c_ubyte)()
rc = X11.XGetWindowProperty(
dpy, win, atom, 0, 256, 0, 0,
ctypes.byref(da), ctypes.byref(di), ctypes.byref(n), ctypes.byref(dl), ctypes.byref(prop),
)
out = None
if rc == 0 and prop and di.value == 8 and n.value > 0:
out = bytes(prop[i] for i in range(n.value)).decode("utf-8", errors="ignore").rstrip("\x00")
if prop:
X11.XFree(prop)
return out
def make_env(tmp, disp):
home = os.path.join(tmp, "home")
xdg_home = os.path.join(home, ".config")
# Provide an isolated bin dir with anode binaries but without long-lived daemons interfering
bin_dir = os.path.join(tmp, "bin")
os.makedirs(xdg_home, exist_ok=True)
os.makedirs(bin_dir, exist_ok=True)
os.symlink(DWM_BIN, os.path.join(bin_dir, "dwm"))
os.symlink(os.path.join(ROOT, "scripts", "anode-session"), os.path.join(bin_dir, "anode-session"))
os.symlink(os.path.join(ROOT, "scripts", "anode-replace"), os.path.join(bin_dir, "anode-replace"))
os.symlink(os.path.join(ROOT, "scripts", "anode-apply-scale"), os.path.join(bin_dir, "anode-apply-scale"))
os.symlink(os.path.join(ROOT, "scripts", "anode-apply-theme"), os.path.join(bin_dir, "anode-apply-theme"))
env = dict(os.environ)
env["DISPLAY"] = disp
env["HOME"] = home
env["XDG_CONFIG_HOME"] = xdg_home
env["ANODE_PREFIX"] = ROOT
env["ANODE_NO_SIGNAL"] = "1"
env["ANODE_NO_DBUS"] = "1"
env["PATH"] = bin_dir + ":" + env.get("PATH", "/usr/bin:/bin")
for k in (
"WAYLAND_DISPLAY", "SWAYSOCK", "HYPRLAND_INSTANCE_SIGNATURE", "I3SOCK",
"KDE_FULL_SESSION", "GNOME_DESKTOP_SESSION_ID",
):
env.pop(k, None)
return env
def kill_pid_and_wait(pid):
if not pid or pid <= 1:
return
try:
os.kill(pid, signal.SIGTERM)
except ProcessLookupError:
return
for _ in range(30):
try:
os.kill(pid, 0)
time.sleep(0.05)
except ProcessLookupError:
return
try:
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
pass
def test_fastfetch_identity():
disp = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
env["XDG_CURRENT_DESKTOP"] = "ANODE"
env["XDG_SESSION_DESKTOP"] = "anode"
env["DESKTOP_SESSION"] = "anode"
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dwm = None
dpy = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy, f"Xvfb failed on {disp}"
root = X11.XDefaultRootWindow(dpy)
scr = X11.XDefaultScreen(dpy)
wm_sel = X11.XInternAtom(dpy, f"WM_S{scr}".encode(), 0)
dwm = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wmcheck = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wmcheck, "dwm did not publish _NET_SUPPORTING_WM_CHECK"
assert get_win_prop_str(dpy, wmcheck, "_NET_WM_NAME") == "ANODE WM"
assert get_win_prop_ulong(dpy, wmcheck, "_NET_WM_PID") == dwm.pid
assert X11.XGetSelectionOwner(dpy, wm_sel) == wmcheck
nm = ctypes.c_char_p()
assert X11.XFetchName(dpy, wmcheck, ctypes.byref(nm)) and nm.value == b"ANODE WM"
X11.XFree(nm)
if shutil.which("fastfetch"):
r = subprocess.run(
["fastfetch", "--format", "json", "--structure", "DE:WM"],
env=env, capture_output=True, text=True, check=True,
)
data = json.loads(r.stdout)
mods = {item["type"]: item.get("result", {}) for item in data}
assert mods.get("DE", {}).get("prettyName") == "ANODE", f"unexpected DE: {data}"
assert mods.get("WM", {}).get("prettyName") == "ANODE WM", f"unexpected WM: {data}"
finally:
terminate(dwm)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_icccm_replace_and_client_preservation():
disp = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
env["XDG_CURRENT_DESKTOP"] = "XFCE"
env["KDE_FULL_SESSION"] = "true"
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dwm1 = None
dpy = None
new_pid = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dwm1 = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
client = X11.XCreateSimpleWindow(dpy, root, 40, 40, 300, 200, 0, 0, 0xffffff)
X11.XMapWindow(dpy, client)
X11.XSync(dpy, 0)
dry = subprocess.run([REPLACE_BIN, "--dry-run"], env=env, capture_output=True, text=True)
assert dry.returncode == 0, dry.stderr
assert "ANODE WM" in dry.stdout
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"anode-replace failed: stdout={rep.stdout} stderr={rep.stderr}"
assert "DE: ANODE, WM: ANODE WM" in rep.stdout
# Original dwm must exit cleanly via SelectionClear (status 75)
assert wait_until(lambda: dwm1.poll() is not None, timeout=5.0), "old dwm did not exit on SelectionClear"
assert dwm1.returncode == 75, f"old dwm exited with {dwm1.returncode}, expected 75"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1, f"expected new _NET_SUPPORTING_WM_CHECK window (wm1={wm1}, wm2={wm2})"
assert get_win_prop_str(dpy, wm2, "_NET_WM_NAME") == "ANODE WM"
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
assert new_pid and new_pid != dwm1.pid
# Mapped client window must survive replacement
attr = XWindowAttributes()
assert X11.XGetWindowAttributes(dpy, client, ctypes.byref(attr)) != 0
X11.XDestroyWindow(dpy, client)
finally:
terminate(dwm1)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_non_icccm_wm_fallback_replace():
disp = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
mock_wm = None
dpy = None
new_pid = None
mock_code = (
"import ctypes, ctypes.util, os, signal, time\n"
"X11 = ctypes.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6')\n"
"X11.XOpenDisplay.restype = ctypes.c_void_p\n"
"X11.XDefaultRootWindow.argtypes = [ctypes.c_void_p]\n"
"X11.XDefaultRootWindow.restype = ctypes.c_ulong\n"
"X11.XSelectInput.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_long]\n"
"X11.XCreateSimpleWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_ulong, ctypes.c_ulong]\n"
"X11.XCreateSimpleWindow.restype = ctypes.c_ulong\n"
"X11.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]\n"
"X11.XInternAtom.restype = ctypes.c_ulong\n"
"X11.XChangeProperty.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]\n"
"X11.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int]\n"
"dpy = X11.XOpenDisplay(None)\n"
"root = X11.XDefaultRootWindow(dpy)\n"
"X11.XSelectInput(dpy, root, 1 << 20)\n"
"w = X11.XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0)\n"
"a_chk = X11.XInternAtom(dpy, b'_NET_SUPPORTING_WM_CHECK', 0)\n"
"a_nm = X11.XInternAtom(dpy, b'_NET_WM_NAME', 0)\n"
"a_pid = X11.XInternAtom(dpy, b'_NET_WM_PID', 0)\n"
"a_utf = X11.XInternAtom(dpy, b'UTF8_STRING', 0)\n"
"a_win = X11.XInternAtom(dpy, b'WINDOW', 0)\n"
"a_card = X11.XInternAtom(dpy, b'CARDINAL', 0)\n"
"wv = ctypes.c_ulong(w)\n"
"pv = ctypes.c_ulong(os.getpid())\n"
"X11.XChangeProperty(dpy, w, a_chk, a_win, 32, 0, ctypes.byref(wv), 1)\n"
"X11.XChangeProperty(dpy, w, a_nm, a_utf, 8, 0, b'LegacyWM', 8)\n"
"X11.XChangeProperty(dpy, w, a_pid, a_card, 32, 0, ctypes.byref(pv), 1)\n"
"X11.XChangeProperty(dpy, root, a_chk, a_win, 32, 0, ctypes.byref(wv), 1)\n"
"X11.XSync(dpy, 0)\n"
"signal.signal(signal.SIGTERM, lambda s, f: os._exit(0))\n"
"while True: time.sleep(0.2)\n"
)
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
mock_wm = subprocess.Popen([sys.executable, "-c", mock_code], env=env)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
assert get_win_prop_str(dpy, wm1, "_NET_WM_NAME") == "LegacyWM"
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"fallback replace failed: stdout={rep.stdout} stderr={rep.stderr}"
assert wait_until(lambda: mock_wm.poll() is not None, timeout=3.0), "legacy WM was not stopped"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
assert get_win_prop_str(dpy, wm2, "_NET_WM_NAME") == "ANODE WM"
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
finally:
terminate(mock_wm)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_anode_session_holds_open_on_replace():
disp = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
env["XDG_CURRENT_DESKTOP"] = "ANODE"
env["XDG_SESSION_DESKTOP"] = "anode"
env["DESKTOP_SESSION"] = "anode"
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
sess1 = None
dpy = None
new_pid = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
sess1 = subprocess.Popen(
[os.path.join(tmp, "bin", "anode-session"), "--no-autostart"],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
assert get_win_prop_str(dpy, wm1, "_NET_WM_NAME") == "ANODE WM"
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"replace inside anode-session failed: {rep.stderr}"
wm2 = wait_until(
lambda: (lambda w: w if w and w != wm1 else None)(get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")),
timeout=5.0,
)
assert wm2
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
assert new_pid
# Original anode-session must stay alive after its dwm yields with status 75
time.sleep(0.8)
assert sess1.poll() is None, f"anode-session exited prematurely on replacement ({sess1.returncode})"
# Once the replacement WM exits, the original session holder should also exit cleanly
kill_pid_and_wait(new_pid)
new_pid = None
assert wait_until(lambda: sess1.poll() is not None, timeout=5.0), "anode-session did not exit after replacement WM died"
assert sess1.returncode == 0
finally:
terminate(sess1)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def compile_x11_flags():
try:
r = subprocess.run(
["pkg-config", "--cflags", "--libs", "x11"],
capture_output=True, text=True, check=True,
)
return r.stdout.split()
except Exception:
return ["-lX11"]
def test_dm_session_leader_guard():
disp = pick_display()
cc = os.environ.get("CC", "cc")
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
dm_bin = os.path.join(tmp, "bin", "lightdm")
wm_bin = os.path.join(tmp, "bin", "mockwm_tst")
dm_c = os.path.join(tmp, "lightdm.c")
with open(dm_c, "w", encoding="utf-8") as f:
f.write(
"#include <sys/wait.h>\n"
"#include <unistd.h>\n"
"int main(int argc, char **argv) {\n"
" if (argc < 2) return 1;\n"
" pid_t p = fork();\n"
" if (p == 0) { execvp(argv[1], argv + 1); _exit(127); }\n"
" int st = 0;\n"
" waitpid(p, &st, 0);\n"
" return WIFEXITED(st) ? WEXITSTATUS(st) : 1;\n"
"}\n"
)
subprocess.run([cc, "-O2", dm_c, "-o", dm_bin], check=True)
wm_c = os.path.join(tmp, "mockwm_tst.c")
with open(wm_c, "w", encoding="utf-8") as f:
f.write(
"#define _POSIX_C_SOURCE 200809L\n"
"#include <signal.h>\n"
"#include <string.h>\n"
"#include <time.h>\n"
"#include <unistd.h>\n"
"#include <X11/Xatom.h>\n"
"#include <X11/Xlib.h>\n"
"static volatile sig_atomic_t alive = 1;\n"
"static void stop_sig(int s) { (void)s; alive = 0; }\n"
"int main(void) {\n"
" signal(SIGTERM, stop_sig);\n"
" Display *d = XOpenDisplay(NULL);\n"
" if (!d) return 1;\n"
" Window root = DefaultRootWindow(d);\n"
" XSelectInput(d, root, SubstructureRedirectMask);\n"
" Window w = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n"
" Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n"
" Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n"
" Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n"
" XChangeProperty(d, w, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XChangeProperty(d, w, an, au, 8, PropModeReplace, (unsigned char *)\"mockwm_tst\", 10);\n"
" XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XSync(d, False);\n"
" while (alive) { struct timespec ts = {0, 100000000L}; nanosleep(&ts, NULL); }\n"
" XDestroyWindow(d, w);\n"
" XCloseDisplay(d);\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", wm_c, "-o", wm_bin] + compile_x11_flags(), check=True)
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dm_proc = None
dpy = None
new_pid = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dm_proc = subprocess.Popen([dm_bin, wm_bin], env=env)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
assert get_win_prop_str(dpy, wm1, "_NET_WM_NAME") == "mockwm_tst"
assert get_win_prop_ulong(dpy, wm1, "_NET_WM_PID") is None
dry = subprocess.run([REPLACE_BIN, "--dry-run"], env=env, capture_output=True, text=True)
assert dry.returncode == 0
assert "lightdm" in dry.stdout
assert "Warning:" in dry.stdout
blocked = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert blocked.returncode != 0, "expected DM session-leader guard to refuse without --force"
assert "lightdm" in blocked.stderr
assert "--switch-session" in blocked.stderr
assert "--force" in blocked.stderr
assert dm_proc.poll() is None, "blocked replace must leave mock DM/WM running"
forced = subprocess.run(
[REPLACE_BIN, "--force", "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert forced.returncode == 0, f"--force failed: stdout={forced.stdout} stderr={forced.stderr}"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
assert get_win_prop_str(dpy, wm2, "_NET_WM_NAME") == "ANODE WM"
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
finally:
terminate(dm_proc)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_switch_session_xprofile_handoff():
import pwd
disp = pick_display()
cc = os.environ.get("CC", "cc")
cur_user = os.environ.get("USER") or pwd.getpwuid(os.getuid()).pw_name
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
xdg_cache = os.path.join(tmp, "cache")
env["XDG_CACHE_HOME"] = xdg_cache
dm_bin = os.path.join(tmp, "bin", "lightdm")
wm_bin = os.path.join(tmp, "bin", "mockwm_tst")
# Stub dm-tool reporting current user already has an active LightDM session
dm_tool_stub = os.path.join(tmp, "bin", "dm-tool")
with open(dm_tool_stub, "w", encoding="utf-8") as f:
f.write(
f"#!/bin/sh\n"
f"if [ \"${{1:-}}\" = \"list-seats\" ]; then\n"
f" printf \"Seat0\\n CanSwitch=true\\n Session0\\n UserName='%s'\\n\" '{cur_user}'\n"
f" exit 0\n"
f"fi\n"
f"exit 0\n"
)
os.chmod(dm_tool_stub, 0o755)
dm_c = os.path.join(tmp, "lightdm.c")
with open(dm_c, "w", encoding="utf-8") as f:
f.write(
"#include <sys/wait.h>\n"
"#include <unistd.h>\n"
"int main(int argc, char **argv) {\n"
" if (argc < 2) return 1;\n"
" pid_t p = fork();\n"
" if (p == 0) { execvp(argv[1], argv + 1); _exit(127); }\n"
" int st = 0;\n"
" waitpid(p, &st, 0);\n"
" return WIFEXITED(st) ? WEXITSTATUS(st) : 1;\n"
"}\n"
)
subprocess.run([cc, "-O2", dm_c, "-o", dm_bin], check=True)
wm_c = os.path.join(tmp, "mockwm_tst.c")
with open(wm_c, "w", encoding="utf-8") as f:
f.write(
"#define _POSIX_C_SOURCE 200809L\n"
"#include <signal.h>\n"
"#include <time.h>\n"
"#include <unistd.h>\n"
"#include <X11/Xatom.h>\n"
"#include <X11/Xlib.h>\n"
"static volatile sig_atomic_t alive = 1;\n"
"static void stop_sig(int s) { (void)s; alive = 0; }\n"
"int main(void) {\n"
" signal(SIGTERM, stop_sig);\n"
" Display *d = XOpenDisplay(NULL);\n"
" if (!d) return 1;\n"
" Window root = DefaultRootWindow(d);\n"
" XSelectInput(d, root, SubstructureRedirectMask);\n"
" Window w = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n"
" Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n"
" Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n"
" Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n"
" XChangeProperty(d, w, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XChangeProperty(d, w, an, au, 8, PropModeReplace, (unsigned char *)\"mockwm_tst\", 10);\n"
" XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XSync(d, False);\n"
" while (alive) { struct timespec ts = {0, 100000000L}; nanosleep(&ts, NULL); }\n"
" XDestroyWindow(d, w);\n"
" XCloseDisplay(d);\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", wm_c, "-o", wm_bin] + compile_x11_flags(), check=True)
xprofile = os.path.join(env["HOME"], ".xprofile")
# Intentionally omit trailing newline to verify safe hook append
with open(xprofile, "w", encoding="utf-8") as f:
f.write("export USER_VAR=kept")
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dm_proc = None
dpy = None
switch_file = os.path.join(xdg_cache, "anode", "switch-once")
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dm_proc = subprocess.Popen([dm_bin, wm_bin], env=env)
assert wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
dry = subprocess.run(
[REPLACE_BIN, "--switch-session", "--profile", "work", "--dry-run"],
env=env, capture_output=True, text=True,
)
assert dry.returncode == 0, dry.stderr
assert ".xprofile" in dry.stdout and "switch-once" in dry.stdout
assert not os.path.exists(switch_file), "--dry-run must not write switch-once"
with open(xprofile, "r", encoding="utf-8") as f:
assert f.read() == "export USER_VAR=kept"
sw = subprocess.run(
[REPLACE_BIN, "--switch-session", "--profile", "work"],
env=env, capture_output=True, text=True,
)
assert sw.returncode == 0, f"--switch-session failed: {sw.stderr}"
assert wait_until(lambda: dm_proc.poll() is not None, timeout=4.0), "WM did not exit for session switch"
assert os.path.exists(switch_file), "switch-once sentinel was not created"
# Simulate LightDM /etc/lightdm/Xsession sourcing ~/.xprofile then running $@
xsession_sim = os.path.join(tmp, "Xsession")
with open(xsession_sim, "w", encoding="utf-8") as f:
f.write("#!/bin/sh\n. \"$HOME/.xprofile\"\nprintf 'USER_VAR=%s ARGS=%s\\n' \"${USER_VAR:-}\" \"$*\"\n")
os.chmod(xsession_sim, 0o755)
run1 = subprocess.run(["/bin/sh", xsession_sim, "i3"], env=env, capture_output=True, text=True, check=True)
expected_sess = os.path.join(ROOT, "scripts", "anode-session")
assert f"USER_VAR=kept ARGS={expected_sess} --profile work" == run1.stdout.strip(), run1.stdout
assert not os.path.exists(switch_file), "switch-once sentinel was not consumed on login"
# Subsequent login must return to original default session (one-shot)
run2 = subprocess.run(["/bin/sh", xsession_sim, "i3"], env=env, capture_output=True, text=True, check=True)
assert "USER_VAR=kept ARGS=i3" == run2.stdout.strip(), run2.stdout
# Re-running --switch-session without X11 WM still running must keep hook idempotent
sw_env = dict(env)
sw_env.pop("DISPLAY", None)
sw2 = subprocess.run(
[REPLACE_BIN, "--switch-session"],
env=sw_env, capture_output=True, text=True,
)
assert sw2.returncode == 0, sw2.stderr
with open(xprofile, "r", encoding="utf-8") as f:
xp_txt = f.read()
assert xp_txt.count("# >>> anode-switch-once >>>") == 1, "xprofile hook was duplicated"
assert "export USER_VAR=kept\n" in xp_txt
finally:
terminate(dm_proc)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_switch_session_stale_i3sock_fallback():
import pwd
disp = pick_display()
cc = os.environ.get("CC", "cc")
cur_user = os.environ.get("USER") or pwd.getpwuid(os.getuid()).pw_name
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
env["XDG_CACHE_HOME"] = os.path.join(tmp, "cache")
env["I3SOCK"] = "/nonexistent/i3/ipc-socket.9999"
dm_tool_stub = os.path.join(tmp, "bin", "dm-tool")
with open(dm_tool_stub, "w", encoding="utf-8") as f:
f.write(
f"#!/bin/sh\n"
f"if [ \"${{1:-}}\" = \"list-seats\" ]; then\n"
f" printf \"Seat0\\n CanSwitch=true\\n Session0\\n UserName='%s'\\n\" '{cur_user}'\n"
f"fi\nexit 0\n"
)
os.chmod(dm_tool_stub, 0o755)
seen_file = os.path.join(tmp, "i3sock_seen")
i3_msg_stub = os.path.join(tmp, "bin", "i3-msg")
with open(i3_msg_stub, "w", encoding="utf-8") as f:
f.write(
f"#!/bin/sh\n"
f"printf '%s\\n' \"${{I3SOCK:-UNSET}}\" > '{seen_file}'\n"
f"exit 1\n"
)
os.chmod(i3_msg_stub, 0o755)
wm_bin = os.path.join(tmp, "bin", "mock_i3")
wm_c = os.path.join(tmp, "mock_i3.c")
with open(wm_c, "w", encoding="utf-8") as f:
f.write(
"#define _POSIX_C_SOURCE 200809L\n"
"#include <signal.h>\n"
"#include <time.h>\n"
"#include <unistd.h>\n"
"#include <X11/Xatom.h>\n"
"#include <X11/Xlib.h>\n"
"static volatile sig_atomic_t alive = 1;\n"
"static void stop_sig(int s) { (void)s; alive = 0; }\n"
"int main(void) {\n"
" signal(SIGTERM, stop_sig);\n"
" Display *d = XOpenDisplay(NULL);\n"
" if (!d) return 1;\n"
" Window root = DefaultRootWindow(d);\n"
" XSelectInput(d, root, SubstructureRedirectMask);\n"
" Window w = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n"
" Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n"
" Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n"
" Atom ap = XInternAtom(d, \"_NET_WM_PID\", False);\n"
" Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n"
" unsigned long pid = (unsigned long)getpid();\n"
" XChangeProperty(d, w, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XChangeProperty(d, w, an, au, 8, PropModeReplace, (unsigned char *)\"i3\", 2);\n"
" XChangeProperty(d, w, ap, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);\n"
" XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n"
" XSync(d, False);\n"
" while (alive) { struct timespec ts = {0, 100000000L}; nanosleep(&ts, NULL); }\n"
" XDestroyWindow(d, w);\n"
" XCloseDisplay(d);\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", wm_c, "-o", wm_bin] + compile_x11_flags(), check=True)
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
wm_proc = None
dpy = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
wm_proc = subprocess.Popen([wm_bin], env=env)
assert wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
sw = subprocess.run([REPLACE_BIN, "--switch-session"], env=env, capture_output=True, text=True)
assert sw.returncode == 0, sw.stderr
assert wait_until(lambda: wm_proc.poll() is not None, timeout=4.0), "PID fallback did not stop WM after i3-msg failure"
with open(seen_file, "r", encoding="utf-8") as f:
assert f.read().strip() == "UNSET", "anode-replace did not unset stale I3SOCK before invoking i3-msg"
finally:
terminate(wm_proc)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_replace_display_scoped_daemon_cleanup():
disp = pick_display()
other_disp = ":199"
cc = os.environ.get("CC", "cc")
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
daemon_dir = os.path.join(tmp, "daemons")
os.makedirs(daemon_dir, exist_ok=True)
sleeper_c = os.path.join(tmp, "sleeper.c")
sleeper_bin = os.path.join(tmp, "sleeper")
with open(sleeper_c, "w", encoding="utf-8") as f:
f.write(
"#include <signal.h>\n"
"#include <unistd.h>\n"
"static void on_term(int s) { (void)s; _exit(0); }\n"
"int main(void) {\n"
" signal(SIGTERM, on_term);\n"
" while (1) pause();\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", sleeper_c, "-o", sleeper_bin], check=True)
statusd_bin = os.path.join(daemon_dir, "anode-statusd")
dunst_bin = os.path.join(daemon_dir, "dunst")
os.link(sleeper_bin, statusd_bin)
os.link(sleeper_bin, dunst_bin)
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dwm1 = None
dpy = None
new_pid = None
procs = []
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dwm1 = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
same_statusd = subprocess.Popen(
[statusd_bin], env=dict(env, DISPLAY=f"{disp}.0"),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
other_statusd = subprocess.Popen(
[statusd_bin], env=dict(env, DISPLAY=other_disp),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
same_dunst = subprocess.Popen(
[dunst_bin], env=dict(env, DISPLAY=disp),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
other_dunst = subprocess.Popen(
[dunst_bin], env=dict(env, DISPLAY=other_disp),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
procs = [same_statusd, other_statusd, same_dunst, other_dunst]
if os.path.isdir(f"/proc/{os.getpid()}"):
expected_comm = [
(same_statusd, "anode-statusd"),
(other_statusd, "anode-statusd"),
(same_dunst, "dunst"),
(other_dunst, "dunst"),
]
def comms_ready():
for p, name in expected_comm:
try:
with open(f"/proc/{p.pid}/comm", "r", encoding="utf-8") as cf:
if cf.read().strip() != name:
return False
except OSError:
return False
return True
assert wait_until(comms_ready, timeout=3.0), "dummy daemons did not finish exec"
else:
time.sleep(0.15)
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"anode-replace failed: stdout={rep.stdout} stderr={rep.stderr}"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
if wm2 and wm2 != wm1:
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
assert wait_until(lambda: same_statusd.poll() is not None, timeout=4.0), (
f"anode-statusd on {disp}.0 was not stopped by anode-replace"
)
assert wait_until(lambda: same_dunst.poll() is not None, timeout=4.0), (
f"dunst on {disp} was not stopped by anode-replace"
)
time.sleep(0.2)
assert other_statusd.poll() is None, f"anode-statusd on {other_disp} was killed across displays"
assert other_dunst.poll() is None, f"dunst on {other_disp} was killed across displays"
finally:
for p in procs:
terminate(p)
terminate(dwm1)
kill_pid_and_wait(new_pid)
time.sleep(0.15)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_replace_preserves_workspaces_and_states():
# Subtest A: ANODE -> ANODE replace preserves desktops, focus, floating geometry, and fullscreen
disp = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp)
xvfb = subprocess.Popen(
["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dwm1 = None
dpy = None
new_pid = None
wins = []
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dwm1 = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
a_type = X11.XInternAtom(dpy, b"_NET_WM_WINDOW_TYPE", 0)
a_dlg = X11.XInternAtom(dpy, b"_NET_WM_WINDOW_TYPE_DIALOG", 0)
a_atom = X11.XInternAtom(dpy, b"ATOM", 0)
a_fs = X11.XInternAtom(dpy, b"_NET_WM_STATE_FULLSCREEN", 0)
w1 = X11.XCreateSimpleWindow(dpy, root, 10, 40, 300, 200, 0, 0, 0xffffff)
w2 = X11.XCreateSimpleWindow(dpy, root, 120, 140, 420, 300, 0, 0, 0xffffff)
dlg_val = ctypes.c_ulong(a_dlg)
X11.XChangeProperty(dpy, w2, a_type, a_atom, 32, 0, ctypes.byref(dlg_val), 1)
w3 = X11.XCreateSimpleWindow(dpy, root, 20, 50, 300, 200, 0, 0, 0xffffff)
w4 = X11.XCreateSimpleWindow(dpy, root, 30, 60, 300, 200, 0, 0, 0xffffff)
wins = [w1, w2, w3, w4]
for w in wins:
X11.XMapWindow(dpy, w)
X11.XSync(dpy, 0)
assert wait_until(lambda: all(w in get_win_prop_ulong_list(dpy, root, "_NET_CLIENT_LIST") for w in wins), timeout=5.0)
send_ewmh_msg(dpy, root, w2, "_NET_WM_DESKTOP", [1, 2, 0, 0, 0])
send_ewmh_msg(dpy, root, w3, "_NET_WM_DESKTOP", [2, 2, 0, 0, 0])
send_ewmh_msg(dpy, root, w4, "_NET_WM_DESKTOP", [1, 2, 0, 0, 0])
send_ewmh_msg(dpy, root, w3, "_NET_WM_STATE", [1, a_fs, 0, 2, 0])
send_ewmh_msg(dpy, root, root, "_NET_CURRENT_DESKTOP", [1, 0, 0, 0, 0])
send_ewmh_msg(dpy, root, w4, "_NET_ACTIVE_WINDOW", [2, 0, 0, 0, 0])
def pre_state_ready():
return (
get_win_prop_ulong(dpy, root, "_NET_CURRENT_DESKTOP") == 1
and get_win_prop_ulong(dpy, root, "_NET_ACTIVE_WINDOW") == w4
and get_win_prop_ulong(dpy, w1, "_NET_WM_DESKTOP") == 0
and get_win_prop_ulong(dpy, w2, "_NET_WM_DESKTOP") == 1
and get_win_prop_ulong(dpy, w3, "_NET_WM_DESKTOP") == 2
and get_win_prop_ulong(dpy, w4, "_NET_WM_DESKTOP") == 1
and a_fs in get_win_prop_ulong_list(dpy, w3, "_NET_WM_STATE")
)
assert wait_until(pre_state_ready, timeout=5.0), "Pre-replace EWMH states did not settle"
X11.XMoveResizeWindow(dpy, w2, 120, 140, 420, 300)
X11.XSync(dpy, 0)
time.sleep(0.15)
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"anode-replace failed: stdout={rep.stdout} stderr={rep.stderr}"
assert wait_until(lambda: dwm1.poll() is not None, timeout=5.0)
assert dwm1.returncode == 75
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
def post_state_ready():
if get_win_prop_ulong(dpy, root, "_NET_CURRENT_DESKTOP") != 1:
return False
if get_win_prop_ulong(dpy, root, "_NET_ACTIVE_WINDOW") != w4:
return False
if get_win_prop_ulong(dpy, w1, "_NET_WM_DESKTOP") != 0:
return False
if get_win_prop_ulong(dpy, w2, "_NET_WM_DESKTOP") != 1:
return False
if get_win_prop_ulong(dpy, w3, "_NET_WM_DESKTOP") != 2:
return False
if get_win_prop_ulong(dpy, w4, "_NET_WM_DESKTOP") != 1:
return False
return a_fs in get_win_prop_ulong_list(dpy, w3, "_NET_WM_STATE")
assert wait_until(post_state_ready, timeout=5.0), (
f"Post-replace EWMH mismatch: cur={get_win_prop_ulong(dpy, root, '_NET_CURRENT_DESKTOP')} "
f"act={get_win_prop_ulong(dpy, root, '_NET_ACTIVE_WINDOW')} "
f"desks={[get_win_prop_ulong(dpy, w, '_NET_WM_DESKTOP') for w in wins]}"
)
attrs = {}
for w in wins:
a = XWindowAttributes()
assert X11.XGetWindowAttributes(dpy, w, ctypes.byref(a)) != 0
attrs[w] = (a.x, a.y, a.width, a.height)
assert attrs[w1][0] < 0 and attrs[w3][0] < 0, f"Hidden desktop windows not offscreen: {attrs}"
assert attrs[w2][0] >= 0 and attrs[w4][0] >= 0, f"Active desktop windows offscreen: {attrs}"
assert attrs[w2] == (120, 140, 420, 300), f"Floating geometry lost across replace: {attrs[w2]}"
finally:
if dpy:
for w in wins:
X11.XDestroyWindow(dpy, w)
terminate(dwm1)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
# Subtest B: Third-party EWMH WM -> ANODE replace preserves desktops even when old WM unmaps & strips props
disp2 = pick_display()
cc = os.environ.get("CC", "cc")
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp2)
ewmh_c = os.path.join(tmp, "mock_ewmh.c")
ewmh_bin = os.path.join(tmp, "bin", "mock_ewmh")
with open(ewmh_c, "w", encoding="utf-8") as f:
f.write(
"#define _POSIX_C_SOURCE 200809L\n"
"#include <signal.h>\n"
"#include <time.h>\n"
"#include <unistd.h>\n"
"#include <X11/Xatom.h>\n"
"#include <X11/Xlib.h>\n"
"static volatile sig_atomic_t alive = 1;\n"
"static void on_sig(int s) { (void)s; alive = 0; }\n"
"int main(void) {\n"
" signal(SIGTERM, on_sig);\n"
" Display *d = XOpenDisplay(NULL);\n"
" if (!d) return 1;\n"
" Window root = DefaultRootWindow(d);\n"
" XSelectInput(d, root, SubstructureRedirectMask);\n"
" Window wmc = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n"
" Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n"
" Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n"
" Atom ap = XInternAtom(d, \"_NET_WM_PID\", False);\n"
" Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n"
" Atom acl = XInternAtom(d, \"_NET_CLIENT_LIST\", False);\n"
" Atom acd = XInternAtom(d, \"_NET_CURRENT_DESKTOP\", False);\n"
" Atom aact = XInternAtom(d, \"_NET_ACTIVE_WINDOW\", False);\n"
" unsigned long pid = (unsigned long)getpid();\n"
" XChangeProperty(d, wmc, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmc, 1);\n"
" XChangeProperty(d, wmc, an, au, 8, PropModeReplace, (unsigned char *)\"MockEWMH\", 8);\n"
" XChangeProperty(d, wmc, ap, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);\n"
" XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmc, 1);\n"
" XSync(d, False);\n"
" while (alive) { struct timespec ts = {0, 50000000L}; nanosleep(&ts, NULL); }\n"
" XDeleteProperty(d, root, acd);\n"
" XDeleteProperty(d, root, acl);\n"
" XDeleteProperty(d, root, aact);\n"
" XDestroyWindow(d, wmc);\n"
" XSync(d, False);\n"
" XCloseDisplay(d);\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", ewmh_c, "-o", ewmh_bin] + compile_x11_flags(), check=True)
xvfb = subprocess.Popen(
["Xvfb", disp2, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
mwm = None
dpy = None
new_pid = None
app_wins = []
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp2.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
a_card = X11.XInternAtom(dpy, b"CARDINAL", 0)
a_win = X11.XInternAtom(dpy, b"WINDOW", 0)
a_atom = X11.XInternAtom(dpy, b"ATOM", 0)
a_cl = X11.XInternAtom(dpy, b"_NET_CLIENT_LIST", 0)
a_cd = X11.XInternAtom(dpy, b"_NET_CURRENT_DESKTOP", 0)
a_wd = X11.XInternAtom(dpy, b"_NET_WM_DESKTOP", 0)
a_act = X11.XInternAtom(dpy, b"_NET_ACTIVE_WINDOW", 0)
a_wms = X11.XInternAtom(dpy, b"_NET_WM_STATE", 0)
a_fs = X11.XInternAtom(dpy, b"_NET_WM_STATE_FULLSCREEN", 0)
wa = X11.XCreateSimpleWindow(dpy, root, 10, 40, 280, 180, 0, 0, 0xffffff)
wb = X11.XCreateSimpleWindow(dpy, root, 0, 0, 1280, 720, 0, 0, 0xffffff)
wc = X11.XCreateSimpleWindow(dpy, root, 50, 60, 320, 220, 0, 0, 0xffffff)
app_wins = [wa, wb, wc]
X11.XMapWindow(dpy, wc)
for w, desk in ((wa, 0), (wb, 1), (wc, 2)):
dv = ctypes.c_ulong(desk)
X11.XChangeProperty(dpy, w, a_wd, a_card, 32, 0, ctypes.byref(dv), 1)
fs_v = ctypes.c_ulong(a_fs)
X11.XChangeProperty(dpy, wb, a_wms, a_atom, 32, 0, ctypes.byref(fs_v), 1)
cl_arr = (ctypes.c_ulong * 3)(wa, wb, wc)
X11.XChangeProperty(dpy, root, a_cl, a_win, 32, 0, cl_arr, 3)
cd_v = ctypes.c_ulong(2)
X11.XChangeProperty(dpy, root, a_cd, a_card, 32, 0, ctypes.byref(cd_v), 1)
act_v = ctypes.c_ulong(wc)
X11.XChangeProperty(dpy, root, a_act, a_win, 32, 0, ctypes.byref(act_v), 1)
X11.XSync(dpy, 0)
mwm = subprocess.Popen([ewmh_bin], env=env)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"3rd-party replace failed: stdout={rep.stdout} stderr={rep.stderr}"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
def third_party_ok():
clist = get_win_prop_ulong_list(dpy, root, "_NET_CLIENT_LIST")
return (
get_win_prop_ulong(dpy, root, "_NET_CURRENT_DESKTOP") == 2
and all(w in clist for w in (wa, wb, wc))
and get_win_prop_ulong(dpy, root, "_NET_ACTIVE_WINDOW") == wc
and get_win_prop_ulong(dpy, wa, "_NET_WM_DESKTOP") == 0
and get_win_prop_ulong(dpy, wb, "_NET_WM_DESKTOP") == 1
and get_win_prop_ulong(dpy, wc, "_NET_WM_DESKTOP") == 2
and a_fs in get_win_prop_ulong_list(dpy, wb, "_NET_WM_STATE")
)
assert wait_until(third_party_ok, timeout=5.0), (
f"3rd-party preserve mismatch: cur={get_win_prop_ulong(dpy, root, '_NET_CURRENT_DESKTOP')} "
f"clist={get_win_prop_ulong_list(dpy, root, '_NET_CLIENT_LIST')} "
f"act={get_win_prop_ulong(dpy, root, '_NET_ACTIVE_WINDOW')}"
)
for w, expect_vis in ((wa, False), (wb, False), (wc, True)):
a = XWindowAttributes()
assert X11.XGetWindowAttributes(dpy, w, ctypes.byref(a)) != 0
if expect_vis:
assert a.x >= 0, f"Active desktop window {w} offscreen: {a.x}"
else:
assert a.x < 0, f"Hidden desktop window {w} not offscreen: {a.x}"
finally:
if dpy:
for w in app_wins:
X11.XDestroyWindow(dpy, w)
terminate(mwm)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def test_replace_autostart_reload_default_and_slow_snapshot_guard():
# Part 1: Default anode-replace runs anode-autostart reload (not start / not XDG .desktop),
# while anode-replace --autostart explicitly runs full anode-autostart start.
disp1 = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp1)
os.symlink(os.path.join(ROOT, "scripts", "anode-autostart"), os.path.join(tmp, "bin", "anode-autostart"))
xdg_sys = os.path.join(tmp, "xdg_sys")
os.makedirs(os.path.join(xdg_sys, "autostart"), exist_ok=True)
os.makedirs(os.path.join(env["XDG_CONFIG_HOME"], "anode"), exist_ok=True)
env["XDG_CONFIG_DIRS"] = xdg_sys
env["ANODE_XDG_AUTOSTART"] = "1"
env["ANODE_FORCE_POLKIT_AGENT"] = "1"
m_exec = os.path.join(tmp, "exec.log")
m_once = os.path.join(tmp, "once.log")
m_always = os.path.join(tmp, "always.log")
m_polkit = os.path.join(tmp, "lxpolkit.log")
lx_stub = os.path.join(tmp, "bin", "lxpolkit")
with open(lx_stub, "w", encoding="utf-8") as f:
f.write(f"#!/bin/sh\nprintf 'pk\\n' >> '{m_polkit}'\n")
os.chmod(lx_stub, 0o755)
once_stub = os.path.join(tmp, "bin", "anode_once_stub")
with open(once_stub, "w", encoding="utf-8") as f:
f.write(f"#!/bin/sh\nprintf 'o\\n' >> '{m_once}'\n")
os.chmod(once_stub, 0o755)
with open(os.path.join(env["XDG_CONFIG_HOME"], "anode", "autostart"), "w", encoding="utf-8") as f:
f.write(
f"exec sh -c \"printf 'e\\n' >> '{m_exec}'\"\n"
"exec_once anode_once_stub\n"
f"exec_always sh -c \"printf 'a\\n' >> '{m_always}'\"\n"
)
with open(os.path.join(xdg_sys, "autostart", "lxpolkit.desktop"), "w", encoding="utf-8") as f:
f.write("[Desktop Entry]\nType=Application\nTryExec=lxpolkit\nExec=lxpolkit\n")
xvfb = subprocess.Popen(
["Xvfb", disp1, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dwm1 = None
dpy = None
cur_pid = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp1.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dwm1 = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
rep1 = subprocess.run([REPLACE_BIN, "--keep-panels"], env=env, capture_output=True, text=True)
assert rep1.returncode == 0, f"default replace failed: stdout={rep1.stdout} stderr={rep1.stderr}"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
cur_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
assert wait_until(lambda: os.path.exists(m_always), timeout=4.0), "default replace did not run exec_always"
time.sleep(0.35)
assert not os.path.exists(m_exec), "default replace must not re-run exec"
assert not os.path.exists(m_once), "default replace must not re-run exec_once"
assert not os.path.exists(m_polkit), "default replace must not re-run XDG lxpolkit.desktop"
rep2 = subprocess.run([REPLACE_BIN, "--autostart", "--keep-panels"], env=env, capture_output=True, text=True)
assert rep2.returncode == 0, f"--autostart replace failed: stdout={rep2.stdout} stderr={rep2.stderr}"
wm3 = wait_until(
lambda: (lambda w: w if w and w != wm2 else None)(get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")),
timeout=5.0,
)
assert wm3
cur_pid = get_win_prop_ulong(dpy, wm3, "_NET_WM_PID")
assert wait_until(lambda: os.path.exists(m_exec), timeout=4.0), "--autostart did not run exec"
assert wait_until(lambda: os.path.exists(m_once), timeout=4.0), "--autostart did not run exec_once"
assert wait_until(lambda: os.path.exists(m_polkit), timeout=4.0), "--autostart did not run XDG desktop"
finally:
terminate(dwm1)
kill_pid_and_wait(cur_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
# Part 2: Slow pre-dwm setup (>1.5s) + third-party WM resetting _NET_WM_DESKTOP=0 / _NET_CURRENT_DESKTOP=0
# on SIGTERM + sparse _NET_DESKTOP_NAMES ("1", "3:code", "5").
disp2 = pick_display()
cc = os.environ.get("CC", "cc")
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp2)
with open(os.path.join(env["HOME"], ".Xresources"), "w", encoding="utf-8") as f:
f.write("theme.name: Anodized\n")
xrdb_shim = os.path.join(tmp, "bin", "xrdb")
with open(xrdb_shim, "w", encoding="utf-8") as f:
f.write("#!/bin/sh\nsleep 1.8\n")
os.chmod(xrdb_shim, 0o755)
ewmh_c = os.path.join(tmp, "mock_ewmh_reset.c")
ewmh_bin = os.path.join(tmp, "bin", "mock_ewmh_reset")
with open(ewmh_c, "w", encoding="utf-8") as f:
f.write(
"#define _POSIX_C_SOURCE 200809L\n"
"#include <signal.h>\n"
"#include <stdlib.h>\n"
"#include <time.h>\n"
"#include <unistd.h>\n"
"#include <X11/Xatom.h>\n"
"#include <X11/Xlib.h>\n"
"static volatile sig_atomic_t alive = 1;\n"
"static void on_sig(int s) { (void)s; alive = 0; }\n"
"int main(int argc, char **argv) {\n"
" signal(SIGTERM, on_sig);\n"
" Display *d = XOpenDisplay(NULL);\n"
" if (!d) return 1;\n"
" Window root = DefaultRootWindow(d);\n"
" XSelectInput(d, root, SubstructureRedirectMask);\n"
" Window wmc = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n"
" Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n"
" Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n"
" Atom ap = XInternAtom(d, \"_NET_WM_PID\", False);\n"
" Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n"
" Atom acd = XInternAtom(d, \"_NET_CURRENT_DESKTOP\", False);\n"
" Atom awd = XInternAtom(d, \"_NET_WM_DESKTOP\", False);\n"
" Atom adn = XInternAtom(d, \"_NET_DESKTOP_NAMES\", False);\n"
" unsigned long pid = (unsigned long)getpid();\n"
" const char names[] = \"1\\0\" \"3:code\\0\" \"5\";\n"
" XChangeProperty(d, wmc, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmc, 1);\n"
" XChangeProperty(d, wmc, an, au, 8, PropModeReplace, (unsigned char *)\"MockResetWM\", 11);\n"
" XChangeProperty(d, wmc, ap, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);\n"
" XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmc, 1);\n"
" XChangeProperty(d, root, adn, au, 8, PropModeReplace, (const unsigned char *)names, sizeof(names));\n"
" XSync(d, False);\n"
" while (alive) { struct timespec ts = {0, 50000000L}; nanosleep(&ts, NULL); }\n"
" unsigned long zero = 0;\n"
" XChangeProperty(d, root, acd, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&zero, 1);\n"
" for (int i = 1; i < argc; i++) {\n"
" Window cw = (Window)strtoul(argv[i], NULL, 0);\n"
" if (cw != None)\n"
" XChangeProperty(d, cw, awd, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&zero, 1);\n"
" }\n"
" XDestroyWindow(d, wmc);\n"
" XSync(d, False);\n"
" XCloseDisplay(d);\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", ewmh_c, "-o", ewmh_bin] + compile_x11_flags(), check=True)
xvfb = subprocess.Popen(
["Xvfb", disp2, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
mwm = None
dpy = None
new_pid = None
app_wins = []
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp2.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
a_card = X11.XInternAtom(dpy, b"CARDINAL", 0)
a_win = X11.XInternAtom(dpy, b"WINDOW", 0)
a_cl = X11.XInternAtom(dpy, b"_NET_CLIENT_LIST", 0)
a_cd = X11.XInternAtom(dpy, b"_NET_CURRENT_DESKTOP", 0)
a_wd = X11.XInternAtom(dpy, b"_NET_WM_DESKTOP", 0)
a_act = X11.XInternAtom(dpy, b"_NET_ACTIVE_WINDOW", 0)
wa = X11.XCreateSimpleWindow(dpy, root, 10, 40, 280, 180, 0, 0, 0xffffff)
wb = X11.XCreateSimpleWindow(dpy, root, 40, 60, 300, 200, 0, 0, 0xffffff)
wc = X11.XCreateSimpleWindow(dpy, root, 70, 80, 320, 220, 0, 0, 0xffffff)
app_wins = [wa, wb, wc]
X11.XMapWindow(dpy, wb)
for w, desk in ((wa, 0), (wb, 1), (wc, 2)):
dv = ctypes.c_ulong(desk)
X11.XChangeProperty(dpy, w, a_wd, a_card, 32, 0, ctypes.byref(dv), 1)
cl_arr = (ctypes.c_ulong * 3)(wa, wb, wc)
X11.XChangeProperty(dpy, root, a_cl, a_win, 32, 0, cl_arr, 3)
cd_v = ctypes.c_ulong(1)
X11.XChangeProperty(dpy, root, a_cd, a_card, 32, 0, ctypes.byref(cd_v), 1)
act_v = ctypes.c_ulong(wb)
X11.XChangeProperty(dpy, root, a_act, a_win, 32, 0, ctypes.byref(act_v), 1)
X11.XSync(dpy, 0)
mwm = subprocess.Popen([ewmh_bin, hex(wa), hex(wb), hex(wc)], env=env)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"slow/sparse replace failed: stdout={rep.stdout} stderr={rep.stderr}"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
def sparse_ok():
return (
get_win_prop_ulong(dpy, root, "_NET_CURRENT_DESKTOP") == 2
and get_win_prop_ulong(dpy, wa, "_NET_WM_DESKTOP") == 0
and get_win_prop_ulong(dpy, wb, "_NET_WM_DESKTOP") == 2
and get_win_prop_ulong(dpy, wc, "_NET_WM_DESKTOP") == 4
and get_win_prop_ulong(dpy, root, "_NET_ACTIVE_WINDOW") == wb
)
assert wait_until(sparse_ok, timeout=5.0), (
f"sparse/slow restore mismatch: cur={get_win_prop_ulong(dpy, root, '_NET_CURRENT_DESKTOP')} "
f"desks={[get_win_prop_ulong(dpy, w, '_NET_WM_DESKTOP') for w in app_wins]} "
f"act={get_win_prop_ulong(dpy, root, '_NET_ACTIVE_WINDOW')}"
)
finally:
if dpy:
for w in app_wins:
X11.XDestroyWindow(dpy, w)
terminate(mwm)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def main():
if not shutil.which("Xvfb"):
print("test_replace: Xvfb not installed (skipping)")
return 0
assert os.path.isfile(DWM_BIN), f"missing {DWM_BIN}"
test_fastfetch_identity()
test_icccm_replace_and_client_preservation()
test_non_icccm_wm_fallback_replace()
test_anode_session_holds_open_on_replace()
test_dm_session_leader_guard()
test_switch_session_xprofile_handoff()
test_switch_session_stale_i3sock_fallback()
test_replace_display_scoped_daemon_cleanup()
test_replace_preserves_workspaces_and_states()
test_replace_autostart_reload_default_and_slow_snapshot_guard()
print("test_replace: OK")
return 0
if __name__ == "__main__":
sys.exit(main())