Files
hyprland-headless-stream-pl…/tests/keyboard_probe.py
T
HermenixandClaude Opus 5 19e484b388 Stage 0: measure the compositor instead of reading its source
A throwaway client against the live /run/hypr-stream that answers the
four open questions. It touches no broker, no lease and no session; it
opens two windows of its own and moves the one cursor, because keyboard
focus cannot be measured without doing both, and it refuses to send a
key until it sees wl_keyboard.enter on a surface it owns.

What it found, with the transcript beside it:

  1  zwp_virtual_keyboard_manager_v1 is present at version 1. The gate
     the plan hangs on holds against the running binary, not just
     against §6.7's [RAN] claim.

  a  ONE IDLE WARP DOES NOT MOVE KEYBOARD FOCUS. A second warp
     immediately after does. Measured with an unfocused fullscreen
     window under a focused floating one, warping into the margin that
     belongs to the first alone -- and `pointer acquire` is one warp, so
     the first key of a lease can land in the previously focused
     window. Neither plan permits building the fallback here, so this
     branch does not; it is the objection in the final report.

  b  destroy with a key down releases nothing and clears no mask
     (release_pressed_on_close is 0 and unset). An earlier run proved it
     by accident: it exited with Shift_L down and the NEXT run's first
     enter carried keys=[42, 0, 0, 0].

  c  one held key is one wl_keyboard.key, with repeat_info 25/600. The
     flood is the client's repeat, not ours -- which is why `down` warns
     unconditionally rather than only if the probe saw repeats.

The XML both plans name does not exist in this nixpkgs: not in
wayland-protocols 1.49, not in wlr-protocols, not in wlroots. Hyprland's
own copy is the only one, so that is what is used -- and because it
names keymap_format and key_state without defining them, both are
written down as cited constants instead of read off an enum.

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

1012 lines
41 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. `InputManager::onMouseWarp`
calls `mouseMoveUnified(refocus=false)`, and with `follow_mouse = 1` keyboard
focus needs `m_mousePosDelta > follow_mouse_threshold` (default 0) — and the
delta is reset to 0 when the previous cursor movement was more than 0.5 s ago.
So one idle warp is expected *not* to move keyboard focus and a second one is.
A probe that reported a single yes/no would hide exactly the thing the lease's
`acquire` does: one warp, then immediately 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
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
say(f" chosen warp target {target[0]:.4f},{target[1]:.4f} (inside {APP_A} only)")
# 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")
probe.warp(*target)
probe.pump(SETTLE_S)
first = probe.report("(a1) -> ")
say(" (a2) a second warp, immediately, still inside the same window")
probe.warp(target[0], min(1.0, target[1] + 0.004))
probe.pump(SETTLE_S)
second = probe.report("(a2) -> ")
# `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)
entered_a2 = any(line.startswith(f"enter surface={APP_A}") for line in second)
pointer_moved = any(
line.startswith(f"wl_pointer.enter surface={APP_A}") for line in first + second
)
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): one idle warp DID deliver 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): one idle warp did NOT deliver enter; the SECOND warp "
f"did. Exactly what the review predicted. A lease's `acquire` is one "
"warp, so the first key of a lease can land in the previously "
"focused window: Stage 4 (or a second warp) is needed, and Stage 3's "
"enter assertion must not be written against a single warp."
)
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 — destroy delivered no release, with another keyboard "
"keeping the seat's capability up. So a driver killed with -9 leaves "
f"evdev {KEY_A} in the seat's m_pressed, and InputManager::"
"onKeyboardKey then DROPS the next press of that code: the key is "
"dead until something sends a matching up. _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())