engine: global save-clip key on Linux (X11 XGrabKey via ctypes; Wayland GlobalShortcuts portal, untested)

Instant replay's Ctrl+Alt+R / Ctrl+Alt+B now work from any window on X11, so they reach the engine while
the game keeps the keyboard. On Wayland the portal is used through jeepney when it is installed; that path is
untested. Without either the engine prints why there is no global key.
This commit is contained in:
alex committed 2026-11-24 07:31:06 +00:00
1 parent 085fd2d5ed
commit 9231102a3e
3 files changed
+417 -1

No files matched your search

+306
View File
@@ -0,0 +1,306 @@
"""System-wide keys on Linux: the save-a-clip key works while the game, not the engine, has the keyboard.
X11 XGrabKey on the root window, through libX11 with ctypes (no extra package). A key another program
already grabbed is reported as taken.
Wayland xdg-desktop-portal's GlobalShortcuts, if the desktop has it and the `jeepney` package is installed.
The desktop asks the user to confirm the key, and may give a different one. NOT TESTED: no Wayland
desktop with that portal was available while this was written.
else reported as unavailable (`GlobalKeys.status`), and the engine window's own keys (R) still work.
Same interface as replay.Hotkeys (Windows): GlobalKeys({"ctrl+alt+r": fn}).start() / .stop().
"""
from __future__ import annotations
import ctypes
import ctypes.util
import os
import select
import threading
import time
from ctypes import POINTER, Structure, Union, byref, c_char_p, c_int, c_long, c_uint, c_ulong, c_void_p
# X11 modifier masks
SHIFT, LOCK, CONTROL, MOD1, MOD2, MOD4 = 1, 2, 4, 8, 16, 64
MODS = {"shift": SHIFT, "ctrl": CONTROL, "control": CONTROL, "alt": MOD1, "super": MOD4, "win": MOD4}
# NumLock (usually Mod2) and CapsLock change the modifier state: a grab is made for each combination of them
IGNORED = (0, LOCK, MOD2, LOCK | MOD2)
KEYPRESS = 2
REPEAT_S = 0.4 # holding the keys down repeats KeyPress: one save per press
def parse(combo: str) -> tuple[int, str]:
""""ctrl+alt+r" -> (X11 modifier mask, key name for XStringToKeysym). ValueError if it has no key or no
modifier (a key on its own would be taken from the game)."""
parts = [p.strip().lower() for p in combo.split("+") if p.strip()]
mods, key = 0, None
for p in parts:
if p in MODS:
mods |= MODS[p]
elif key is None:
key = p
else:
raise ValueError(f"{combo!r}: more than one key")
if key is None:
raise ValueError(f"{combo!r}: no key")
if not mods & (CONTROL | MOD1 | MOD4):
raise ValueError(f"{combo!r}: needs Ctrl, Alt or Super")
return mods, key
def portal_trigger(combo: str) -> str:
""""ctrl+alt+r" -> "CTRL+ALT+r", the shortcuts spec's form for the portal's preferred_trigger."""
mods, key = parse(combo)
names = [n for n, m in (("CTRL", CONTROL), ("ALT", MOD1), ("SHIFT", SHIFT), ("LOGO", MOD4)) if mods & m]
return "+".join(names + [key])
def backend(env=os.environ) -> tuple[str, str]:
"""Which way to get global keys in this session: ("x11" | "portal" | "none", why)."""
kind = env.get("XDG_SESSION_TYPE", "").lower()
if kind == "wayland" or (not kind and env.get("WAYLAND_DISPLAY")):
return "portal", "Wayland session: xdg-desktop-portal GlobalShortcuts"
if env.get("DISPLAY"):
return "x11", f"X11 session (DISPLAY={env['DISPLAY']}): XGrabKey"
return "none", "no X11 or Wayland session"
class _XKeyEvent(Structure):
_fields_ = [("type", c_int), ("serial", c_ulong), ("send_event", c_int), ("display", c_void_p),
("window", c_ulong), ("root", c_ulong), ("subwindow", c_ulong), ("time", c_ulong),
("x", c_int), ("y", c_int), ("x_root", c_int), ("y_root", c_int), ("state", c_uint),
("keycode", c_uint), ("same_screen", c_int)]
class _XEvent(Union):
_fields_ = [("type", c_int), ("xkey", _XKeyEvent), ("pad", c_long * 24)]
class _XErrorEvent(Structure):
_fields_ = [("type", c_int), ("display", c_void_p), ("resourceid", c_ulong), ("serial", c_ulong),
("error_code", ctypes.c_ubyte), ("request_code", ctypes.c_ubyte), ("minor_code", ctypes.c_ubyte)]
_x_errors: list[int] = []
_ERR_FN = ctypes.CFUNCTYPE(c_int, c_void_p, POINTER(_XErrorEvent))
_ERROR_HANDLER = _ERR_FN(lambda _d, e: (_x_errors.append(e.contents.error_code), 0)[1]) # kept alive: Xlib holds it
BAD_ACCESS = 10
class X11Keys:
"""XGrabKey on the root window of its own X connection, read on a thread of its own."""
def __init__(self, keys: dict, display: str | None = None) -> None:
self.keys, self.name = keys, display or os.environ.get("DISPLAY", ":0")
self.got: list[str] = [] # combos grabbed
self.taken: list[str] = [] # combos another program has
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._ready = threading.Event()
self.error: str | None = None
def start(self) -> None:
self._thread = threading.Thread(target=self._run, name="globalkeys-x11", daemon=True)
self._thread.start()
self._ready.wait(5)
def _run(self) -> None:
try:
x = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6")
except OSError as e:
self.error = f"libX11 not found ({e})"
self._ready.set()
return
x.XOpenDisplay.restype, x.XOpenDisplay.argtypes = c_void_p, [c_char_p]
x.XDefaultRootWindow.restype, x.XDefaultRootWindow.argtypes = c_ulong, [c_void_p]
x.XStringToKeysym.restype, x.XStringToKeysym.argtypes = c_ulong, [c_char_p]
x.XKeysymToKeycode.restype, x.XKeysymToKeycode.argtypes = ctypes.c_ubyte, [c_void_p, c_ulong]
x.XGrabKey.argtypes = [c_void_p, c_int, c_uint, c_ulong, c_int, c_int, c_int]
x.XUngrabKey.argtypes = [c_void_p, c_int, c_uint, c_ulong]
x.XSync.argtypes = [c_void_p, c_int]
x.XPending.argtypes = [c_void_p]
x.XNextEvent.argtypes = [c_void_p, POINTER(_XEvent)]
x.XConnectionNumber.argtypes = [c_void_p]
x.XCloseDisplay.argtypes = [c_void_p]
x.XSetErrorHandler.restype, x.XSetErrorHandler.argtypes = c_void_p, [c_void_p]
d = x.XOpenDisplay(self.name.encode())
if not d:
self.error = f"can't open the X display {self.name}"
self._ready.set()
return
root = x.XDefaultRootWindow(d)
fns: dict[tuple[int, int], tuple[str, object]] = {}
try:
for combo, fn in self.keys.items():
mods, key = parse(combo)
sym = x.XStringToKeysym(key.encode())
code = x.XKeysymToKeycode(d, sym) if sym else 0
if not code:
print(f"[keys] {combo}: no key {key!r} on this keyboard")
continue
x.XSetErrorHandler(_ERROR_HANDLER)
_x_errors.clear()
for extra in IGNORED:
x.XGrabKey(d, code, mods | extra, root, 1, 1, 1) # owner_events, GrabModeAsync x2
x.XSync(d, 0)
if BAD_ACCESS in _x_errors:
for extra in IGNORED:
x.XUngrabKey(d, code, mods | extra, root)
self.taken.append(combo)
print(f"[keys] {combo} is taken by another program; use the engine window's own key")
continue
fns[(code, mods)] = (combo, fn)
self.got.append(combo)
except ValueError as e:
print(f"[keys] {e}")
self._ready.set()
fd = x.XConnectionNumber(d)
ev, last = _XEvent(), {}
try:
while not self._stop.is_set():
if not x.XPending(d):
select.select([fd], [], [], 0.25)
continue
x.XNextEvent(d, byref(ev))
if ev.type != KEYPRESS:
continue
k = (ev.xkey.keycode, ev.xkey.state & (SHIFT | CONTROL | MOD1 | MOD4))
hit = fns.get(k)
if hit is None:
continue
now = time.monotonic()
if now - last.get(k, 0) < REPEAT_S:
last[k] = now
continue
last[k] = now
combo, fn = hit
try:
fn()
except Exception as e: # noqa: BLE001 - a failing save must not end the key thread
print(f"[keys] {combo}: {e}")
finally:
for code, mods in fns:
for extra in IGNORED:
x.XUngrabKey(d, code, mods | extra, root)
x.XSync(d, 0)
x.XCloseDisplay(d)
def stop(self) -> None:
self._stop.set()
if self._thread is not None and self._thread.is_alive():
self._thread.join(timeout=2)
class PortalKeys:
"""xdg-desktop-portal GlobalShortcuts over D-Bus with jeepney. Untested (see the module's note)."""
IFACE = "org.freedesktop.portal.GlobalShortcuts"
def __init__(self, keys: dict) -> None:
self.keys = keys
self.got: list[str] = []
self.taken: list[str] = []
self.error: str | None = None
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._ready = threading.Event()
def start(self) -> None:
self._thread = threading.Thread(target=self._run, name="globalkeys-portal", daemon=True)
self._thread.start()
self._ready.wait(60) # the desktop may show a dialog to confirm the keys
def _run(self) -> None:
try:
from jeepney import DBusAddress, MatchRule, message_bus, new_method_call
from jeepney.io.blocking import Proxy, open_dbus_connection
except ImportError:
self.error = "the jeepney package is not installed (pip install jeepney)"
self._ready.set()
return
try:
conn = open_dbus_connection(bus="SESSION")
except Exception as e: # noqa: BLE001
self.error = f"no session D-Bus ({e})"
self._ready.set()
return
portal = DBusAddress("/org/freedesktop/portal/desktop", bus_name="org.freedesktop.portal.Desktop",
interface=self.IFACE)
bus = Proxy(message_bus, conn)
sender = conn.unique_name[1:].replace(".", "_")
def request(method: str, sig: str, args: tuple, token: str):
path = f"/org/freedesktop/portal/desktop/request/{sender}/{token}"
rule = MatchRule(type="signal", interface="org.freedesktop.portal.Request", member="Response", path=path)
bus.AddMatch(rule)
with conn.filter(rule) as q:
reply = conn.send_and_get_reply(new_method_call(portal, method, sig, args), timeout=10)
if reply.header.message_type.name == "error":
raise RuntimeError(f"{method}: {reply.body}")
code, results = conn.recv_until_filtered(q, timeout=60).body
if code != 0:
raise RuntimeError(f"{method} was refused or cancelled (code {code})")
return results
try:
tok = f"summit{os.getpid()}"
res = request("CreateSession", "a{sv}", ({"handle_token": ("s", tok + "a"), "session_handle_token": ("s", tok)},), tok + "a")
session = res["session_handle"][1]
ids = {f"key{i}": (combo, fn) for i, (combo, fn) in enumerate(self.keys.items())}
shortcuts = [(sid, {"description": ("s", "Summit: save a clip" if i == 0 else f"Summit: {combo}"),
"preferred_trigger": ("s", portal_trigger(combo))})
for i, (sid, (combo, _fn)) in enumerate(ids.items())]
res = request("BindShortcuts", "oa(sa{sv})sa{sv}", (session, shortcuts, "", {"handle_token": ("s", tok + "b")}), tok + "b")
bound = {sid for sid, _ in res.get("shortcuts", ("", []))[1]}
self.got = [ids[s][0] for s in ids if s in bound]
self.taken = [ids[s][0] for s in ids if s not in bound]
except Exception as e: # noqa: BLE001
self.error = f"GlobalShortcuts portal: {e}"
self._ready.set()
return
self._ready.set()
rule = MatchRule(type="signal", interface=self.IFACE, member="Activated")
bus.AddMatch(rule)
with conn.filter(rule) as q:
while not self._stop.is_set():
try:
msg = conn.recv_until_filtered(q, timeout=0.5)
except TimeoutError:
continue
_sess, sid, *_ = msg.body
if sid in ids:
try:
ids[sid][1]()
except Exception as e: # noqa: BLE001
print(f"[keys] {ids[sid][0]}: {e}")
conn.close()
def stop(self) -> None:
self._stop.set()
if self._thread is not None and self._thread.is_alive():
self._thread.join(timeout=2)
class GlobalKeys:
"""Picks X11 or the portal for this session; `status` says what it got, in words."""
def __init__(self, keys: dict, env=os.environ) -> None:
self.keys = keys
self.kind, self.why = backend(env)
self.impl = X11Keys(keys) if self.kind == "x11" else PortalKeys(keys) if self.kind == "portal" else None
self.status = ""
def start(self) -> None:
if self.impl is None:
self.status = f"global keys unavailable: {self.why}"
else:
self.impl.start()
if self.impl.error:
self.status = f"global keys unavailable ({self.why}): {self.impl.error}"
else:
got = ", ".join(self.impl.got) or "none"
self.status = f"global keys ({self.kind}): {got}" + (f"; taken: {', '.join(self.impl.taken)}" if self.impl.taken else "")
print(f"[keys] {self.status}")
def stop(self) -> None:
if self.impl is not None:
self.impl.stop()
+6 -1
View File
@@ -443,7 +443,12 @@ class Recorder:
print(f"[replay] keeping the last {_dur(self.length)}")
if self._hotkeys_wanted:
if self.length and self._hotkeys is None:
self._hotkeys = Hotkeys({"ctrl+alt+r": lambda: self.save(), "ctrl+alt+b": lambda: self.save("compare")})
keys = {"ctrl+alt+r": lambda: self.save(), "ctrl+alt+b": lambda: self.save("compare")}
if sys.platform.startswith("linux"):
from .globalkeys import GlobalKeys # X11 key grab, or the Wayland portal
self._hotkeys = GlobalKeys(keys)
else:
self._hotkeys = Hotkeys(keys)
self._hotkeys.start()
elif not self.length and self._hotkeys is not None:
self._hotkeys.stop()
+105
View File
@@ -0,0 +1,105 @@
"""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")
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_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
@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()