Files
HermenixandClaude Opus 5 b1f2744cf0 Stage 0 review: correct what the log does not say, and edit the plan
The Stage 0 review (docs/reviews/2026-10-04-stage0-review.md, verdict
yes-with-fixes) found that the measurements were sound and the write-up
was not. All four of its high and medium defects, verified against the
committed transcript before fixing:

(1) 19e484b's README claimed a verbatim excerpt and printed serial=336
    while the run's (a2) enter was serial 371. It also claimed six
    reproductions with one transcript, and cited a `keys=[42, 0, 0, 0]`
    enter from a run whose log was never kept -- every enter in the
    committed file is `keys=[]`. The excerpt is now copied from the log
    with line numbers to check it against, the reproduction claim is
    gone, and the Shift observation is named as not-in-this-log.

(2) THE (a) CONCLUSION WAS WRONG, and it is the one that matters. The
    first idle warp onto the unfocused window gave wl_pointer.enter and
    NO keyboard enter; the leave/enter arrived on the LATER motion. So
    it is not "enter, one warp late" -- the first warp's delta is set to
    0, the threshold is 0.0, and the second motion's own non-zero delta
    is what focused. Two corollaries the old text got backwards: a
    second warp to the SAME point returns before mouseMoveUnified
    touches the delta and proves nothing, and waiting longer does not
    help. The probe now prints both targets and the measured gap
    (0.401s) instead of hardcoding the word "immediately", and its
    ANSWER string says the mechanism.

    Consequence, now stated everywhere it belongs: `pointer acquire` is
    one warp, so the first key of a lease can land on whatever was
    already focused. Stage 3's enter subtest must not be designed from
    acquire's single warp, and must not be made to pass by warping twice
    to the same bookmark.

(3) d07a1fd did not edit the plan -- `git diff 14b3f69 HEAD --
    docs/plans/2026-10-03-keyboard-input.md` was empty, so anyone told
    to follow the plan still had the contradicted text. All eight
    pre-code changes are now folded into that file, each marked
    [SUPERSEDED], plus a banner at the top. Changes 5 and 7 were the
    ones that had survived intact in four places: the [keyboard] TOML
    table (dropped -- the broker reads that file and the driver is a
    different unit, so it would have been a setting with no effect) and
    "if it repeats, the help text says so" (now unconditional). The four
    closed open questions and the stage table are updated with what
    Stage 0 measured, including that Stage 4 is no longer contingent.

(4) mask_cleared=no was reported as a held mask surviving destroy. The
    held key was a letter, so the mask was 0 throughout; the README now
    says destroy emitted no key-up and no modifiers event, and that the
    reason release_all still sends modifiers(0,0,0,0) is
    VirtualKeyboard.cpp's releasePressed, not this line. The real
    poison evidence is promoted: onKeyboardKey drops a release whose
    code is not in m_pressed, so the cleanup's `key code=30 state=0`
    arriving from a brand-new keyboard proves 30 was still in that set.

The transcript is a fresh run of the corrected probe, so the file and
the claims about it agree line for line.

19e484b's message carries defect (2)'s wrong causality. It is corrected
here rather than by rewriting that commit, so the hashes the reviewer
cites keep resolving.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GhNPM6rGcuzxocM1nATnuM
2026-10-04 03:46:53 +00:00

1071 lines
44 KiB
Python

