#!/usr/bin/env python3 """A Wayland client that says which keys it was sent, in the layout's own words. A sibling of ``pointer_target.py`` and deliberately not an extension of it: that client's contract is "report pointer events", this one's is "report keyboard events, decoded with the keymap the compositor forwarded", and the second needs a dependency (xkbcommon) and a seat capability the first does not. Two small programs read better than one with a mode switch, and the pointer checks should not start failing because the keyboard check needed a new listener. Three things it does that matter to the assertions: * **It sets ``xdg_toplevel`` app id from ``$HHSTREAM_APP_ID``**, which is what gets its window into its session's container. ``foot`` and ``wev`` ignore the environment, keep their own class, match no per-session rule and are swept into the quarantine workspace — so there would be nothing for the cursor to land in. Same reason ``pointer_target.py`` exists. * **Every keysym it prints is decoded from the keymap the compositor sent it**, over ``wl_keyboard.keymap``, compiled here with xkbcommon and updated with ``xkb_state_update_mask`` on every ``modifiers`` event. Never from a table in this file. That is the whole mutation rule for the check: keycodes that arrive with no decodable symbol are a failure, not a pass, so a driver that stopped uploading its keymap cannot leave the check green. If no keymap arrived, ``sym`` is printed as ``?`` and says so. * **It prints the raw evdev code beside the symbol, and the modifier mask beside both.** A toolkit that ignored ``wl_keyboard.modifiers`` and shifted only on ``KEY_LEFTSHIFT`` would decode a capital wrongly, so the check has to see the mask the compositor forwarded *and* the absence of a Shift keycode — the mask is how this build makes a capital, and sending both is how a capital gets shifted twice or not at all. It also binds ``wl_pointer`` and prints ``enter``/``leave`` for it. Not decoration: a cursor that arrives in a window whose keyboard focus did not follow is exactly the failure a one-warp ``acquire`` produces, and without the pointer line the check could not tell that apart from a warp that never arrived at all. Deliberately loud and deliberately unbuffered: the broker captures stdout into the session log, so ``hhstream session logs`` is the read-back, and a check that goes red says whether the window was never mapped, never focused, or focused and sent the wrong symbol. """ from __future__ import annotations import argparse import mmap import os import signal import struct import sys from pywayland.client import Display from pywayland.protocol.wayland import WlCompositor, WlSeat, WlShm from pywayland.protocol.xdg_shell import XdgWmBase from xkbcommon import xkb #: Opaque 32-bit colour. Something has to be in the buffer for the compositor #: to map the surface at all, and an unmapped surface is never focused. FILL = 0xFF2A4D6E #: Fallback size for a compositor that configures 0x0 ("you choose"). DEFAULT_SIZE = (640, 360) #: A Wayland/evdev keycode is the XKB keycode minus 8. ``wl_keyboard.key`` #: carries the evdev value; xkbcommon's tables are indexed by the XKB one. EVDEV_OFFSET = 8 #: ``wl_keyboard.key_state``. ``2`` is ``repeated`` and only reaches a version #: 10 client; it is named here so a count of presses cannot miss one. STATE_NAMES = {0: "released", 1: "pressed", 2: "repeated"} def say(line: str) -> None: """One line, flushed. The reader is a log tail.""" print(line, flush=True) class Target: def __init__(self, app_id: str, title: str) -> None: self.app_id = app_id self.title = title self.display: Display | None = None self.compositor = None self.shm = None self.wm_base = None self.seat = None self.window: _Window | None = None self.keyboard = None self.pointer = None #: The compositor's own keymap, as forwarded, and a state machine over #: it. Every `sym=` comes from here; see the module docstring. self._keymap = None self._state = None # -- setup --------------------------------------------------------- def run(self) -> int: self.display = Display() self.display.connect() registry = self.display.get_registry() registry.dispatcher["global"] = self._on_global self.display.roundtrip() missing = [ name for name, value in ( ("wl_compositor", self.compositor), ("wl_shm", self.shm), ("xdg_wm_base", self.wm_base), ("wl_seat", self.seat), ) if value is None ] if missing: say(f"target: FATAL missing globals: {', '.join(missing)}") return 1 self.wm_base.dispatcher["ping"] = lambda base, serial: base.pong(serial) self.seat.dispatcher["capabilities"] = self._on_capabilities self.window = _Window(self) self.display.roundtrip() say(f"target: app_id={self.app_id} pid={os.getpid()}") while True: # Blocking dispatch: this process exists to report events, so there # is nothing to do between them and nothing to poll for. if self.display.dispatch(block=True) < 0: say("target: display disconnected") return 1 def _on_global(self, registry, global_id: int, interface: str, version: int) -> None: if interface == WlCompositor.name: self.compositor = registry.bind(global_id, WlCompositor, min(version, 4)) elif interface == WlShm.name: self.shm = registry.bind(global_id, WlShm, 1) elif interface == XdgWmBase.name: self.wm_base = registry.bind(global_id, XdgWmBase, min(version, 2)) elif interface == WlSeat.name and self.seat is None: self.seat = registry.bind(global_id, WlSeat, min(version, 5)) def _on_capabilities(self, seat, capabilities: int) -> None: """Bind what the seat has, and say out loud what it has not. A headless seat has **no keyboard capability at all** until something creates a virtual one — there is no input device here — so "keyboard not bound" is a statement about the driver, not about this client, and a check that saw no key events needs to know which. """ say(f"target: seat capabilities={capabilities}") if capabilities & WlSeat.capability.keyboard.value and self.keyboard is None: self.keyboard = seat.get_keyboard() self.keyboard.dispatcher["keymap"] = self._on_keymap self.keyboard.dispatcher["enter"] = self._on_enter self.keyboard.dispatcher["leave"] = self._on_leave self.keyboard.dispatcher["key"] = self._on_key self.keyboard.dispatcher["modifiers"] = self._on_modifiers self.keyboard.dispatcher["repeat_info"] = self._on_repeat_info say("target: keyboard bound") elif not capabilities & WlSeat.capability.keyboard.value: say("target: seat has no keyboard capability yet") if capabilities & WlSeat.capability.pointer.value and self.pointer is None: self.pointer = seat.get_pointer() self.pointer.dispatcher["enter"] = self._on_pointer_enter self.pointer.dispatcher["leave"] = self._on_pointer_leave say("target: pointer bound") # -- keyboard ------------------------------------------------------ def _on_keymap(self, keyboard, format_: int, fd: int, size: int) -> None: """Compile what the compositor forwarded, and decode with it. The size on the wire includes the NUL terminator, so the text is everything up to the first one. A keymap that will not compile is reported rather than swallowed: it is indistinguishable, from here, from a compositor that was never given one, and the two have very different causes. """ try: with os.fdopen(fd, "rb", closefd=True) as handle: raw = handle.read(size) except OSError as exc: say(f"keyboard keymap bytes={size} UNREADABLE {exc}") return text = raw.split(b"\0", 1)[0].decode("utf-8", "replace") symbols = next( (line.strip() for line in text.splitlines() if "xkb_symbols" in line), "?" ) try: self._keymap = xkb.Context().keymap_new_from_string(text) self._state = self._keymap.state_new() except Exception as exc: say(f"keyboard keymap bytes={size} WILL-NOT-COMPILE {exc}") return # `symbols=` is the line the check greps to prove *which* layout was # uploaded: `pc_us_inet(evdev)` against `pc_de_inet(evdev)`. say(f"keyboard keymap format={format_} bytes={size} symbols={symbols}") def _sym(self, code: int) -> str: """The keysym name for an evdev code, under the forwarded keymap.""" if self._state is None: # `?` and not a guess: the check treats a key with no symbol as a # failure, which is what makes "the keymap was uploaded" an # assertion rather than an assumption. return "?" return xkb.keysym_get_name(self._state.key_get_one_sym(code + EVDEV_OFFSET)) def _on_enter(self, keyboard, serial, surface, keys) -> None: held = list(keys) if keys else [] say(f"keyboard enter serial={serial} keys={held}") def _on_leave(self, keyboard, serial, surface) -> None: say(f"keyboard leave serial={serial}") def _on_key(self, keyboard, serial, time_, key: int, state: int) -> None: say( f"keyboard key code={key} state={state}" f" ({STATE_NAMES.get(state, 'unknown')}) sym={self._sym(key)}" ) def _on_modifiers(self, keyboard, serial, depressed, latched, locked, group) -> None: if self._state is not None: # The mask first, then the sym lookup above is the one a real # client does: `A` is only `A` because Shift is in this mask. self._state.update_mask(depressed, latched, locked, 0, 0, group) say( f"keyboard modifiers depressed={depressed} latched={latched}" f" locked={locked} group={group}" ) def _on_repeat_info(self, keyboard, rate: int, delay: int) -> None: say(f"keyboard repeat_info rate={rate} delay={delay}") # -- pointer, for telling two failures apart ------------------------ def _on_pointer_enter(self, pointer, serial, surface, x, y) -> None: say(f"pointer enter x={x:.2f} y={y:.2f}") def _on_pointer_leave(self, pointer, serial, surface) -> None: say("pointer leave") class _Window: """One toplevel: a surface, its xdg wrapper, and an shm buffer.""" def __init__(self, target: Target) -> None: self.target = target self.size = DEFAULT_SIZE self.buffer = None self._pool = None self._map: mmap.mmap | None = None self.surface = target.compositor.create_surface() self.xdg_surface = target.wm_base.get_xdg_surface(self.surface) self.xdg_surface.dispatcher["configure"] = self._on_configure self.toplevel = self.xdg_surface.get_toplevel() # The whole reason this program exists rather than `wev`. self.toplevel.set_app_id(target.app_id) self.toplevel.set_title(target.title) self.toplevel.dispatcher["configure"] = self._on_toplevel_configure self.toplevel.dispatcher["close"] = lambda *_: sys.exit(0) self.surface.commit() def _on_toplevel_configure(self, toplevel, width, height, states) -> None: if width and height: self.size = (width, height) def _on_configure(self, xdg_surface, serial) -> None: xdg_surface.ack_configure(serial) self._paint() say(f"target: window configured {self.size[0]}x{self.size[1]}") def _paint(self) -> None: width, height = self.size stride = width * 4 size = stride * height if self._map is None or self._map.size() < size: self._allocate(size) # A flat fill, written once per resize: the pixels are not the subject # of any assertion, they only make the surface mappable. self._map.seek(0) self._map.write(struct.pack(" None: fd = os.memfd_create("hhs-keyboard-target", 0) os.ftruncate(fd, size) self._map = mmap.mmap(fd, size) self._pool = self.target.shm.create_pool(fd, size) os.close(fd) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="hhs-keyboard-target", description="A Wayland window that reports the key events it receives, " "decoded with the keymap the compositor forwarded.", ) parser.add_argument( "--app-id", default=None, help="xdg_toplevel app id; the default is $HHSTREAM_APP_ID, which is how " "a session's window rule finds its container", ) parser.add_argument("--title", default="hhs-keyboard-target") args = parser.parse_args(argv) app_id = args.app_id or os.environ.get("HHSTREAM_APP_ID") if not app_id: print( "hhs-keyboard-target: no --app-id and no $HHSTREAM_APP_ID; refusing to " "guess, because the app id is the whole point of this program", file=sys.stderr, ) return 2 # The broker kills the process group; exit on the first signal rather than # leaving the compositor to notice a dead client. signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) signal.signal(signal.SIGINT, lambda *_: sys.exit(0)) return Target(app_id, args.title).run() if __name__ == "__main__": sys.exit(main())