- Splash: Summit's icon rises in over an amber glow, the name follows, then it fades into the app (about a second, no keys taken, off when motion is off) - install.sh: after installing icons, rebuild KDE's sycoca and send KIconLoader.iconChanged so a running Plasma shows the updated icon - New app icon (SVG + rendered PNG sizes, render.sh), used by the packages and the engine's window - Lutris scan, consoles (Remote Play via chiaki-ng frame tap, capture cards), Steam account switching, running-game tracking, window mode, artwork - Library UI: add dialog, profile editor, accounts, "now playing" screen - Engine: in-game overlay/HUD, overlay key, global key fixes Co-Authored-By: Claude Opus 5.5 <[email protected]>
431 lines
21 KiB
Python
431 lines
21 KiB
Python
"""System-wide keys on Linux: the save-a-clip key and the overlay's key work 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.
|
|
Summit registers itself as the host app "summit" first (org.freedesktop.host.portal.Registry): without
|
|
an app id the portal refuses ("An app id is required", seen on Plasma 6.8). The desktop may ask the user
|
|
to confirm the key, and may give a different one. If the portal can't be had and XWayland is there
|
|
(DISPLAY set), the X11 grab below is used through XWayland: it fires while an XWayland window (most
|
|
games: Proton, Wine, older native ones) has the keyboard.
|
|
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().
|
|
|
|
The overlay (framegen/menu.py) over a game uses X11Keys directly, on X11 and through XWayland: its key may be a key
|
|
on its own (Insert), which only an X grab takes without asking, and while the overlay is open X11Keys.set_modal takes
|
|
the whole keyboard, so the arrows, Enter and Esc move about in the overlay instead of reaching the game. The game
|
|
gets its keys back the moment the overlay closes.
|
|
"""
|
|
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
|
|
MODAL_S = 2.0 # X11Keys.set_modal: the keyboard goes back to the game if the overlay hasn't asked again for this long
|
|
|
|
|
|
# Key names as written (lower case) -> X keysym names, where they differ from the lower-case name itself
|
|
KEYSYMS = {"insert": "Insert", "ins": "Insert", "home": "Home", "end": "End", "delete": "Delete", "del": "Delete",
|
|
"pageup": "Prior", "prior": "Prior", "pagedown": "Next", "next": "Next", "pause": "Pause",
|
|
"scrolllock": "Scroll_Lock", "scroll_lock": "Scroll_Lock", "tab": "Tab", "space": "space",
|
|
"esc": "Escape", "escape": "Escape", "enter": "Return", "return": "Return", "backspace": "BackSpace",
|
|
"up": "Up", "down": "Down", "left": "Left", "right": "Right"}
|
|
KEYSYMS |= {f"f{n}": f"F{n}" for n in range(1, 25)}
|
|
# The overlay's keys (X keysym names), taken one by one while it's open when the whole keyboard can't be
|
|
NAV_KEYS = ("Up", "Down", "Left", "Right", "Return", "KP_Enter", "Escape", "BackSpace", "Tab", "Prior", "Next")
|
|
|
|
|
|
def parse(combo: str, bare: bool = False) -> 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) unless `bare` allows that (the overlay's key)."""
|
|
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 = KEYSYMS.get(p, p)
|
|
else:
|
|
raise ValueError(f"{combo!r}: more than one key")
|
|
if key is None:
|
|
raise ValueError(f"{combo!r}: no key")
|
|
if not bare and 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.
|
|
|
|
bare: a key on its own may be grabbed too (the overlay's key: Insert, Home). set_modal(True, fn): from then
|
|
until set_modal(False) every key goes here instead of to the game, and fn(name, shift) gets each press that
|
|
isn't one of `keys` (name: the X keysym name in lower case: "up", "return", "escape", "tab"). `modal` says how
|
|
that went: "keyboard" (the whole keyboard), "keys" (another program holds the keyboard, so only NAV_KEYS were
|
|
taken) or "" (off). The overlay asks again every time round its loop while it's open; if it stops asking for
|
|
MODAL_S (the video loop stalled), the keyboard goes back to the game by itself."""
|
|
|
|
def __init__(self, keys: dict, display: str | None = None, bare: bool = False) -> None:
|
|
self.keys, self.name, self.bare = keys, display or os.environ.get("DISPLAY", ":0"), bare
|
|
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
|
|
self.modal = ""
|
|
self._modal_want, self._modal_fn, self._modal_asked = False, None, 0.0
|
|
self._wake = os.pipe() # set_modal and stop wake the thread through it
|
|
|
|
def start(self) -> None:
|
|
self._thread = threading.Thread(target=self._run, name="globalkeys-x11", daemon=True)
|
|
self._thread.start()
|
|
self._ready.wait(5)
|
|
|
|
def set_modal(self, on: bool, fn=None) -> None:
|
|
"""Takes the keyboard for the overlay, or gives it back (any thread; done on the key thread, at once).
|
|
While it's on, call it again at least every MODAL_S."""
|
|
self._modal_fn = fn if on else self._modal_fn
|
|
self._modal_asked = time.monotonic()
|
|
if on != self._modal_want or on != bool(self.modal):
|
|
self._modal_want = on
|
|
self._poke()
|
|
|
|
def _poke(self) -> None:
|
|
try:
|
|
os.write(self._wake[1], b"x")
|
|
except OSError:
|
|
pass
|
|
|
|
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.XKeysymToString.restype, x.XKeysymToString.argtypes = c_char_p, [c_ulong]
|
|
x.XLookupKeysym.restype, x.XLookupKeysym.argtypes = c_ulong, [POINTER(_XKeyEvent), c_int]
|
|
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.XGrabKeyboard.restype, x.XGrabKeyboard.argtypes = c_int, [c_void_p, c_ulong, c_int, c_int, c_int, c_ulong]
|
|
x.XUngrabKeyboard.argtypes = [c_void_p, c_ulong]
|
|
x.XSync.argtypes = [c_void_p, c_int]
|
|
x.XFlush.argtypes = [c_void_p]
|
|
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)
|
|
x.XSetErrorHandler(_ERROR_HANDLER)
|
|
fns: dict[tuple[int, int], tuple[str, object]] = {}
|
|
for combo, fn in self.keys.items():
|
|
try:
|
|
mods, key = parse(combo, self.bare)
|
|
except ValueError as e:
|
|
print(f"[keys] {e}")
|
|
continue
|
|
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_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")
|
|
continue
|
|
fns[(code, mods)] = (combo, fn)
|
|
self.got.append(combo)
|
|
self._ready.set()
|
|
nav: list[int] = [] # modal "keys": the keycodes taken one by one
|
|
|
|
def modal(on: bool) -> None:
|
|
if on and not self.modal:
|
|
# owner_events off, both async, CurrentTime: every key comes here until it's let go of
|
|
if x.XGrabKeyboard(d, root, 0, 1, 1, 0) == 0:
|
|
self.modal = "keyboard"
|
|
else: # a game or another program holds the keyboard: the overlay's own keys, one by one
|
|
for name in NAV_KEYS:
|
|
code = x.XKeysymToKeycode(d, x.XStringToKeysym(name.encode()))
|
|
if code and not any(code == c for c, _ in fns):
|
|
for extra in IGNORED:
|
|
x.XGrabKey(d, code, extra, root, 1, 1, 1)
|
|
x.XGrabKey(d, code, extra | SHIFT, root, 1, 1, 1)
|
|
nav.append(code)
|
|
self.modal = "keys"
|
|
elif not on and self.modal:
|
|
if self.modal == "keyboard":
|
|
x.XUngrabKeyboard(d, 0)
|
|
for code in nav:
|
|
for extra in IGNORED:
|
|
x.XUngrabKey(d, code, extra, root)
|
|
x.XUngrabKey(d, code, extra | SHIFT, root)
|
|
nav.clear()
|
|
self.modal = ""
|
|
x.XSync(d, 0)
|
|
|
|
fd = x.XConnectionNumber(d)
|
|
ev, last = _XEvent(), {}
|
|
try:
|
|
while not self._stop.is_set():
|
|
if self._modal_want and time.monotonic() - self._modal_asked > MODAL_S:
|
|
self._modal_want = False # nobody is looking after the overlay: the game gets its keys back
|
|
print("[keys] the overlay stopped answering: the keyboard is the game's again")
|
|
if self._modal_want != bool(self.modal):
|
|
modal(self._modal_want)
|
|
elif self.modal == "keys" and x.XGrabKeyboard(d, root, 0, 1, 1, 0) == 0:
|
|
for code in nav: # whoever held the keyboard let go: all of it now, as usual
|
|
for extra in IGNORED:
|
|
x.XUngrabKey(d, code, extra, root)
|
|
x.XUngrabKey(d, code, extra | SHIFT, root)
|
|
nav.clear()
|
|
self.modal = "keyboard"
|
|
if not x.XPending(d):
|
|
ready = select.select([fd, self._wake[0]], [], [], 0.25)[0]
|
|
if self._wake[0] in ready:
|
|
os.read(self._wake[0], 64)
|
|
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)
|
|
try:
|
|
if hit is None:
|
|
if self.modal and self._modal_fn is not None:
|
|
name = x.XKeysymToString(x.XLookupKeysym(byref(ev.xkey), 0))
|
|
if name:
|
|
self._modal_fn(name.decode().lower(), bool(ev.xkey.state & SHIFT))
|
|
continue
|
|
now = time.monotonic()
|
|
if now - last.get(k, 0) < REPEAT_S:
|
|
last[k] = now
|
|
continue
|
|
last[k] = now
|
|
hit[1]()
|
|
except Exception as e: # noqa: BLE001 - a failing save must not end the key thread
|
|
print(f"[keys] {hit[0] if hit else 'overlay'}: {e}")
|
|
finally:
|
|
modal(False)
|
|
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()
|
|
self._poke()
|
|
if self._thread is not None and self._thread.is_alive():
|
|
self._thread.join(timeout=2)
|
|
|
|
|
|
APP_ID = "summit" # matches packaging/summit.desktop
|
|
|
|
|
|
def register_host_app(conn, app_id: str = APP_ID) -> str | None:
|
|
"""Tells xdg-desktop-portal (1.19 and newer) which app this connection is: portals that need an app id
|
|
(GlobalShortcuts) refuse a host program without one. Returns why it couldn't, or None. Must come before any
|
|
other portal call on `conn`."""
|
|
from jeepney import DBusAddress, new_method_call
|
|
reg = DBusAddress("/org/freedesktop/portal/desktop", bus_name="org.freedesktop.portal.Desktop",
|
|
interface="org.freedesktop.host.portal.Registry")
|
|
try:
|
|
reply = conn.send_and_get_reply(new_method_call(reg, "Register", "sa{sv}", (app_id, {})), timeout=5)
|
|
except Exception as e: # noqa: BLE001
|
|
return str(e)
|
|
if reply.header.message_type.name == "error":
|
|
return str(reply.body)
|
|
return None
|
|
|
|
|
|
class PortalKeys:
|
|
"""xdg-desktop-portal GlobalShortcuts over D-Bus with jeepney (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(".", "_")
|
|
register_host_app(conn)
|
|
|
|
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, self.env = keys, env
|
|
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 and self.kind == "portal" and self.env.get("DISPLAY"):
|
|
print(f"[keys] GlobalShortcuts portal: {self.impl.error}; using an XWayland key grab instead "
|
|
"(it works while an XWayland window, most games, has the keyboard)")
|
|
self.kind, self.why = "xwayland", "Wayland session: X11 key grab through XWayland"
|
|
self.impl = X11Keys(self.keys, self.env.get("DISPLAY"))
|
|
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()
|