#!/usr/bin/env python3
"""Measure the keyboard behaviours neither plan would let Stage 1 guess at.
`docs/plans/2026-10-03-keyboard-input.md` §6 lists four open questions about
the *running* compositor; `docs/plans/2026-10-04-keyboard-verification.md` §B1
turns them into a script with expectations and a list of false passes. This is
that script. It prints what it saw, not what it hoped for.
1. Is the global really `zwp_virtual_keyboard_manager_v1`, at version 1?
Anything else stops the project. Exits 2 if so.
(a1) One warp, after the cursor has been still for longer than Hyprland's
0.5 s window — does the aimed window get `wl_keyboard.enter`?
(a2) A second warp immediately after — does it then?
(b) `destroy` with a key still down: is the key released? Is the modifier
mask cleared?
(c) Is one held key one `wl_keyboard.key`, with `repeat_info` still sent?
(a1) and (a2) are separate questions on purpose, and (a2) is not a repeat of
(a1). `InputManager::onMouseWarp` calls `mouseMoveUnified(refocus=false)`;
with `follow_mouse = 1`, keyboard focus needs
`m_mousePosDelta > follow_mouse_threshold`, that threshold is 0 by default, and
the delta is *set to* 0 when the previous cursor movement was more than 0.5 s
ago. So an idle warp is expected to move the cursor and not keyboard focus,
and a following motion that changes the floored pixel inside 0.5 s is expected
to focus.
Two things follow, and both are printed rather than assumed:
* **(a2) must land on a different pixel.** `mouseMoveUnified` returns before
it touches the delta when the floored position did not change, so a second
`motion_absolute` to the *same* point proves nothing. (a2) offsets by about
3 px and the report prints both normalised points.
* **The gap between them is a measurement, not the word "immediately".** It
has to stay under 0.5 s for (a2) to be the in-window case, so the report
prints the monotonic gap it achieved.
A probe that collapsed the two into one yes/no would hide exactly what the
lease's `acquire` does: *one* warp, and then a key.
It talks to the compositor and to nothing else: **no broker, no lease, no
`hhstreamd` socket, no `hhstream` CLI**. Read-only `hyprctl` is used to learn
where the windows actually are and what the relevant options are set to;
`hyprctl dispatch` is *not* used, because `dispatch focuswindow` would answer
(a) by cheating.
Two windows, `kb-probe-a` and `kb-probe-b`, because a one-window probe is the
review's first listed false pass: a single mapped window is focused at map
time, so it prints `enter` and proves nothing about the warp. The first is
made fullscreen, which on the deployment machine is the only way to get two
windows that do not cover each other exactly — its catch-all rule is `float
on, size 1040 560, center on`, so two ordinary windows would be the same box
in the same place and no warp could tell them apart. The probe prints both
boxes it read from `hyprctl clients -j` and the point it chose between them.
Every key event is decoded with **the keymap the compositor forwarded**, not
with a table in this file: that is what makes the symbols evidence that our
upload arrived rather than evidence that we can spell.
Throwaway on purpose. It generates the protocol bindings into a temporary
directory with pywayland's scanner instead of importing a vendored module, so
it ran before any of Stage 1 existed. The seeding trick is the one
`hhstream_pointer._protocol.regenerate` documents: the scanner builds its
import map only from the files it was handed, so `wl_seat` has to be put there
by hand.
How to run it, and what it answered, is in `tests/README-keyboard-probe.md`.
"""
from __future__ import annotations
import argparse
import importlib
import json
import mmap
import os
import pathlib
import select
import struct
import subprocess
import sys
import tempfile
import time
from pywayland.client import Display
from pywayland.protocol.wayland import WlCompositor, WlOutput, WlSeat, WlShm
from pywayland.protocol.xdg_shell import XdgWmBase
#: The only copy of this XML on the machine is in `pkgs.hyprland.src`. It is
#: *not* where either plan says it is: wayland-protocols 1.49 (this flake's
#: nixpkgs) has no `unstable/virtual-keyboard/` at all, and neither
#: `pkgs.wlr-protocols` nor `pkgs.wlroots.src` carries it. Find it with:
#:
#: echo "$(nix eval --raw nixpkgs#hyprland.src)/protocols"
XML_NAME = "virtual-keyboard-unstable-v1.xml"
#: `zwp_virtual_keyboard_manager_v1` is version 1 and only version 1. Anything
#: else is the gate the plan says stops the project.
WANTED_MANAGER_VERSION = 1
#: `wl_keyboard.keymap_format.xkb_v1`. Spelled out because the XML this is
#: generated from *names* `keymap_format` in prose and never defines it, so the
#: generated module carries no enum to read it from.
XKB_FORMAT_TEXT_V1 = 1
#: `wl_keyboard.key_state`. Same integers as `hhstream_pointer.buttons.STATES`
#: and, like the format above, documented-but-undefined in this XML. `2` is
#: `repeated`, which only a `wl_keyboard` version 10 client ever receives and
#: which `zwp_virtual_keyboard_v1` cannot send.
RELEASED, PRESSED, REPEATED = 0, 1, 2
#: evdev codes, readable against `linux/input-event-codes.h`. The XKB keycode
#: is 8 higher; that offset is applied only where a *keysym* is wanted.
KEY_A = 30 # KEY_A
EVDEV_OFFSET = 8
#: Opaque fill, as in `checks/lib/pointer_target.py`: a surface with no content
#: is never mapped, and an unmapped surface is never focused.
FILL = 0xFF205070
#: Coordinates on the wire are the output's own 0..1 frame scaled by a fixed
#: extent — `hhstream_pointer.backend.EXTENT`, repeated rather than imported
#: because the probe measures the driver's behaviour, not its code.
EXTENT = 0xFFFF
#: Fallback size for a compositor that configures 0x0 ("you choose").
DEFAULT_SIZE = (640, 360)
#: Longer than Hyprland's 0.5 s `m_mousePosDelta` window, so (a1) really is the
#: idle case it claims to be.
IDLE_S = 0.8
#: Longer than the default `repeat_delay` of 600 ms, so (c) would see a repeat
#: if there were one.
REPEAT_HOLD_S = 1.5
#: After a warp. Generous: a missed event on a software-rendered two-core box
#: would be read as a NO.
SETTLE_S = 0.4
#: How far (a2) moves, as a fraction of the output's height. About 3 px on a
#: 720-line output, which is what makes the floored pixel change —
#: `mouseMoveUnified` returns early otherwise and never touches the delta
#: keyboard focus is compared against.
A2_OFFSET = 0.004
APP_A, APP_B = "kb-probe-a", "kb-probe-b"
#: Hyprland options the answers depend on, printed so a reader never has to
#: take this script's word for the configuration it measured.
OPTIONS = (
"input:follow_mouse",
"input:follow_mouse_threshold",
"input:virtualkeyboard:release_pressed_on_close",
"input:repeat_rate",
"input:repeat_delay",
"input:kb_layout",
)
def say(line: str = "") -> None:
"""One line, flushed: the output is a report, read as it is produced."""
print(line, flush=True)
# --------------------------------------------------------------------------
# protocol bindings, generated into a temporary directory
# --------------------------------------------------------------------------
def load_virtual_keyboard(xml: pathlib.Path):
"""Generate and import `virtual_keyboard_unstable_v1` from `xml`.
The generated file asks its *sibling* for the core interfaces (`from
..wayland import WlSeat`), so a shim is written beside it that re-exports
pywayland's own class — two Python classes for one Wayland interface would
each register a `wl_interface` and the registry would bind the wrong one.
"""
from pywayland.protocol import wayland as core
from pywayland.scanner.protocol import Protocol
protocol = Protocol.parse_file(str(xml))
name = protocol.name.replace("-", "_")
root = pathlib.Path(tempfile.mkdtemp(prefix="hhs-probe-")) / "_probe_protocol"
root.mkdir()
(root / "__init__.py").write_text("")
(root / "wayland.py").write_text(
"from pywayland.protocol.wayland import WlSeat # noqa: F401\n"
)
core_dir = pathlib.Path(core.__file__).parent
imports = {path.stem: "wayland" for path in core_dir.glob("wl_*.py")}
imports.update({interface.name: name for interface in protocol.interface})
protocol.output(str(root), imports)
sys.path.insert(0, str(root.parent))
return importlib.import_module(f"_probe_protocol.{name}")
def find_xml(explicit: pathlib.Path | None) -> pathlib.Path:
"""`--xml`, else `$HHSTREAM_PROTOCOL_DIR`, else give up loudly."""
if explicit is not None:
return explicit
root = pathlib.Path(os.environ.get("HHSTREAM_PROTOCOL_DIR", ""))
candidate = root / XML_NAME
if candidate.is_file():
return candidate
raise SystemExit(
f"keyboard-probe: cannot find {XML_NAME}. Pass --xml, or set "
'$HHSTREAM_PROTOCOL_DIR to "$(nix eval --raw nixpkgs#hyprland.src)/protocols".'
)
# --------------------------------------------------------------------------
# read-only compositor IPC
# --------------------------------------------------------------------------
def hyprctl(*args: str) -> str | None:
"""One read-only `hyprctl` call, or `None` if it is not usable.
Allowed by the review's §B1 so the warp hits a known box. `dispatch` is
deliberately never passed here: there is one call site and it takes the
query words, so a reader can see the whole of what this probe asks for.
"""
try:
done = subprocess.run(
["hyprctl", "-i", "0", *args],
capture_output=True,
text=True,
timeout=5,
check=False,
)
except (OSError, subprocess.SubprocessError) as exc:
say(f" hyprctl {' '.join(args)}: unavailable ({exc})")
return None
if done.returncode != 0:
say(f" hyprctl {' '.join(args)}: exit {done.returncode} {done.stderr.strip()}")
return None
return done.stdout
def report_options() -> None:
say(" options this measurement depends on:")
for option in OPTIONS:
raw = hyprctl("getoption", option, "-j")
if raw is None:
continue
try:
value = json.loads(raw)
except ValueError:
say(f" {option} = <unparseable: {raw.strip()!r}>")
continue
# Printed whole, including the zeros: `follow_mouse_threshold = 0` is
# the value (a) turns on, and a filter that hid falsy fields would hide
# exactly the number the reader came for.
say(f" {option} = {json.dumps(value, sort_keys=True)}")
def boxes() -> dict[str, tuple[int, int, int, int]]:
"""`app-id -> (x, y, w, h)` for our own windows, from `hyprctl clients`."""
raw = hyprctl("clients", "-j")
if raw is None:
return {}
try:
clients = json.loads(raw)
except ValueError:
return {}
found = {}
for client in clients:
app_id = client.get("initialClass") or client.get("class")
if app_id in (APP_A, APP_B):
x, y = client.get("at", [0, 0])
w, h = client.get("size", [0, 0])
found[app_id] = (x, y, w, h)
return found
def pick_point(
target: tuple[int, int, int, int],
avoid: tuple[int, int, int, int] | None,
monitor: tuple[int, int],
) -> tuple[float, float] | None:
"""A normalised point inside `target` and outside `avoid`.
Returns `None` when there is no such point, which is a real outcome and not
a bug: with this machine's catch-all rule two ordinary windows are the same
box, and a probe that warped anyway would be measuring nothing.
"""
tx, ty, tw, th = target
width, height = monitor
candidates = []
for fx in (0.01, 0.05, 0.5, 0.95, 0.99):
for fy in (0.01, 0.05, 0.5, 0.95, 0.99):
candidates.append((tx + tw * fx, ty + th * fy))
for px, py in candidates:
if avoid is not None:
ax, ay, aw, ah = avoid
if ax <= px <= ax + aw and ay <= py <= ay + ah:
continue
if not (0 <= px < width and 0 <= py < height):
continue
return (px / width, py / height)
return None
# --------------------------------------------------------------------------
# the keymap we upload
# --------------------------------------------------------------------------
def keymap_text(layout: str, model: str) -> str:
"""A keymap for `layout`, compiled rather than written out by hand.
xkbcommon because an uploaded keymap that does not compile is
indistinguishable, from the client side, from a compositor that ignored the
upload — and because this is the library Stage 1's `keymap.py` uses, so a
failure here is a failure that matters.
"""
from xkbcommon import xkb
keymap = xkb.Context().keymap_new_from_names(
rules="evdev", model=model, layout=layout, variant="", options=""
)
return keymap.get_as_bytes().decode("utf-8")
def keymap_fd(text: str) -> tuple[int, int]:
"""A memfd holding `text` **NUL-terminated**, and its size including the NUL.
The terminator is load-bearing and is the review's change 2: Hyprland
`mmap`s exactly `size` bytes and hands the pointer to
`xkb_keymap_new_from_string`, which wants a C string, so a size that
excludes the NUL reads off the end of the mapping.
"""
payload = text.encode("utf-8") + b"\0"
fd = os.memfd_create("hhs-probe-keymap", 0)
os.ftruncate(fd, len(payload))
with os.fdopen(os.dup(fd), "wb", closefd=True) as handle:
handle.write(payload)
return fd, len(payload)
# --------------------------------------------------------------------------
# the probe
# --------------------------------------------------------------------------
class Probe:
def __init__(self, vk_module, *, layout: str, model: str, output_name: str | None) -> None:
self.vk = vk_module
self.layout = layout
self.model = model
self.output_name = output_name
self.display: Display | None = None
self.compositor = None
self.shm = None
self.wm_base = None
self.seat = None
self.vk_manager = None
self.vk_manager_version = 0
self.vp_manager: tuple | None = None
self.vp_manager_version = 0
#: registry id -> [proxy, name-or-None, (width, height)]
self.outputs: dict[int, list] = {}
self.globals: list[tuple[str, int]] = []
self.keyboard = None
self.pointer = None
self.windows: list[_Window] = []
self.virtual_pointer = None
self.virtual_keyboards: list = []
#: The compositor's own keymap, as forwarded over `wl_keyboard.keymap`,
#: and a state machine over it. Every `sym=` in the log comes from
#: here, which is the review's rule for the keymap-upload assertion.
self._keymap = None
self._state = None
self._mask = (0, 0, 0, 0)
#: Observations. A list rather than counters: the order of a `leave`
#: and an `enter` is part of the answer to (a).
self.events: list[str] = []
#: The app id that currently holds keyboard focus, `"other"` for a
#: window that is not ours, `None` for nothing.
self.focus: str | None = None
self.repeat_info: tuple[int, int] | None = None
# -- lifecycle -----------------------------------------------------
def connect(self, runtime_dir: pathlib.Path) -> None:
names = sorted(
p.name
for p in runtime_dir.iterdir()
if p.name.startswith("wayland-") and not p.name.endswith(".lock")
)
if len(names) != 1:
# `backend.find_wayland_display` refuses the same way: guessing
# which of two compositors to drive is a coin flip.
raise SystemExit(
f"keyboard-probe: expected one wayland-* socket in {runtime_dir}, "
f"found {names or 'none'}"
)
os.environ["XDG_RUNTIME_DIR"] = str(runtime_dir)
self.display = Display(names[0])
self.display.connect()
registry = self.display.get_registry()
registry.dispatcher["global"] = self._on_global
# Twice: the first trip delivers the globals, the second the `name` and
# `mode` events the bound outputs emit.
self.display.roundtrip()
self.display.roundtrip()
def close(self) -> None:
if self.display is not None:
self.display.disconnect()
self.display = None
def _on_global(self, registry, global_id: int, interface: str, version: int) -> None:
self.globals.append((interface, version))
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))
self.wm_base.dispatcher["ping"] = lambda base, serial: base.pong(serial)
elif interface == WlSeat.name and self.seat is None:
self.seat = registry.bind(global_id, WlSeat, min(version, 5))
self.seat.dispatcher["capabilities"] = lambda _s, caps: self.events.append(
f"seat capabilities={caps}"
)
elif interface == WlOutput.name:
entry = [registry.bind(global_id, WlOutput, min(version, 4)), None, (0, 0)]
entry[0].dispatcher["name"] = lambda _p, name, e=entry: e.__setitem__(1, name)
entry[0].dispatcher["mode"] = (
lambda _p, flags, w, h, refresh, e=entry: e.__setitem__(2, (w, h))
)
self.outputs[global_id] = entry
elif interface == self.vk.ZwpVirtualKeyboardManagerV1.name:
self.vk_manager_version = version
self.vk_manager = registry.bind(
global_id, self.vk.ZwpVirtualKeyboardManagerV1, WANTED_MANAGER_VERSION
)
elif interface == "zwlr_virtual_pointer_manager_v1":
# Kept as (registry, id) and bound later: the class comes from the
# driver's vendored package, and importing it needs a `sys.path`
# edit that a registry callback should not be doing.
self.vp_manager_version = version
self.vp_manager = (registry, global_id)
# -- event pump ----------------------------------------------------
def pump(self, seconds: float) -> None:
"""Dispatch for `seconds`, then return. Never raises on a timeout.
A `roundtrip()` is not enough for any of these questions: each one is a
*negative* as well as a positive — no `enter`, no release, no repeat —
so the probe has to wait out a real interval and report what did not
arrive.
"""
assert self.display is not None
deadline = time.monotonic() + seconds
while True:
self.display.flush()
remaining = deadline - time.monotonic()
if remaining <= 0:
return
readable, _, _ = select.select([self.display.get_fd()], [], [], remaining)
if not readable:
return
self.display.read()
if self.display.dispatch(block=False) < 0:
raise SystemExit("keyboard-probe: the compositor closed the connection")
# -- setup steps ---------------------------------------------------
def output(self):
"""The output to bind the virtual pointer to: proxy, name, and mode.
Named rather than implicit for the same reason `backend.py` resolves by
name: warp coordinates are output-local, so a pointer bound to the
wrong output aims somewhere else entirely.
"""
named = {entry[1]: entry for entry in self.outputs.values() if entry[1]}
if self.output_name:
if self.output_name not in named:
raise SystemExit(
f"keyboard-probe: no output named {self.output_name!r} "
f"(known: {', '.join(sorted(named)) or 'none'})"
)
chosen = self.output_name
elif len(named) != 1:
raise SystemExit(
f"keyboard-probe: {len(named)} outputs ({', '.join(sorted(named))}); "
"pass --output to say which"
)
else:
chosen = next(iter(named))
entry = named[chosen]
return entry[0], chosen, entry[2]
def bind_keyboard(self) -> None:
"""Bind `wl_keyboard` and wire every event we measure.
Bound *after* a virtual keyboard exists: this seat has no physical
keyboard (the headless unit sets `WLR_LIBINPUT_NO_DEVICES=1`, and
`hyprctl devices` lists none), so until something creates a virtual one
the seat advertises no keyboard capability and `get_keyboard` returns a
proxy that never speaks.
"""
self.keyboard = self.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
self.display.roundtrip()
def bind_pointer(self) -> None:
self.pointer = self.seat.get_pointer()
self.pointer.dispatcher["enter"] = self._on_pointer_enter
self.pointer.dispatcher["leave"] = lambda _p, serial, surface: self.events.append(
"wl_pointer.leave"
)
self.display.roundtrip()
def create_virtual_pointer(self):
registry, global_id = self.vp_manager
# Version 2 for `create_virtual_pointer_with_output`, exactly as
# `hhstream_pointer.backend` requires: version 1's coordinates are the
# global layout, so a 0.5,0.5 warp would not be this output's centre.
manager = registry.bind(global_id, _wlr_pointer_manager(), 2)
proxy, name, mode = self.output()
self.virtual_pointer = manager.create_virtual_pointer_with_output(self.seat, proxy)
return name, mode
def create_virtual_keyboard(self):
"""Create one device and upload one keymap to it, in that order.
One keymap per device, sent once: a second `keymap` on the same device
replaces Hyprland's xkb state without walking `m_pressed`, which is
exactly the state (b) and (c) are about.
"""
keyboard = self.vk_manager.create_virtual_keyboard(self.seat)
fd, size = keymap_fd(keymap_text(self.layout, self.model))
try:
keyboard.keymap(XKB_FORMAT_TEXT_V1, fd, size)
# Round-trip before the fd is closed: the compositor has to have
# received and mapped it, and a flush is not a receipt.
self.display.roundtrip()
finally:
os.close(fd)
self.virtual_keyboards.append(keyboard)
self.events.append(f"uploaded keymap format={XKB_FORMAT_TEXT_V1} size={size}")
return keyboard
def open_windows(self) -> None:
"""`kb-probe-a` fullscreen, then `kb-probe-b` on top of it.
See the module docstring: the fullscreen one exists so the probe has an
unfocused window of its own to warp onto on a machine whose window rule
gives every window the same box.
"""
first = _Window(self, APP_A)
first.toplevel.set_fullscreen(None)
first.surface.commit()
self.windows.append(first)
self.display.roundtrip()
self.display.roundtrip()
self.windows.append(_Window(self, APP_B))
self.display.roundtrip()
self.display.roundtrip()
# -- events --------------------------------------------------------
def _app_of(self, surface) -> str:
for window in self.windows:
if window.surface == surface:
return window.app_id
return "other"
def _on_keymap(self, keyboard, format_: int, fd: int, size: int) -> None:
"""Compile what the compositor forwarded, and decode every later key
with it. A symbol decoded from a table in this file would prove
nothing about whether our upload arrived."""
from xkbcommon import xkb
try:
with os.fdopen(fd, "rb", closefd=True) as handle:
raw = handle.read(size)
except OSError as exc:
self.events.append(f"wl_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: # a keymap we cannot compile is the finding
self.events.append(f"wl_keyboard.keymap bytes={size} WILL NOT COMPILE: {exc}")
return
self.events.append(
f"wl_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:
return "?"
from xkbcommon import xkb
return xkb.keysym_get_name(self._state.key_get_one_sym(code + EVDEV_OFFSET))
def _on_enter(self, keyboard, serial, surface, keys) -> None:
app = self._app_of(surface)
self.focus = app
self.events.append(
f"enter surface={app} serial={serial} keys={list(keys) if keys else []}"
)
def _on_leave(self, keyboard, serial, surface) -> None:
app = self._app_of(surface)
if app == self.focus:
self.focus = None
self.events.append(f"leave surface={app}")
def _on_key(self, keyboard, serial, time_, key: int, state: int) -> None:
self.events.append(f"key code={key} state={state} sym={self._sym(key)}")
def _on_modifiers(self, keyboard, serial, depressed, latched, locked, group) -> None:
self._mask = (depressed, latched, locked, group)
if self._state is not None:
# Mask first, then the sym lookup above is the one a real client
# would do: `A` is only `A` because Shift is in this mask.
self._state.update_mask(depressed, latched, locked, 0, 0, group)
self.events.append(
f"modifiers depressed={depressed} latched={latched} "
f"locked={locked} group={group}"
)
def _on_repeat_info(self, keyboard, rate: int, delay: int) -> None:
self.repeat_info = (rate, delay)
self.events.append(f"repeat_info rate={rate} delay={delay}")
def _on_pointer_enter(self, pointer, serial, surface, x, y) -> None:
self.events.append(
f"wl_pointer.enter surface={self._app_of(surface)} at {x:.0f},{y:.0f}"
)
# -- the two actions the probe performs -----------------------------
def warp(self, x: float, y: float) -> None:
self.virtual_pointer.motion_absolute(
_now_ms(), round(x * EXTENT), round(y * EXTENT), EXTENT, EXTENT
)
self.virtual_pointer.frame()
self.display.flush()
def key(self, keyboard, code: int, state: int) -> None:
keyboard.key(_now_ms(), code, state)
self.display.flush()
def modifiers(self, keyboard, depressed: int) -> None:
keyboard.modifiers(depressed, 0, 0, 0)
self.display.flush()
# -- reporting ------------------------------------------------------
def report(self, prefix: str = "") -> list[str]:
seen, self.events[:] = list(self.events), []
for line in seen:
say(f" {prefix}{line}")
return seen
def _now_ms() -> int:
"""A millisecond timestamp for the protocol's `time` arguments.
The same function `hhstream_pointer.backend` uses, for the reason the
protocol gives: all requests on one object must share one clock, and the
compositor only compares them to each other.
"""
return int(time.monotonic() * 1000) & 0xFFFFFFFF
def _wlr_pointer_manager():
"""The wlr virtual-pointer manager class, from the repo's vendored copy.
Imported by path so the probe runs from a checkout without the package
being installed: Stage 0 has no reason to grow a second copy of a protocol
the driver already vendors.
"""
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "src"))
from hhstream_pointer._protocol.wlr_virtual_pointer_unstable_v1 import (
ZwlrVirtualPointerManagerV1,
)
return ZwlrVirtualPointerManagerV1
class _Window:
"""One toplevel, painted once, with an app id of its own.
Modelled on `checks/lib/pointer_target.py` and deliberately not shared with
it: that client is a VM fixture with a contract of its own (it reads
`$HHSTREAM_APP_ID`, because a container's window rule is written against
it), and this one is a probe that will be deleted.
"""
def __init__(self, probe: Probe, app_id: str) -> None:
self.probe = probe
self.app_id = app_id
self.size = DEFAULT_SIZE
self._pool = None
self._map: mmap.mmap | None = None
self.buffer = None
self.surface = probe.compositor.create_surface()
self.xdg_surface = probe.wm_base.get_xdg_surface(self.surface)
self.xdg_surface.dispatcher["configure"] = self._on_configure
self.toplevel = self.xdg_surface.get_toplevel()
self.toplevel.set_app_id(app_id)
self.toplevel.set_title(app_id)
self.toplevel.dispatcher["configure"] = self._on_toplevel_configure
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)
width, height = self.size
stride, size = width * 4, width * 4 * height
if self._map is None or self._map.size() < size:
fd = os.memfd_create(f"hhs-probe-{self.app_id}", 0)
os.ftruncate(fd, size)
self._map = mmap.mmap(fd, size)
self._pool = self.probe.shm.create_pool(fd, size)
os.close(fd)
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()
self.probe.events.append(f"configured surface={self.app_id} {width}x{height}")
# --------------------------------------------------------------------------
# the questions
# --------------------------------------------------------------------------
def question_globals(probe: Probe) -> int:
say()
say("=== 1. globals on this compositor ===")
for interface, version in sorted(probe.globals):
say(f" global {interface} v{version}")
wanted = probe.vk.ZwpVirtualKeyboardManagerV1.name
if probe.vk_manager is None:
say(f"ANSWER 1: {wanted} is ABSENT. The plan says stop here.")
return 2
if probe.vk_manager_version != WANTED_MANAGER_VERSION:
say(
f"ANSWER 1: {wanted} is version {probe.vk_manager_version}, not "
f"{WANTED_MANAGER_VERSION}. The plan says stop here."
)
return 2
say(f"ANSWER 1: {wanted} is present at version {probe.vk_manager_version}.")
if probe.vp_manager is None:
say(" ...but zwlr_virtual_pointer_manager_v1 is absent, so (a) cannot be measured.")
return 2
say(f" zwlr_virtual_pointer_manager_v1 v{probe.vp_manager_version} (needed for (a)).")
return 0
def question_focus(probe: Probe, output_name: str, mode: tuple[int, int]) -> None:
say()
say("=== (a) does a virtual-pointer warp move wl_keyboard focus? ===")
report_options()
geometry = boxes()
say(f" output {output_name} mode {mode[0]}x{mode[1]}")
for app, box in sorted(geometry.items()):
say(f" box {app} at {box[0]},{box[1]} size {box[2]}x{box[3]}")
say(f" focus at map time: {probe.focus} (expected {APP_B}: it mapped last)")
if APP_A not in geometry:
say(
"SKIPPED (a): hyprctl did not report our windows, so there is no "
"known box to warp into. Re-run with hyprctl on PATH."
)
return
target = pick_point(geometry[APP_A], geometry.get(APP_B), mode)
if target is None:
say(
f"SKIPPED (a): no point is inside {APP_A} and outside {APP_B} — the two "
"windows cover each other exactly, so no warp could tell them apart. "
"Measure it in vm-keyboard, where two sessions have two outputs."
)
return
second = (target[0], min(1.0, target[1] + A2_OFFSET))
say(f" (a1) target {target[0]:.4f},{target[1]:.4f} (inside {APP_A} only)")
say(
f" (a2) target {second[0]:.4f},{second[1]:.4f} — about "
f"{round(A2_OFFSET * mode[1])}px lower, so the FLOORED pixel changes. A "
"second warp to the same point would return before mouseMoveUnified "
"touched the delta, and would prove nothing."
)
# The whole point of (a1): the cursor must have been still for longer than
# Hyprland's 0.5 s window, or the delta from an earlier move carries it.
probe.pump(IDLE_S)
probe.report("idle -> ")
say(f" (a1) one warp after {IDLE_S}s of stillness")
first_sent = time.monotonic()
probe.warp(*target)
probe.pump(SETTLE_S)
first_bucket = probe.report("(a1) -> ")
say(" (a2) a second warp, to the (a2) target above")
gap = time.monotonic() - first_sent
probe.warp(*second)
probe.pump(SETTLE_S)
second_bucket = probe.report("(a2) -> ")
# Timed rather than asserted in prose: (a2) is the in-window case only
# while this stays under 0.5 s, and an earlier version of this script
# printed the word "immediately" about a gap it never measured.
say(
f" gap between the two motion_absolute calls: {gap:.3f}s "
f"({'under' if gap < 0.5 else 'OVER'} Hyprland's 0.5s delta window)"
)
# `startswith`, not `in`: `wl_pointer.enter surface=kb-probe-a` contains
# the substring `enter surface=kb-probe-a`, and an `in` test here reported
# a1_enter=yes off a pointer event. That is the review's own category of
# false pass, found in this probe.
entered_a1 = any(line.startswith(f"enter surface={APP_A}") for line in first_bucket)
entered_a2 = any(line.startswith(f"enter surface={APP_A}") for line in second_bucket)
pointer_moved = any(
line.startswith(f"wl_pointer.enter surface={APP_A}")
for line in first_bucket + second_bucket
)
say(
f" a1_enter={'yes' if entered_a1 else 'no'} "
f"a2_enter={'yes' if entered_a2 else 'no'} "
f"pointer_reached_{APP_A}={'yes' if pointer_moved else 'no'}"
)
if entered_a1:
say(
f"ANSWER (a): the idle warp DID deliver wl_keyboard.enter to {APP_A}. "
"That is not what v0.56.2's threshold logic predicts, so this binary "
"does not match the read of InputManager::onMouseWarp. Stage 3 must "
"still assert it rather than assume it."
)
elif entered_a2:
say(
f"ANSWER (a): the idle warp onto unfocused {APP_A} delivered "
f"wl_pointer.enter and NO wl_keyboard.enter. {APP_B}'s leave and "
f"{APP_A}'s enter arrived only after the LATER motion_absolute, the "
"one that changed the floored pixel -- so the enter belongs to that "
"motion's non-zero m_mousePosDelta and is NOT a delayed effect of "
"the first warp."
)
say(
" Consequence: `pointer acquire` is one warp, so the first "
"key of a lease can land in whatever was already focused. Stage 3's "
"enter subtest must not be written against acquire's single warp, "
"and warping twice to the same bookmark is not the fix -- the same "
"floored pixel returns early."
)
elif pointer_moved:
say(
f"ANSWER (a): NO — the cursor reached {APP_A} (wl_pointer.enter above) "
"and keyboard focus never followed, on either warp. Stage 4 "
"(dispatch focuswindow before the first key of a lease) is required."
)
else:
say(
"ANSWER (a): INCONCLUSIVE — the cursor never reached the aimed window "
"at all, so focus was never in question. Read the boxes above."
)
def question_repeat(probe: Probe) -> None:
"""(c), and it deliberately leaves the key down for (b)."""
say()
say("=== (c) is one held virtual key one wl_keyboard.key? ===")
if probe.focus not in (APP_A, APP_B):
say("SKIPPED (c): no window of ours holds keyboard focus; refusing to type.")
return
keyboard = probe.virtual_keyboards[0]
probe.report("before -> ")
probe.key(keyboard, KEY_A, PRESSED)
probe.pump(REPEAT_HOLD_S)
held = probe.report("")
presses = sum(
1
for line in held
if f"key code={KEY_A} state={PRESSED}" in line or f"key code={KEY_A} state={REPEATED}" in line
)
say(f" press_count={presses} repeat_info={probe.repeat_info}")
if presses > 1:
say(f"ANSWER (c): {presses} events in {REPEAT_HOLD_S}s — the compositor repeats.")
elif presses == 1:
say(
"ANSWER (c): press_count=1 — the compositor does not repeat on the "
f"wire; it published repeat_info {probe.repeat_info} and the CLIENT "
"repeats. This is NOT 'keyboard down will not flood a text field': "
"foot/GTK/Qt will insert characters from this one press until the "
"key-up or the lease TTL. The help text must warn unconditionally."
)
else:
say("ANSWER (c): INCONCLUSIVE — the press itself never arrived.")
say(f" (key code={KEY_A} deliberately left down, for (b))")
def question_destroy(probe: Probe) -> None:
"""(b): destroy with the key from (c) still down. No key-up first."""
say()
say("=== (b) does destroying the virtual keyboard release a held key? ===")
if probe.focus not in (APP_A, APP_B):
say("SKIPPED (b): no window of ours holds keyboard focus; refusing to type.")
return
# A second device first. With only one, `destroy` takes the seat's last
# keyboard away, `wl_keyboard` goes with it, and "no release arrived" would
# be ambiguous: no release *could* arrive. The spare keeps the capability
# up so a release has somewhere to be delivered.
spare = probe.create_virtual_keyboard()
probe.pump(0.3)
probe.report("spare -> ")
victim = probe.virtual_keyboards[0]
victim.destroy()
probe.virtual_keyboards.remove(victim)
probe.pump(1.0)
after = probe.report("after destroy -> ")
released = any(f"key code={KEY_A} state={RELEASED}" in line for line in after)
cleared = any("modifiers depressed=0" in line for line in after)
say(
f" release_on_destroy={'yes' if released else 'no'} "
f"mask_cleared={'yes' if cleared else 'no'}"
)
say(" (compare with input:virtualkeyboard:release_pressed_on_close, printed above)")
if released:
say("ANSWER (b): YES — destroy released the held key.")
else:
say(
"ANSWER (b): NO RELEASE — destroy delivered no key-up, with a second "
"keyboard keeping the seat's capability up and with nothing of ours "
"having sent an up beforehand."
)
say(
" Read `mask_cleared` narrowly: it says only that destroy "
"emitted no `modifiers` event. The held key is a letter, so the "
"depressed mask was 0 throughout -- this is NOT a measurement of a "
"non-zero mask surviving destroy. releasePressed emits key-ups only "
"(VirtualKeyboard.cpp), which is why release_all sends "
"modifiers(0,0,0,0) regardless."
)
say(
" The confirming evidence is the cleanup below: "
"onKeyboardKey DROPS a release whose code is not in the seat's "
f"m_pressed, so a `key code={KEY_A} state=0` arriving from a BRAND "
"NEW keyboard means the code was still in that set after destroy. A "
"driver killed with -9 leaves it there and the next driver's press "
"of it is dropped: dead, not merely stuck. _lift_everything is the "
"only guard on the clean path and SIGKILL skips it."
)
# Required cleanup, and it is the review's step 7: a NEW virtual keyboard,
# its own keymap, then the key-up and a zeroed mask that undo a poisoned
# m_pressed. Without this the next run of anything inherits a dead key.
fresh = probe.create_virtual_keyboard()
probe.key(fresh, KEY_A, RELEASED)
probe.modifiers(fresh, 0)
probe.pump(0.4)
probe.report("cleanup -> ")
say(" cleanup=sent")
probe.modifiers(spare, 0)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="keyboard-probe",
description=__doc__.splitlines()[0],
epilog="Read-only with respect to the broker: it speaks to the compositor only.",
)
parser.add_argument(
"--runtime-dir",
type=pathlib.Path,
default=pathlib.Path("/run/hypr-stream"),
help="the compositor's XDG_RUNTIME_DIR (default: %(default)s)",
)
parser.add_argument("--xml", type=pathlib.Path, default=None, help=f"path to {XML_NAME}")
parser.add_argument("--output", default=None, help="output name; only needed if several")
parser.add_argument("--xkb-layout", default="us")
parser.add_argument("--xkb-model", default="pc105")
args = parser.parse_args(argv)
module = load_virtual_keyboard(find_xml(args.xml))
probe = Probe(module, layout=args.xkb_layout, model=args.xkb_model, output_name=args.output)
probe.connect(args.runtime_dir)
try:
gate = question_globals(probe)
if gate:
return gate
output_name, mode = probe.create_virtual_pointer()
# The device before the listener: with no physical keyboard on this
# seat, `wl_keyboard` has nothing to report until a virtual one exists.
probe.create_virtual_keyboard()
probe.bind_keyboard()
probe.bind_pointer()
probe.open_windows()
probe.pump(1.0)
setup = probe.report("setup -> ")
stale = [line for line in setup if "keys=[" in line and "keys=[]" not in line]
if stale:
# Worth shouting about: a key down in a *fresh* client's very first
# `enter` was left there by something that is no longer running.
# It is the evidence (b) asks for, arriving before (b) is asked.
say(
" NOTE: this connection was handed a key that was already "
f"down: {stale[-1].strip()}. Nothing of ours is holding it."
)
question_focus(probe, output_name, mode)
question_repeat(probe)
question_destroy(probe)
finally:
# Lift anything still down before the connection goes, because that is
# the only guard the driver has either
# (`hhstream_pointer.__main__._lift_everything`).
for keyboard in probe.virtual_keyboards:
probe.key(keyboard, KEY_A, RELEASED)
probe.modifiers(keyboard, 0)
probe.pump(0.3)
probe.close()
say()
say("Done. Nothing here touched the broker, the lease or any session.")
return 0
if __name__ == "__main__":
sys.exit(main())