Files
hyprland-headless-stream-pl…/tests/pointer/test_keymap.py
T
HermenixandClaude Opus 5 e6f4c3bb3f Stage 1 review fixes, and Stage 2: the broker, the CLI and the module
The Stage 1 review (docs/reviews/2026-10-04-stage1-review.md, verdict
yes-with-fixes) found a real bug, and it was the kind Stage 2 would have
cemented. All five findings:

(1) HIGH, and reproduced before fixing: `key` resolved the action and
    then used only its `code`. So `keyboard key A` sent a bare code 30
    and the window received `a`; on `de`, `at` lost its level-three mask
    and typed `q`. `type` was the only path that used the mask, which is
    why every `type` test stayed green. `key` now sends
    modifiers(baseline | mask) before the down and restores the baseline
    on the up -- the one-character `type` sequence -- and `Shift_L`
    keeps its key-then-mask order, which is the other path on purpose.

    The same hole aliased two names onto one keycode: `down A` then
    `down a` recorded both and pressed 30 twice, Hyprland dropped the
    second, and the held set lied until the lease ended. A second name
    for a code already down is now refused.

(2) HIGH: the shutdown comment claimed hyprland-conf.nix sets
    input:virtualkeyboard:release_pressed_on_close. It did not. The line
    is there now, with the note that it releases keys and still never
    clears a mask -- which is why release_all zeroes the mask on every
    path we control rather than relying on it.

(3) MEDIUM: nothing would have noticed the keymap upload stopping. A
    `main` that connected and listened without uploading passed every
    test in the tree. Now asserted on the real sink: uploaded once,
    before `listen` (one shared ordering log across both stand-ins), the
    payload NUL-terminated with `size == len(utf8) + 1` read back
    through the fd, format 1, one terminator not two, and modifiers(0)
    straight after.

(4) LOW: `key` up now forgets the name only after a successful send,
    like `button` -- otherwise a raise between the two leaves us
    believing a key is up that the compositor still has down, and
    release_all will not try again.

(5) LOW: `\r` no longer aliases to Return (CRLF would have become two
    newlines silently), and an empty layout is refused -- xkbcommon
    compiles "" as the same keymap as `us`, so `--xkb-layout ''` looked
    configured and typed `us`.

Several of the review's named false passes are closed too: Control's
mask is compared against mod_get_index("Control") rather than merely
"not Shift's"; the keymap text assertion names pc_us_inet/pc_de_inet
instead of substring-matching "us"; the capital-under-Control case
asserts the whole sequence; the exit-code mirror is compared against
hhstreamd.protocol; and the module's defaults are read out of
nix/module.nix rather than asserted against themselves.

Stage 2 proper:

  * broker verbs keyboard.key / keyboard.type, both in the mutation set,
    both through _refresh (so they refresh the lease and, like every
    pointer verb, do NOT count as activity)
  * the driver's `kind` token mapped: a bad keysym or character is
    invalid_argument (exit 2), a missing keyboard global stays
    driver_refused (exit 10). The 4096-scalar cap and the shape checks
    are broker-side, because only a broker-side invalid_argument is 2
  * keys[] on pointer.state, keys_lifted[] on pointer.release and on
    pointer_lease_timeout, one release_all for both halves
  * CLI `session keyboard type|key|down|up`, reusing the pointer lease
    and its cache; `type` takes one raw argument and interprets nothing;
    the audit records a character count and never the text
  * sessions.keyboard.{layout,model,variant,options} on the unit's argv,
    layout defaulting to "us" with a type that refuses a comma. NO
    [keyboard] TOML table: hhstreamd reads that file and the driver is a
    different unit, so it would be a setting with no effect
  * CONTRACT-sessions.md bumped to v3; README.dev.md item 3 and
    vm-pointer.nix's header corrected (both still said the conf ships
    follow_mouse = 0 and that the keyboard work would choose)

And the operator decision that acquire grabs both devices: it now sends
two warps a real pixel apart, because one warp onto an idle cursor moves
the cursor and not keyboard focus. follow_mouse_threshold = 0 is set
explicitly in hyprland-conf.nix since the second warp depends on it,
`dispatch focuswindow` is the fallback when the nudge cannot be sent,
and the reply and audit carry which mechanism ran. The acquire test
asserts the pair and that they floor to different pixels -- a test that
only saw wl_pointer.enter would pass while the first keystroke went to
the wrong window.

  nix develop -c python -m pytest tests/pointer tests/sessions/unit -q
  605 passed in 27.11s

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

