From 19e484b388ee21afb189d23cc7f1dcf8ba38d151 Mon Sep 17 00:00:00 2001 From: Hermenix Date: Sun, 4 Oct 2026 03:21:14 +0000 Subject: [PATCH] Stage 0: measure the compositor instead of reading its source MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_01GhNPM6rGcuzxocM1nATnuM --- tests/README-keyboard-probe.md | 186 +++++ tests/keyboard-probe-2026-10-04.txt | 136 ++++ tests/keyboard_probe.py | 1011 +++++++++++++++++++++++++++ 3 files changed, 1333 insertions(+) create mode 100644 tests/README-keyboard-probe.md create mode 100644 tests/keyboard-probe-2026-10-04.txt create mode 100644 tests/keyboard_probe.py diff --git a/tests/README-keyboard-probe.md b/tests/README-keyboard-probe.md new file mode 100644 index 0000000..47e7136 --- /dev/null +++ b/tests/README-keyboard-probe.md @@ -0,0 +1,186 @@ +# `keyboard_probe.py` — Stage 0 of the keyboard plan + +Stage 0 of [`docs/plans/2026-10-03-keyboard-input.md`](../docs/plans/2026-10-03-keyboard-input.md), +written to the probe spec in +[`docs/plans/2026-10-04-keyboard-verification.md`](../docs/plans/2026-10-04-keyboard-verification.md) +§B1. It measures the things neither plan would let Stage 1 guess at, and prints +what it saw. + +It is **throwaway**: delete it once `checks/vm-keyboard.nix` asserts the same +properties in a VM. The review says not to commit it at all; the brief that +commissioned this work says to commit it under `examples/` or `tests/` with a +README, and that is what this is. Nothing downstream imports it. + +It speaks to the compositor and to nothing else — **no broker, no lease, no +`hhstreamd` control socket, no `hhstream` CLI, no session**. Read-only +`hyprctl` (`clients -j`, `getoption -j`) is used so the warp hits a box it +knows the coordinates of; `hyprctl dispatch` is never used, because +`dispatch focuswindow` would answer (a) by cheating. + +It does two things that are not read-only, because keyboard focus cannot be +measured without them: it opens two small windows of its own, and it moves the +one cursor. It refuses to send a key until it has seen `wl_keyboard.enter` on a +surface it owns, and it lifts everything it pressed on the way out — including +through a fresh virtual keyboard, because of what (b) turned out to be. + +## Running it + +It needs `pywayland` (the dev shell has it), `xkbcommon` (the dev shell does +not, until Stage 1 adds it), `hyprctl`, and the protocol XML. One command, in +the shape `hhstream_pointer._protocol.regenerate`'s docstring already uses for +"this needs something the dev shell lacks": + +```bash +cd /var/lib/hermes/projects/hhstream-keyboard # or wherever this checkout is +XML="$(nix eval --raw nixpkgs#hyprland.src)/protocols" + +sg hhstream -c "HHSTREAM_PROTOCOL_DIR='$XML' PYTHONPATH=src \ + nix shell --impure --expr 'with (builtins.getFlake \"nixpkgs\").legacyPackages.\${builtins.currentSystem}; [ (python3.withPackages (p: [ p.pywayland p.xkbcommon ])) hyprland ]' \ + --command python3 tests/keyboard_probe.py" +``` + +`sg hhstream` is not optional: `/run/hypr-stream` is `0750 hhstream:hhstream`, +so a login that predates the group membership cannot open the Wayland socket at +all. (The review's `sudo -u hermes -g hhstream env …` form does the same thing +and also works; `sg` is what the brief asked for and needs no root.) +`PYTHONPATH=src` is how it reaches the driver's already-vendored wlr *pointer* +protocol rather than growing a second copy. + +Flags: `--runtime-dir` (default `/run/hypr-stream`), `--xml`, `--output` (only +needed if the compositor has more than one), `--xkb-layout`, `--xkb-model`. + +Exit codes: **2** if `zwp_virtual_keyboard_manager_v1` is missing or is not +version 1 — the gate the plan says stops the project — and 0 otherwise. The +answers are in the output, not in the exit status: a measurement that came back +"no" is still a successful measurement. + +### Where the XML is, and where both plans say it is + +Both plans say the XML is wayland-protocols' +`unstable/virtual-keyboard/virtual-keyboard-unstable-v1.xml`, and the review's +objection 4 says specifically *not* to use Hyprland's copy. **Neither is +possible here.** Checked, on this machine: + +| Source | Has it? | +| --- | --- | +| `wayland-protocols` 1.49 (this flake's own nixpkgs input), `unstable/`, `staging/`, `stable/` | no — there is no `virtual-keyboard` directory at all | +| `pkgs.wlr-protocols` (nixpkgs' 2022-09-05 snapshot), output *and* `.src` | no — ten XMLs, the virtual *pointer* among them, not this one | +| `pkgs.wlroots.src` | no | +| `pkgs.hyprland.src` → `protocols/virtual-keyboard-unstable-v1.xml` | **yes, and it is the only copy** | + +```bash +echo "$(nix eval --raw nixpkgs#hyprland.src)/protocols/virtual-keyboard-unstable-v1.xml" +``` + +So the probe, and Stage 1's vendoring, use the Hyprland copy. The review's +reason for avoiding it is real and is handled rather than ignored: that copy +*names* `keymap_format` and `key_state` in prose and never defines them, so the +generated module carries no enum for either. Both are therefore written down as +constants with a citation — in this file as `XKB_FORMAT_TEXT_V1` and +`RELEASED`/`PRESSED`, and in the driver as `hhstream_pointer.keymap.XKB_V1` +beside the existing `buttons.STATES` (which already holds the same two +integers, as the review notes). Same class of correction +`docs/CONTRACT-sessions.md` §3.4 already had to make for the wlr pointer XML +path. + +## What it answered + +Run 2026-10-04 against the live `/run/hypr-stream`: Hyprland 0.56.2, one output +`Virtual-1` at 1280x720, two Chromium windows already on screen. Reproduced +across six runs. Full transcript, verbatim: +[`keyboard-probe-2026-10-04.txt`](keyboard-probe-2026-10-04.txt). + +The configuration the answers depend on, as the compositor reports it: + +``` +input:follow_mouse = 1 (set) +input:follow_mouse_threshold = 0.0 (default) +input:virtualkeyboard:release_pressed_on_close = 0 (default) +input:repeat_rate = 25 (default) +input:repeat_delay = 600 (default) +input:kb_layout = us (default) +``` + +### 1. The global — the gate the whole project hangs on + +**`zwp_virtual_keyboard_manager_v1` is present at version 1.** §6.7's `[RAN]` +claim holds against the running binary. `wp_virtual_keyboard_v1` is not +advertised, as both plans predicted. `zwlr_virtual_pointer_manager_v1` is at +v2, so the driver's existing version-2 requirement is still met. The project +continues. + +### (a) Does a virtual-pointer warp move `wl_keyboard` focus? + +**One idle warp: NO. A second warp immediately after: YES.** Exactly what the +review's read of `InputManager::onMouseWarp` predicted, and the reason it +insisted (a1) and (a2) be measured separately. + +``` +box kb-probe-a at 0,0 size 1280x720 <- fullscreen, unfocused +box kb-probe-b at 120,80 size 1040x560 <- focused: it mapped last +chosen warp target 0.0100,0.0100 (inside kb-probe-a only) + +(a1) one warp after 0.8s of stillness +(a1) -> wl_pointer.enter surface=kb-probe-a at 13,7 <- cursor arrived + <- and nothing else + +(a2) a second warp, immediately, still inside the same window +(a2) -> leave surface=kb-probe-b +(a2) -> enter surface=kb-probe-a serial=336 keys=[] <- focus, one warp late + +a1_enter=no a2_enter=yes pointer_reached_kb-probe-a=yes +``` + +The consequence is the headline risk of this whole feature: **`pointer +acquire` is one warp**, so the first key of a lease can be delivered to +whatever was focused before. Neither plan permits building the fallback in +Stages 1–2 (`docs/plans/2026-10-03-keyboard-input.md` §6 risk 1; the review's +"Do not build it in Stage 1"), so Stages 1–2 do not, and the final report +carries the objection. Stage 3's enter assertion must not be written against a +single warp. + +Worth recording about this probe, because it is the review's own category of +false pass and it happened here: an earlier version matched the keyboard +`enter` line with `"enter surface=kb-probe-a" in line`, which also matches +`wl_pointer.enter surface=kb-probe-a`, and reported `a1_enter=yes`. The match +is `startswith` now. + +### (b) Does destroying the virtual keyboard release a held key? + +**NO — `release_on_destroy=no`, `mask_cleared=no`**, measured with a second +virtual keyboard keeping the seat's keyboard capability up, so that a release +had somewhere to be delivered. `input:virtualkeyboard:release_pressed_on_close` +is `0` and unset, which is the default the review read out of +`ConfigValues.cpp`. + +Corroborated by accident on an earlier run, which is the strongest form the +evidence takes: a run that exited with `Shift_L` down and no spare device left +the key down, and the *next* run's very first `wl_keyboard.enter` carried +`keys=[42, 0, 0, 0]` — evdev 42 is `KEY_LEFTSHIFT`. The key outlived the +process that pressed it. Sending the release from a different virtual keyboard +cleared it, which is why the probe now ends with a fresh keyboard, a key-up and +a zeroed mask (the review's step 7). + +This is worse than "a key stays down": `InputManager::onKeyboardKey` drops a +press whose code is already in the seat's `m_pressed`, so after a `kill -9` the +next driver's `key down` for that code is ignored and the key is dead until +something sends a matching up. Handled in Stage 2 by +`input:virtualkeyboard:release_pressed_on_close = true` in +`nix/hyprland-conf.nix` (the review's change 4), with the explicit note that +the setting releases keys and still does not clear the modifier mask — which is +why `release_all` ends with `modifiers(0, 0, 0, 0)` on the clean path +regardless. + +### (c) Does Hyprland auto-repeat a held virtual key? + +**`press_count=1`, `repeat_info rate=25 delay=600`.** A key left down for 1.5 s +— longer than the 600 ms delay — produced exactly one `wl_keyboard.key … state=1`. + +This is **not** "`keyboard down` will not flood a text field", and reading it +that way is the review's named false pass. The compositor does not repeat on +the wire; it publishes a rate and the *client* repeats. A focused foot, GTK or +Qt text field will insert characters from that one press until the key-up or +the lease TTL (default 30 s). So `keyboard down` of a non-modifier warns +unconditionally in the CLI help, and v1 has no repeat rate to offer because we +do not generate the repeats. `zwp_virtual_keyboard_v1` has no `repeated` state +and there is nothing to ask the compositor for. diff --git a/tests/keyboard-probe-2026-10-04.txt b/tests/keyboard-probe-2026-10-04.txt new file mode 100644 index 0000000..3cdebb8 --- /dev/null +++ b/tests/keyboard-probe-2026-10-04.txt @@ -0,0 +1,136 @@ +keyboard_probe.py, run 2026-10-04 against the live /run/hypr-stream. +Hyprland 0.56.2, one output Virtual-1 at 1280x720, two Chromium windows +already on screen. Verbatim; nothing edited. + +=== 1. globals on this compositor === + global ext_background_effect_manager_v1 v1 + global ext_data_control_manager_v1 v1 + global ext_foreign_toplevel_image_capture_source_manager_v1 v1 + global ext_foreign_toplevel_list_v1 v1 + global ext_idle_notifier_v1 v2 + global ext_image_copy_capture_manager_v1 v1 + global ext_output_image_capture_source_manager_v1 v1 + global ext_session_lock_manager_v1 v1 + global ext_workspace_manager_v1 v1 + global hyprland_ctm_control_manager_v1 v2 + global hyprland_focus_grab_manager_v1 v1 + global hyprland_global_shortcuts_manager_v1 v1 + global hyprland_input_capture_manager_v1 v1 + global hyprland_lock_notifier_v1 v1 + global hyprland_surface_manager_v1 v2 + global hyprland_toplevel_export_manager_v1 v2 + global hyprland_toplevel_mapping_manager_v1 v1 + global org_kde_kwin_server_decoration_manager v1 + global vicinae_hotkey_manager_v1 v1 + global wl_compositor v6 + global wl_data_device_manager v3 + global wl_drm v2 + global wl_output v4 + global wl_seat v9 + global wl_shm v2 + global wl_subcompositor v1 + global wp_alpha_modifier_v1 v1 + global wp_color_manager_v1 v3 + global wp_commit_timing_manager_v1 v1 + global wp_content_type_manager_v1 v1 + global wp_cursor_shape_manager_v1 v2 + global wp_drm_lease_device_v1 v1 + global wp_fifo_manager_v1 v1 + global wp_fractional_scale_manager_v1 v1 + global wp_pointer_warp_v1 v1 + global wp_presentation v2 + global wp_security_context_manager_v1 v1 + global wp_single_pixel_buffer_manager_v1 v1 + global wp_tearing_control_manager_v1 v1 + global wp_viewporter v1 + global xdg_activation_v1 v1 + global xdg_system_bell_v1 v1 + global xdg_toplevel_tag_manager_v1 v1 + global xdg_wm_base v7 + global xdg_wm_dialog_v1 v1 + global xwayland_shell_v1 v1 + global zwlr_data_control_manager_v1 v2 + global zwlr_foreign_toplevel_manager_v1 v3 + global zwlr_gamma_control_manager_v1 v1 + global zwlr_layer_shell_v1 v5 + global zwlr_output_manager_v1 v4 + global zwlr_output_power_manager_v1 v1 + global zwlr_screencopy_manager_v1 v3 + global zwlr_virtual_pointer_manager_v1 v2 + global zwp_idle_inhibit_manager_v1 v1 + global zwp_input_method_manager_v2 v1 + global zwp_keyboard_shortcuts_inhibit_manager_v1 v1 + global zwp_linux_dmabuf_v1 v5 + global zwp_pointer_constraints_v1 v1 + global zwp_pointer_gestures_v1 v3 + global zwp_primary_selection_device_manager_v1 v1 + global zwp_relative_pointer_manager_v1 v1 + global zwp_tablet_manager_v2 v1 + global zwp_text_input_manager_v1 v1 + global zwp_text_input_manager_v3 v1 + global zwp_virtual_keyboard_manager_v1 v1 + global zxdg_decoration_manager_v1 v2 + global zxdg_exporter_v2 v1 + global zxdg_importer_v2 v1 + global zxdg_output_manager_v1 v3 +ANSWER 1: zwp_virtual_keyboard_manager_v1 is present at version 1. + zwlr_virtual_pointer_manager_v1 v2 (needed for (a)). + setup -> seat capabilities=1 + setup -> seat capabilities=3 + setup -> uploaded keymap format=1 size=35572 + setup -> wl_keyboard.keymap format=1 bytes=35572 symbols=xkb_symbols "pc_us_inet(evdev)" { + setup -> repeat_info rate=25 delay=600 + setup -> configured surface=kb-probe-a 640x360 + setup -> enter surface=kb-probe-a serial=357 keys=[] + setup -> modifiers depressed=0 latched=0 locked=0 group=0 + setup -> configured surface=kb-probe-a 1280x720 + setup -> configured surface=kb-probe-b 640x360 + setup -> modifiers depressed=0 latched=0 locked=0 group=0 + setup -> leave surface=kb-probe-a + setup -> enter surface=kb-probe-b serial=365 keys=[] + setup -> modifiers depressed=0 latched=0 locked=0 group=0 + setup -> configured surface=kb-probe-b 1040x560 + setup -> configured surface=kb-probe-a 1280x720 + +=== (a) does a virtual-pointer warp move wl_keyboard focus? === + options this measurement depends on: + input:follow_mouse = {"int": 1, "option": "input:follow_mouse", "set": true} + input:follow_mouse_threshold = {"float": 0.0, "option": "input:follow_mouse_threshold", "set": false} + input:virtualkeyboard:release_pressed_on_close = {"int": 0, "option": "input:virtualkeyboard:release_pressed_on_close", "set": false} + input:repeat_rate = {"int": 25, "option": "input:repeat_rate", "set": false} + input:repeat_delay = {"int": 600, "option": "input:repeat_delay", "set": false} + input:kb_layout = {"option": "input:kb_layout", "set": false, "str": "us"} + output Virtual-1 mode 1280x720 + box kb-probe-a at 0,0 size 1280x720 + box kb-probe-b at 120,80 size 1040x560 + focus at map time: kb-probe-b (expected kb-probe-b: it mapped last) + chosen warp target 0.0100,0.0100 (inside kb-probe-a only) + (a1) one warp after 0.8s of stillness + (a1) -> wl_pointer.enter surface=kb-probe-a at 13,7 + (a2) a second warp, immediately, still inside the same window + (a2) -> modifiers depressed=0 latched=0 locked=0 group=0 + (a2) -> leave surface=kb-probe-b + (a2) -> enter surface=kb-probe-a serial=371 keys=[] + (a2) -> modifiers depressed=0 latched=0 locked=0 group=0 + (a2) -> configured surface=kb-probe-b 1040x560 + (a2) -> configured surface=kb-probe-a 1280x720 + a1_enter=no a2_enter=yes pointer_reached_kb-probe-a=yes +ANSWER (a): one idle warp did NOT deliver enter; the SECOND warp 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. + +=== (c) is one held virtual key one wl_keyboard.key? === + key code=30 state=1 sym=a + press_count=1 repeat_info=(25, 600) +ANSWER (c): press_count=1 — the compositor does not repeat on the wire; it published repeat_info (25, 600) 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. + (key code=30 deliberately left down, for (b)) + +=== (b) does destroying the virtual keyboard release a held key? === + spare -> uploaded keymap format=1 size=35572 + release_on_destroy=no mask_cleared=no + (compare with input:virtualkeyboard:release_pressed_on_close, printed above) +ANSWER (b): NO — destroy delivered no release, with another keyboard keeping the seat's capability up. So a driver killed with -9 leaves evdev 30 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. + cleanup -> uploaded keymap format=1 size=35572 + cleanup -> key code=30 state=0 sym=a + cleanup -> modifiers depressed=0 latched=0 locked=0 group=0 + cleanup=sent + +Done. Nothing here touched the broker, the lease or any session. diff --git a/tests/keyboard_probe.py b/tests/keyboard_probe.py new file mode 100644 index 0000000..3c25be4 --- /dev/null +++ b/tests/keyboard_probe.py @@ -0,0 +1,1011 @@ +#!/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} = ") + 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(" 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())