The keyboard's only purpose is that a client receives symbols, so a unit
suite alone was testing the shape of a request nobody answered --
docs/TODO/scroll-has-no-compositor-proof.md is the precedent. This is
the compositor proof: two nixosTests, 16 subtests each, real time, no
injected clock.
nix build --no-link -L .#checks.x86_64-linux.vm-keyboard
test script finished in 281.06s (16/16, exit 0)
nix build --no-link -L .#checks.x86_64-linux.vm-keyboard-de
test script finished in 278.15s (16/16, exit 0)
The victim, checks/lib/keyboard_target.py, decodes every keysym from the
keymap the COMPOSITOR forwarded rather than from a table of its own.
That is the mutation rule PLAN §14 asks for: a driver that stopped
uploading leaves the client with nothing to decode with, every key
arrives as `sym=?`, and the character assertions go red. A victim with
its own keymap would decode `hello` either way and the check would be
asserting that the check can spell.
What the client actually reported, which is the point of reading back
the application's state rather than the broker's intention:
type A [(30, 1, 'A'), (30, 0, 'A')] masks [1, 1, 0, 0]
-- evdev 30 decoded as A, so the mask arrived BEFORE the
key, and no code 42 anywhere
key Return [(28, 1, 'Return'), (28, 0, 'Return')]
TTL expiry [(42, 1, 'Shift_L'), (42, 0, 'Shift_L')] masks [1,1,0,0]
-- lifted by the sweeper alone, mask cleared with it
chord depressed mask [4, 4] while Control held, still held
after the type returned
It runs TWICE because `sessions.keyboard.layout` reaches the uploaded
keymap through exactly one path -- `--xkb-layout` on the driver unit's
argv -- and one layout cannot tell that path from a hardcoded `us`:
us: symbols=pc_us_inet(evdev) bytes=35572
type y -> [(21, 1, 'y')] type z -> [(44, 1, 'z')]
type cafü -> exit 2, "scalar 3 (U+00FC) is not typeable", and the
client reported [] -- no prefix typed
de: symbols=pc_de_inet(evdev) bytes=37532
type y -> [(44, 1, 'y')] type z -> [(21, 1, 'z')] (swapped)
type cafü -> {'chars': 4, 'ok': True}
client decoded ['c', 'a', 'f', 'udiaeresis']
Hyprland's own input:kb_layout is left at `us` in BOTH runs, so a client
that ignored our keymap would decode the us answer on the de machine.
The decisive subtest is "acquire takes the KEYBOARD as well as the
cursor". With session B holding keyboard focus because its window mapped
last, acquire on A delivered wl_pointer.enter AND wl_keyboard.enter to A
and wl_keyboard.leave to B, with focus == "warp". A check that asserted
only pointer delivery would have gone green while A had the cursor, B
had the keys, and the first keystroke of the lease went to B -- which is
exactly what one warp does. §B3's "one warp" and the Stage 0 review's
"do not assert enter on acquire" are superseded by the two-warp acquire,
and the header says so.
One deviation from §B3, with reasons in the header: its subtest 4 says
`type y` decodes to sym `z`, which is wrong for a victim that decodes
from the forwarded keymap -- the same paragraph requires that. `type y`
resolves keysym y against the uploaded layout and sends that layout's
code; the client decodes it back to `y`. The sym is `y` on both layouts
by construction. What differs is the CODE, the symbols name, and whether
ü is typeable at all, and those are what this asserts.
── AND A PRE-EXISTING BUG THE FIRST RUN EXPOSED ──────────────────────
checks/lib/session-tools.nix opened a heredoc with `<<EOF` and closed it
with an INDENTED ` EOF`. A delimiter has to be at column zero, so it
never closed: it swallowed the rest of the builder -- both `install`
lines and every self-test -- into the shim's own text. The derivation
built anyway, with `hhs-ipc-watch` alone in $out/bin:
$ ls /nix/store/wy3lp3...-hhstream-session-tools/bin/
hhs-ipc-watch
So hhs-pointer-target has NEVER existed in that derivation either.
vm-pointer execs that absolute path, and vm-keyboard failed the same
way: the broker reported `target exited immediately (exit code 127)`,
which is true about a path that was never created and says nothing about
why. hhs-ipc-watch's own first line was ` #!...`, indented, which is
not a shebang, so vm-ipc is affected too. The build-time self-tests that
exist to catch exactly this had themselves become heredoc text. The
unquoted delimiter also expanded the swallowed text, so the builder ran
`hhstreamd.ipc` as a command.
The shim is a writeTextFile now -- no delimiter to indent wrong -- and
`test -x` on all three programs is the guard that would have caught it.
NOT DONE, and it needs doing: vm-pointer and vm-ipc have not been
re-run. checks/default.nix says one VM at a time on this two-core box
and I did not want to perturb the keyboard runs. That they WOULD have
failed is read off the store listing above, not off a run.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GhNPM6rGcuzxocM1nATnuM
340 lines
14 KiB
Python
340 lines
14 KiB
Python
#!/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("<I", FILL) * (size // 4))
|
|
self.buffer = self._pool.create_buffer(
|
|
0, width, height, stride, WlShm.format.xrgb8888.value
|
|
)
|
|
self.surface.attach(self.buffer, 0, 0)
|
|
self.surface.damage(0, 0, width, height)
|
|
self.surface.commit()
|
|
|
|
def _allocate(self, size: int) -> 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())
|