"""Linux global keys (framegen/globalkeys.py): parsing, picking X11 / portal / none, and a real XGrabKey on an X server (Xvfb here, or the desktop's) with key presses sent through XTest. That test is skipped without one.""" import ctypes import ctypes.util import os import pathlib import shutil import subprocess import sys import time import pytest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from framegen import globalkeys as gk def test_parse_and_portal_trigger(): assert gk.parse("ctrl+alt+r") == (gk.CONTROL | gk.MOD1, "r") assert gk.parse(" Ctrl + Shift + F9 ") == (gk.CONTROL | gk.SHIFT, "F9") # (as X names the key) assert gk.portal_trigger("ctrl+alt+r") == "CTRL+ALT+r" for bad in ("r", "shift+r", "ctrl+alt", "ctrl+r+t"): with pytest.raises(ValueError): gk.parse(bad) def test_a_key_on_its_own_only_for_the_overlay(): assert gk.parse("Insert", bare=True) == (0, "Insert") assert gk.parse("home", bare=True) == (0, "Home") assert gk.parse("ctrl+pageup") == (gk.CONTROL, "Prior") with pytest.raises(ValueError): gk.parse("Insert") def test_backend_follows_the_session(): assert gk.backend({"XDG_SESSION_TYPE": "x11", "DISPLAY": ":0"})[0] == "x11" assert gk.backend({"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":0", "WAYLAND_DISPLAY": "wayland-0"})[0] == "portal" assert gk.backend({"WAYLAND_DISPLAY": "wayland-0"})[0] == "portal" assert gk.backend({"DISPLAY": ":1"})[0] == "x11" assert gk.backend({})[0] == "none" def test_no_session_is_reported_not_hidden(capsys): k = gk.GlobalKeys({"ctrl+alt+r": lambda: None}, env={}) k.start() k.stop() assert k.status == "global keys unavailable: no X11 or Wayland session" assert "unavailable" in capsys.readouterr().out def test_portal_without_jeepney_says_so(monkeypatch): monkeypatch.setitem(sys.modules, "jeepney", None) # import fails k = gk.GlobalKeys({"ctrl+alt+r": lambda: None}, env={"XDG_SESSION_TYPE": "wayland"}) k.start() assert "jeepney" in k.status and "unavailable" in k.status def test_wayland_falls_back_to_an_xwayland_grab_when_the_portal_fails(monkeypatch): monkeypatch.setitem(sys.modules, "jeepney", None) # the portal can't be asked started = [] monkeypatch.setattr(gk.X11Keys, "start", lambda self: started.append(self.name)) k = gk.GlobalKeys({"ctrl+alt+r": lambda: None}, env={"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":5"}) k.start() assert started == [":5"] and k.kind == "xwayland" @pytest.fixture def xserver(): if os.environ.get("DISPLAY"): yield os.environ["DISPLAY"] return if not shutil.which("Xvfb"): pytest.skip("no X server and no Xvfb") disp = ":97" p = subprocess.Popen(["Xvfb", disp, "-screen", "0", "640x480x24"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(1.0) yield disp p.terminate() p.wait(5) def _press(disp, keys): """XTest: press and release `keys` (keysym names) like a keyboard would.""" tst = ctypes.util.find_library("Xtst") if not tst: pytest.skip("no libXtst") x, t = ctypes.CDLL(ctypes.util.find_library("X11")), ctypes.CDLL(tst) x.XOpenDisplay.restype = ctypes.c_void_p x.XOpenDisplay.argtypes = [ctypes.c_char_p] x.XStringToKeysym.restype, x.XStringToKeysym.argtypes = ctypes.c_ulong, [ctypes.c_char_p] x.XKeysymToKeycode.restype, x.XKeysymToKeycode.argtypes = ctypes.c_ubyte, [ctypes.c_void_p, ctypes.c_ulong] x.XFlush.argtypes = x.XCloseDisplay.argtypes = [ctypes.c_void_p] t.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong] d = x.XOpenDisplay(disp.encode()) codes = [x.XKeysymToKeycode(d, x.XStringToKeysym(k.encode())) for k in keys] for c in codes: t.XTestFakeKeyEvent(d, c, 1, 0) for c in reversed(codes): t.XTestFakeKeyEvent(d, c, 0, 0) x.XFlush(d) x.XCloseDisplay(d) def test_x11_grab_fires_on_the_key_only(xserver): hits = [] k = gk.X11Keys({"ctrl+alt+r": lambda: hits.append("r"), "ctrl+alt+b": lambda: hits.append("b")}, display=xserver) k.start() try: assert k.error is None and k.got == ["ctrl+alt+r", "ctrl+alt+b"], (k.error, k.got, k.taken) _press(xserver, ["Control_L", "Alt_L", "r"]) time.sleep(0.6) _press(xserver, ["r"]) # without the modifiers: not ours _press(xserver, ["Control_L", "Alt_L", "b"]) time.sleep(0.6) assert hits == ["r", "b"] # a second grab of the same key is refused by the X server and reported as taken other = gk.X11Keys({"ctrl+alt+r": lambda: None}, display=xserver) other.start() assert other.taken == ["ctrl+alt+r"] and other.got == [] other.stop() finally: k.stop() def test_the_overlays_key_and_the_keyboard_while_it_is_open(xserver, monkeypatch): """Insert on its own toggles; the arrows, Enter and Esc come here only while the overlay is open, and the keyboard goes back by itself if the overlay stops asking for it.""" monkeypatch.setattr(gk, "MODAL_S", 0.8) toggles, nav = [], [] k = gk.X11Keys({"Insert": lambda: toggles.append(1)}, display=xserver, bare=True) k.start() try: assert k.error is None and k.got == ["Insert"], (k.error, k.got, k.taken) _press(xserver, ["Insert"]) for key in ("Escape", "Up", "Return"): # closed: these are the game's _press(xserver, [key]) time.sleep(0.5) assert toggles == [1] and nav == [] and k.modal == "" k.set_modal(True, lambda name, shift: nav.append((name, shift))) time.sleep(0.3) assert k.modal == "keyboard" for key in ("Up", "Return", "Escape"): _press(xserver, [key]) _press(xserver, ["Shift_L", "Tab"]) time.sleep(0.3) k.set_modal(True, None) # still open assert [n for n in nav if n[0] != "shift_l"] == [("up", False), ("return", False), ("escape", False), ("tab", True)] _press(xserver, ["Insert"]) # the overlay's key still toggles while it's open time.sleep(0.3) assert toggles == [1, 1] k.set_modal(False) time.sleep(0.3) seen = len(nav) _press(xserver, ["Escape"]) time.sleep(0.3) assert k.modal == "" and len(nav) == seen # closed again: Esc is the game's k.set_modal(True, lambda name, shift: nav.append((name, shift))) time.sleep(0.3) assert k.modal == "keyboard" time.sleep(1.2) # the video loop stalled: nobody asks again assert k.modal == "" finally: k.stop()