332 lines
12 KiB
Python

"""Keysym names and text to ``(evdev code, modifier mask)``, against real xkbcommon.
A real keymap, not a stub, and that is the whole design of this file. A stub
can be made to agree with any resolver; only xkbcommon can tell you that ``é``
is unmappable on ``us``, that ``@`` on ``de`` is a *level-three* symbol rather
than a shifted one, and that ``y`` and ``z`` swap keycodes between the two.
Those three facts are what the resolver exists for, so ``xkbcommon`` is a hard
dependency (``pyproject.toml`` says why) and these tests do not skip.
Codes here are **evdev**, never XKB. ``a`` is 30 and not 38: 30 is what
``zwp_virtual_keyboard_v1.key`` carries and what the client reads back off
``wl_keyboard.key``, and asserting 38 would be asserting an internal index that
never reaches the wire.
Masks are read out of the keymap, never written down. ``A`` needs
``1 << mod_get_index("Shift")``, which happens to be 1 on every layout here —
so the test computes it, because a hard-coded 1 passes today and is wrong the
first time a resolver is asked for a level-three character.
"""
from __future__ import annotations
import pytest
from hhstream_pointer import keymap as keymaps
from hhstream_pointer.ops import KIND_INVALID, Dispatcher
#: evdev codes from ``linux/input-event-codes.h``, spelled out so a failure
#: reads against the header rather than against another part of this suite.
KEY_A = 30
KEY_ENTER = 28
KEY_TAB = 15
KEY_LEFTSHIFT = 42
KEY_Y = 21 # the physical key that is `y` on us and `z` on de
KEY_Z = 44 # ...and `z` on us, `y` on de
@pytest.fixture(scope="module")
def us() -> keymaps.Keymap:
return keymaps.build(layout="us")
@pytest.fixture(scope="module")
def de() -> keymaps.Keymap:
return keymaps.build(layout="de")
def shift_mask(keymap: keymaps.Keymap) -> int:
"""Shift's bit, asked of the keymap rather than assumed to be 1."""
return 1 << keymap._keymap.mod_get_index("Shift")
# -- the letter path --------------------------------------------------------
def test_a_lower_case_letter_is_its_evdev_code_and_no_modifier(us):
action = us.resolve_name("a")
assert (action.code, action.mask) == (KEY_A, 0)
def test_a_capital_is_the_same_code_with_shift_in_the_mask(us):
action = us.resolve_name("A")
assert action.code == KEY_A
assert action.mask == shift_mask(us)
# The point of the mask: a capital is NOT a Shift keycode. Hyprland's
# virtual keyboard never runs updateXkbStateWithKey, so a synthetic
# KEY_LEFTSHIFT would change no modifier state at all.
assert action.code != KEY_LEFTSHIFT
def test_shift_is_a_key_in_its_own_right_with_no_mask_of_its_own(us):
action = us.resolve_name("Shift_L")
# Pressing Shift needs no modifier held; what it *contributes* is separate.
assert (action.code, action.mask) == (KEY_LEFTSHIFT, 0)
assert us.is_modifier("Shift_L")
assert us.modifier_mask("Shift_L") == shift_mask(us)
# -- the named keys ---------------------------------------------------------
@pytest.mark.parametrize(
"name, code",
[("Return", KEY_ENTER), ("Tab", KEY_TAB), ("BackSpace", 14), ("Left", 105)],
)
def test_a_named_keysym_resolves_to_its_evdev_code(us, name, code):
assert us.resolve_name(name).code == code
@pytest.mark.parametrize("character, code", [("\n", KEY_ENTER), ("\t", KEY_TAB)])
def test_the_two_allowed_control_characters_are_named_keys(us, character, code):
(action,) = us.resolve_text(character)
assert action.code == code
assert action.mask == 0
def test_a_carriage_return_is_refused_rather_than_aliased_to_return(us):
"""Only `\n` and `\t` are exempt from the C0 rule.
A `\r` silently typed as Return means a caller who pasted CRLF gets two
newlines per line and no way to find out, so it is refused with the rest
of the C0 block.
"""
with pytest.raises(keymaps.UnknownKey) as caught:
us.resolve_text("\r")
assert "scalar 0" in str(caught.value)
assert "U+000D" in str(caught.value)
def test_an_empty_string_is_no_actions_and_not_an_error(us):
assert us.resolve_text("") == []
# -- refusals ---------------------------------------------------------------
@pytest.mark.parametrize("character", ["é", "ü", "😀", "\x01", "\x1b", "\x7f"])
def test_a_character_this_layout_cannot_produce_is_refused(us, character):
with pytest.raises(keymaps.UnknownKey) as caught:
us.resolve_text(character)
message = str(caught.value)
# The index and the codepoint, and NOT the character: this message reaches
# the driver's log, and the string it came from is a password as often as
# not.
assert "scalar 0" in message
assert character not in message
def test_the_refusal_names_the_index_of_the_offending_scalar(us):
with pytest.raises(keymaps.UnknownKey) as caught:
us.resolve_text("abcé")
assert "scalar 3" in str(caught.value)
assert "é" not in str(caught.value)
def test_a_dead_keysym_is_refused_by_name(us):
with pytest.raises(keymaps.UnknownKey) as caught:
us.resolve_name("dead_acute")
assert "dead key" in str(caught.value)
def test_an_unknown_keysym_name_is_refused(us):
with pytest.raises(keymaps.UnknownKey):
us.resolve_name("NoSuchKeysymAtAll")
def test_an_empty_layout_is_refused_rather_than_compiled_as_us():
"""xkbcommon compiles `""` as the *same keymap as `us`*.
So `--xkb-layout ''` would look configured, type `us`, and never say
otherwise -- the same class of silent-wrong-layout as the comma below.
"""
with pytest.raises(keymaps.KeymapError) as caught:
keymaps.build(layout="")
assert "layout" in str(caught.value)
def test_a_comma_separated_layout_is_refused_before_anything_is_compiled():
# xkbcommon accepts `us,ru` happily and hands back a two-group keymap. v1
# always sends group 0, so the second group would be silently unreachable:
# a caller asking for Cyrillic would get Latin and no error.
with pytest.raises(keymaps.KeymapError) as caught:
keymaps.build(layout="us,ru")
assert "group" in str(caught.value)
def test_a_layout_xkbcommon_rejects_is_a_keymap_error_naming_it():
with pytest.raises(keymaps.KeymapError) as caught:
keymaps.build(layout="zzz-no-such-layout")
assert "zzz-no-such-layout" in str(caught.value)
# -- the cap ----------------------------------------------------------------
def test_the_cap_is_exactly_at_the_limit(us):
assert len(us.resolve_text("a" * keymaps.MAX_TEXT_SCALARS)) == keymaps.MAX_TEXT_SCALARS
def test_one_scalar_over_the_cap_is_refused(us):
with pytest.raises(keymaps.UnknownKey) as caught:
us.resolve_text("a" * (keymaps.MAX_TEXT_SCALARS + 1))
assert str(keymaps.MAX_TEXT_SCALARS) in str(caught.value)
def test_the_cap_counts_scalars_and_not_bytes(us):
# 4096 astral-plane scalars are 16384 UTF-8 bytes. A byte cap would refuse
# this for being too long; the scalar cap lets it through to the character
# check, which refuses it for being unmappable instead. The distinction is
# the whole test: a byte cap and a scalar cap agree on ASCII, so only a
# non-ASCII case can tell them apart.
text = "😀" * keymaps.MAX_TEXT_SCALARS
assert len(text) == keymaps.MAX_TEXT_SCALARS
assert len(text.encode("utf-8")) > keymaps.MAX_TEXT_SCALARS
with pytest.raises(keymaps.UnknownKey) as caught:
us.resolve_text(text)
assert "scalar 0" in str(caught.value)
assert "limit" not in str(caught.value)
# -- the modifier set -------------------------------------------------------
def test_the_modifier_set_is_measured_and_not_empty(us):
assert us.modifier_names() == keymaps.EXPECTED_MODIFIERS
def test_a_lock_is_not_a_modifier(us):
# Caps_Lock reports a *locked* mask, so `type` refuses while it is held
# rather than producing a case nobody asked for.
assert us.lock_names() == keymaps.EXPECTED_LOCKS
for name in keymaps.EXPECTED_LOCKS:
assert not us.is_modifier(name)
assert us.modifier_mask(name) == 0
def test_control_contributes_the_bit_the_keymap_gives_control(us):
"""The *right* bit, not merely a different one from Shift's.
"not 0 and not Shift" is satisfied by Alt's bit, and every wire assertion
compares against `modifier_mask(...)` -- so a consistently wrong bit would
be consistently wrong and green. This asks the keymap for the index.
"""
expected = 1 << us._keymap.mod_get_index("Control")
assert us.modifier_mask("Control_L") == expected
assert us.modifier_mask("Control_R") == expected
assert expected not in (0, shift_mask(us))
# -- a second layout, which is what stops a Shift special case ---------------
def test_de_swaps_y_and_z_against_us(us, de):
assert (us.resolve_name("y").code, us.resolve_name("z").code) == (KEY_Y, KEY_Z)
# Same keysyms, other codes: a resolver with a table beside the keymap
# rather than inside it would return the us answer here.
assert (de.resolve_name("y").code, de.resolve_name("z").code) == (KEY_Z, KEY_Y)
def test_on_de_the_at_sign_needs_a_level_three_mask_not_shift(us, de):
at_us = us.resolve_text("@")[0]
at_de = de.resolve_text("@")[0]
assert at_us.mask == shift_mask(us)
# The case a Shift-only special case gets wrong: `@` is AltGr+q on de.
assert at_de.mask not in (0, shift_mask(de))
assert at_de.mask == de.modifier_mask("ISO_Level3_Shift")
def test_a_character_us_cannot_type_is_ordinary_on_de(us, de):
with pytest.raises(keymaps.UnknownKey):
us.resolve_text("ü")
(action,) = de.resolve_text("ü")
assert action.name == "udiaeresis"
assert action.mask == 0
# -- the keymap text we upload ----------------------------------------------
def test_the_keymap_text_is_an_xkb_keymap_naming_its_layout(us, de):
assert us.text().lstrip().startswith("xkb_keymap {")
# The exact symbols names, not `"us" in ...` -- which is true of every
# us-family map and would stay true of a `de` keymap that had silently
# compiled as `us`. These are also the strings the VM check should grep,
# so they are written down once here.
assert 'xkb_symbols "pc_us_inet(evdev)"' in _symbols_line(us)
assert 'xkb_symbols "pc_de_inet(evdev)"' in _symbols_line(de)
def _symbols_line(keymap: keymaps.Keymap) -> str:
return next(line for line in keymap.text().splitlines() if "xkb_symbols" in line)
# -- through the dispatcher: nothing is emitted for a bad string -------------
class _Sink:
"""Just enough of :class:`hhstream_pointer.ops.PointerSink` to count calls."""
def __init__(self) -> None:
self.calls: list[tuple] = []
def has_keyboard(self) -> bool:
return True
def key(self, code, state):
self.calls.append(("key", code, state))
def modifiers(self, depressed, latched, locked, group):
self.calls.append(("modifiers", depressed, latched, locked, group))
def test_an_unmappable_character_emits_nothing_through_the_dispatcher(us):
sink = _Sink()
reply = Dispatcher(sink, us).handle({"op": "type", "text": "abcé"})
assert reply["ok"] is False
# The assertion that matters: not "no event carried é" -- which would also
# pass if a, b and c had been typed -- but that the sink was never called.
assert sink.calls == []
assert reply["kind"] == KIND_INVALID
def test_a_string_over_the_cap_emits_nothing_through_the_dispatcher(us):
sink = _Sink()
reply = Dispatcher(sink, us).handle(
{"op": "type", "text": "a" * (keymaps.MAX_TEXT_SCALARS + 1)}
)
assert reply["ok"] is False
assert reply["kind"] == KIND_INVALID
assert sink.calls == []
def test_the_keymap_object_is_built_once_and_reused_across_types(us):
"""Two ``type``s, one keymap.
The false pass this guards is a backend that recompiles and re-*uploads*
per string: a second ``keymap`` request replaces Hyprland's XKB state
without walking the keys it believes are down, so re-uploading under a held
modifier strands it. The dispatcher is handed one object and never asks for
another, which is what makes the single upload in ``__main__`` sufficient.
"""
sink = _Sink()
dispatcher = Dispatcher(sink, us)
assert dispatcher.handle({"op": "type", "text": "a"})["ok"] is True
assert dispatcher.handle({"op": "type", "text": "b"})["ok"] is True
assert dispatcher._keymap is us