Stage 1: the driver learns to type

`zwp_virtual_keyboard_v1`, spoken by the process that already speaks
`zwlr_virtual_pointer_v1`. One device for the seat, one keymap uploaded
once, keysym names on our socket and evdev codes only on the Wayland
request -- the division buttons.py already draws.

keymap.py is the new seam, and it holds the three decisions that have a
wrong version which looks right:

  * A capital is the MASK, not a synthetic Shift keycode. Hyprland's
    virtual keyboard never runs updateXkbStateWithKey, so a virtual
    KEY_LEFTSHIFT changes no modifier state at all -- and sending both
    is how a toolkit applies Shift twice.
  * A modifier is whatever the keymap says is one, measured by pressing
    each key in a throwaway xkb state. Not a name list: `@` on `de` is a
    level-three symbol, and a Shift-only special case types the wrong
    character. (The measured set is also smaller than the canonical one,
    because no keycode on us/pc105 carries Meta or Hyper.)
  * A lock is not a modifier. Caps_Lock reports a *locked* mask, so
    `type` refuses while it is held rather than guessing the case.

The whole string resolves before anything is emitted, and every refusal
names the scalar INDEX, never the character: these messages reach the
driver's log and the string is a password as often as not.

Folding in the review's changes 1, 2, 3 and 6:

  1 a Rejected now carries a `kind`. A bad keysym or an unmappable
    character is `invalid_argument`; a missing keyboard global is
    `refused`. Without the token the broker would have to tell exit 2
    from exit 10 by reading English, and _drive maps every `ok: false`
    to driver_refused today.
  2 the keymap `size` on the wire includes the trailing NUL, and the fd
    outlives a roundtrip rather than a flush. Hyprland mmaps exactly
    that many bytes and hands the pointer to xkb_keymap_new_from_string.
  3 release_all lifts buttons, then keys in press order, then zeroes the
    mask -- and the mask only if something set it, so a compositor with
    no keyboard global still gets its buttons lifted. One release_all is
    the whole of expiry; an exception in the key half would abandon it.
  6 `key` and `type` never call _aimed(). A keyboard has no output, and
    one test deliberately never warps so that stays true.

Also: `--xkb-layout/-model/-variant/-options`, compiled BEFORE any
Wayland call so a bad layout is exit 2 rather than exit 10; a comma in
the layout refused outright, because v1 always sends group 0 and
xkbcommon would hand back a second group nothing could reach; the
keymap uploaded after connect and before listen, with one
modifiers(0,0,0,0) after it; and xkbcommon as a hard, non-optional
dependency -- an optional one would let test_keymap.py skip, and the
unmappable-character path is the one that must not rot.

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GhNPM6rGcuzxocM1nATnuM
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-10-04 03:39:00 +00:00
1 parent 19e484b388
commit f931858f30
19 files changed
+2461 -107

No files matched your search

+438 -17
View File
@@ -13,17 +13,34 @@ from __future__ import annotations
import pytest
from hhstream_pointer import buttons
from hhstream_pointer.ops import Dispatcher
from hhstream_pointer import buttons, keymap as keymaps
from hhstream_pointer.ops import KIND_INVALID, KIND_REFUSED, Dispatcher
LEFT = buttons.CODES["left"]
RIGHT = buttons.CODES["right"]
DOWN = buttons.STATES["down"]
UP = buttons.STATES["up"]
#: evdev codes, from ``linux/input-event-codes.h``. Asserted as the integers
#: the wire carries, never as XKB codes: ``a`` is 30 there and 38 in xkbcommon's
#: tables, and only one of the two ever leaves this process.
KEY_A = 30
KEY_B = 48
KEY_ENTER = 28
KEY_LEFTSHIFT = 42
KEY_LEFTCTRL = 29
class RecordingSink:
"""Every call, in order, as a tuple. Nothing else."""
"""Every call, in order, as a tuple. Nothing else.
``has_keyboard`` answers True by default because most tests want one. The
keyboard calls carry **no output**: a virtual keyboard is seat-global, and
a sink that tagged them with one would be hiding the fact that a key after
a warp to another output still goes to whatever has focus.
"""
keyboard = True
def __init__(self) -> None:
self.calls: list[tuple] = []
@@ -40,6 +57,31 @@ class RecordingSink:
def frame(self, output):
self.calls.append(("frame", output))
def has_keyboard(self):
return self.keyboard
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))
class KeyboardlessSink(RecordingSink):
"""A compositor with no ``zwp_virtual_keyboard_manager_v1``.
Not a failing sink: the methods are simply never meant to be reached, and
a call that got through would be the bug.
"""
keyboard = False
def key(self, code, state):
raise AssertionError("no virtual keyboard exists; key must not be sent")
def modifiers(self, depressed, latched, locked, group):
raise AssertionError("no virtual keyboard exists; modifiers must not be sent")
class FailingSink(RecordingSink):
"""A sink whose motion raises, standing in for an output that vanished."""
@@ -56,9 +98,21 @@ def sink() -> RecordingSink:
return RecordingSink()
@pytest.fixture(scope="module")
def us() -> keymaps.Keymap:
"""A real ``us`` keymap.
Real, not a fake, for the reason ``test_keymap.py`` gives at length: the
mask for ``A`` and the refusal of ``é`` are properties of the layout, and a
fake that agreed with the dispatcher would prove only that they agree.
"""
return keymaps.build(layout="us")
@pytest.fixture
def driver(sink) -> Dispatcher:
return Dispatcher(sink)
def driver(sink, us) -> Dispatcher:
return Dispatcher(sink, us)
def warp(driver, output="hh-alpha", x=0.5, y=0.5):
@@ -90,7 +144,7 @@ def test_a_click_is_warp_button_frame(driver, sink):
("button", "hh-alpha", LEFT, UP),
("frame", "hh-alpha"),
]
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": []}
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": [], "keys": []}
def test_the_boundary_coordinates_are_accepted(driver, sink):
@@ -160,7 +214,11 @@ def test_pressed_reports_what_is_down_oldest_first(driver):
warp(driver)
driver.handle({"op": "button", "button": "right", "state": "down"})
driver.handle({"op": "button", "button": "left", "state": "down"})
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": ["right", "left"]}
assert driver.handle({"op": "pressed"}) == {
"ok": True,
"buttons": ["right", "left"],
"keys": [],
}
def test_release_all_lifts_everything_and_frames_once(driver, sink):
@@ -169,17 +227,28 @@ def test_release_all_lifts_everything_and_frames_once(driver, sink):
driver.handle({"op": "button", "button": "right", "state": "down"})
sink.calls.clear()
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": ["left", "right"]}
assert driver.handle({"op": "release_all"}) == {
"ok": True,
"lifted": ["left", "right"],
"lifted_keys": [],
}
assert sink.calls == [
("button", "hh-alpha", LEFT, UP),
("button", "hh-alpha", RIGHT, UP),
("frame", "hh-alpha"),
]
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": []}
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": [], "keys": []}
def test_release_all_on_a_quiet_driver_lifts_nothing(driver, sink):
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": []}
assert driver.handle({"op": "release_all"}) == {
"ok": True,
"lifted": [],
"lifted_keys": [],
}
# Including no zeroed `modifiers`: a mask nothing ever set is not ours to
# clear, and on a sink with no keyboard at all sending one would raise and
# abandon the button lifting above.
assert sink.calls == []
@@ -196,7 +265,11 @@ def test_release_all_lifts_through_the_pointer_the_press_went_to(driver, sink):
driver.handle({"op": "button", "button": "right", "state": "down"})
sink.calls.clear()
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": ["left", "right"]}
assert driver.handle({"op": "release_all"}) == {
"ok": True,
"lifted": ["left", "right"],
"lifted_keys": [],
}
assert sink.calls == [
("button", "hh-alpha", LEFT, UP),
("button", "hh-beta", RIGHT, UP),
@@ -209,7 +282,11 @@ def test_a_lifted_button_is_forgotten(driver):
warp(driver)
driver.handle({"op": "button", "button": "left", "state": "down"})
driver.handle({"op": "button", "button": "left", "state": "up"})
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": []}
assert driver.handle({"op": "release_all"}) == {
"ok": True,
"lifted": [],
"lifted_keys": [],
}
def test_every_known_button_name_round_trips(driver, sink):
@@ -227,6 +304,10 @@ def test_button_before_any_warp_is_refused(driver, sink):
assert driver.handle({"op": "button", "button": "left", "state": "down"}) == {
"ok": False,
"error": "no output is aimed; warp before button or frame",
# `refused` and not `invalid_argument`: the request was well formed,
# what is missing is a warp, and the broker reports that as exit 10
# exactly as it already does for an unknown button.
"kind": "refused",
}
assert sink.calls == []
@@ -277,8 +358,8 @@ def test_a_failed_warp_does_not_change_the_aim():
({"op": "axis", "value": -1e9}, "wheel-click limit"),
],
)
def test_malformed_requests_are_answered_not_fatal(sink, request_, fragment):
driver = Dispatcher(sink)
def test_malformed_requests_are_answered_not_fatal(sink, us, request_, fragment):
driver = Dispatcher(sink, us)
# Aim first, so a refusal is about the field under test rather than the aim.
warp(driver)
sink.calls.clear()
@@ -300,9 +381,11 @@ def test_the_contracts_ops_are_exactly_what_is_implemented() -> None:
An op that exists here and nowhere in the contract -- or the reverse --
fails this test rather than surprising whoever reads the contract next.
``axis`` is the one addition since the freeze, made deliberately so that a
session can scroll; the set is edited by hand, which is the reminder to
write it down.
``axis`` was the first addition since the freeze, so a session could
scroll; ``key`` and ``type`` are the second, and there is deliberately no
keyboard ``frame`` or ``release_all_keys`` beside them -- the protocol has
no frame, and expiry has exactly one call site. The set is edited by hand,
which is the reminder to write it down.
"""
assert set(Dispatcher._ops) == {
@@ -310,6 +393,344 @@ def test_the_contracts_ops_are_exactly_what_is_implemented() -> None:
"button",
"axis",
"frame",
"key",
"type",
"pressed",
"release_all",
}
# -- key: one keysym at a time ----------------------------------------------
#
# Names on this socket, evdev codes on the Wayland request -- the same division
# `buttons.py` draws, and the reason `pressed` answers "Control_L" rather than
# 29. These tests assert both halves: the response names, the sink codes.
def test_key_down_sends_the_code_and_lists_the_name(driver, sink):
assert driver.handle({"op": "key", "key": "Return", "state": "down"}) == {
"ok": True,
"keys": ["Return"],
"lifted": [],
}
assert sink.calls == [("key", KEY_ENTER, DOWN)]
assert driver.handle({"op": "pressed"})["keys"] == ["Return"]
def test_key_needs_no_warp(sink, us):
"""A keyboard has no output, so `type` must not demand an aim.
Deliberately the one test in this file that never warps: a virtual keyboard
is seat-global, so requiring a warp first would refuse a caller who only
ever wanted to type -- and every other test here warps out of habit, which
is exactly how that bug would survive.
"""
driver = Dispatcher(sink, us)
assert driver.handle({"op": "type", "text": "Hi"})["ok"] is True
assert driver.handle({"op": "key", "key": "a", "state": "down"})["ok"] is True
assert ("key", KEY_A, DOWN) in sink.calls
def test_a_key_is_not_tagged_with_an_output_even_after_a_warp(driver, sink):
warp(driver, output="hh-beta")
sink.calls.clear()
driver.handle({"op": "key", "key": "a", "state": "down"})
# Two items, not three: no output travels with a key. A sink that accepted
# one would let a future change route keys per output, which the protocol
# cannot do.
assert sink.calls == [("key", KEY_A, DOWN)]
def test_key_up_forgets_the_key(driver, sink):
driver.handle({"op": "key", "key": "a", "state": "down"})
assert driver.handle({"op": "key", "key": "a", "state": "up"}) == {
"ok": True,
"keys": [],
"lifted": ["a"],
}
assert sink.calls == [("key", KEY_A, DOWN), ("key", KEY_A, UP)]
def test_up_of_a_key_that_was_never_down_lifts_nothing_and_emits_nothing(driver, sink):
"""Same rule as `unpress` for a button that was never pressed.
Reported rather than invented, and silent on the wire: a key-up the
compositor has no matching key-down for puts its own `m_pressed` out of
step with ours, and on this build that makes the *next* press of the code
a no-op.
"""
assert driver.handle({"op": "key", "key": "a", "state": "up"}) == {
"ok": True,
"keys": [],
"lifted": [],
}
assert sink.calls == []
def test_keys_are_reported_oldest_first(driver):
for name in ("Control_L", "Shift_L", "a"):
driver.handle({"op": "key", "key": name, "state": "down"})
assert driver.handle({"op": "pressed"})["keys"] == ["Control_L", "Shift_L", "a"]
# -- the modifier half, which a key-up does not undo ------------------------
def test_a_modifier_down_sends_the_key_and_the_mask(driver, sink, us):
driver.handle({"op": "key", "key": "Shift_L", "state": "down"})
assert sink.calls == [
("key", KEY_LEFTSHIFT, DOWN),
("modifiers", us.modifier_mask("Shift_L"), 0, 0, 0),
]
def test_a_modifier_up_restores_the_mask_of_whatever_is_still_held(driver, sink, us):
driver.handle({"op": "key", "key": "Shift_L", "state": "down"})
driver.handle({"op": "key", "key": "Control_L", "state": "down"})
sink.calls.clear()
driver.handle({"op": "key", "key": "Shift_L", "state": "up"})
# Not zero: Control is still down, so the mask drops to Control's bit
# alone. A key-up changes no modifier state on this compositor, so the
# mask is only ever what we last said it was.
assert sink.calls == [
("key", KEY_LEFTSHIFT, UP),
("modifiers", us.modifier_mask("Control_L"), 0, 0, 0),
]
def test_an_ordinary_key_down_sends_no_mask(driver, sink):
driver.handle({"op": "key", "key": "a", "state": "down"})
assert sink.calls == [("key", KEY_A, DOWN)]
# -- type -------------------------------------------------------------------
def test_type_of_a_capital_is_the_mask_and_not_a_shift_keycode(driver, sink, us):
assert driver.handle({"op": "type", "text": "A"}) == {"ok": True, "keys": []}
shift = us.modifier_mask("Shift_L")
assert sink.calls == [
# The mask goes FIRST. A client that decodes with the mask from the
# last `wl_keyboard.modifiers` -- foot, GTK -- emits `a` if the key
# arrives before the mask.
("modifiers", shift, 0, 0, 0),
("key", KEY_A, DOWN),
("key", KEY_A, UP),
("modifiers", 0, 0, 0, 0),
]
# And no synthetic Shift key anywhere: sending both a mask and KEY_LEFTSHIFT
# is how a toolkit applies Shift twice, or not at all.
assert not any(call[0] == "key" and call[1] == KEY_LEFTSHIFT for call in sink.calls)
def test_type_leaves_no_key_held(driver):
driver.handle({"op": "type", "text": "Hello"})
assert driver.handle({"op": "pressed"})["keys"] == []
def test_type_emits_a_down_up_pair_per_character(driver, sink):
driver.handle({"op": "type", "text": "ab"})
assert [c for c in sink.calls if c[0] == "key"] == [
("key", KEY_A, DOWN),
("key", KEY_A, UP),
("key", KEY_B, DOWN),
("key", KEY_B, UP),
]
def test_type_of_an_empty_string_emits_nothing_and_succeeds(driver, sink):
assert driver.handle({"op": "type", "text": ""}) == {"ok": True, "keys": []}
assert sink.calls == []
def test_type_ors_an_explicitly_held_modifier_and_leaves_it_down(driver, sink, us):
"""`down Control_L` then `type c` is Ctrl+C, and Control is still down."""
driver.handle({"op": "key", "key": "Control_L", "state": "down"})
sink.calls.clear()
assert driver.handle({"op": "type", "text": "c"}) == {"ok": True, "keys": ["Control_L"]}
control = us.modifier_mask("Control_L")
assert sink.calls == [
("modifiers", control, 0, 0, 0),
("key", us.resolve_name("c").code, DOWN),
("key", us.resolve_name("c").code, UP),
# Back to the BASELINE, not to zero: Control was not ours to lift.
("modifiers", control, 0, 0, 0),
]
assert not any(call[0] == "key" and call[1] == KEY_LEFTCTRL for call in sink.calls)
assert driver.handle({"op": "pressed"})["keys"] == ["Control_L"]
def test_type_of_a_capital_under_a_held_control_ors_both_masks(driver, sink, us):
driver.handle({"op": "key", "key": "Control_L", "state": "down"})
sink.calls.clear()
driver.handle({"op": "type", "text": "A"})
both = us.modifier_mask("Control_L") | us.modifier_mask("Shift_L")
assert sink.calls[0] == ("modifiers", both, 0, 0, 0)
assert sink.calls[-1] == ("modifiers", us.modifier_mask("Control_L"), 0, 0, 0)
def test_type_while_a_non_modifier_is_held_emits_nothing(driver, sink):
driver.handle({"op": "key", "key": "a", "state": "down"})
sink.calls.clear()
reply = driver.handle({"op": "type", "text": "bc"})
assert reply["ok"] is False
assert reply["kind"] == KIND_INVALID
assert sink.calls == []
# And the held key is untouched: a refused request changes nothing.
assert driver.handle({"op": "pressed"})["keys"] == ["a"]
def test_type_while_a_lock_is_held_is_refused_too(driver, sink):
"""Caps_Lock reports a *locked* mask, so it is not a modifier.
Typing under it would produce a case the caller did not ask for, and v1
refuses rather than guessing which one they meant.
"""
driver.handle({"op": "key", "key": "Caps_Lock", "state": "down"})
sink.calls.clear()
assert driver.handle({"op": "type", "text": "a"})["ok"] is False
assert sink.calls == []
def test_a_string_that_fails_on_its_third_character_emits_nothing(driver, sink):
reply = driver.handle({"op": "type", "text": "abé"})
assert reply["ok"] is False
# Not "no event carried é" -- that would also pass with a and b typed.
assert sink.calls == []
def test_a_bad_character_is_a_usage_error_and_a_missing_keyboard_is_not(sink, us):
"""The two refusals the broker must tell apart (the review's change 1).
An unmappable character is the caller's; a compositor with no keyboard
global is not. They become exit 2 and exit 10, and the only thing carrying
the difference across the socket is this token.
"""
usable = Dispatcher(sink, us)
assert usable.handle({"op": "type", "text": "é"})["kind"] == KIND_INVALID
assert usable.handle({"op": "key", "key": "Nope", "state": "down"})["kind"] == KIND_INVALID
assert usable.handle({"op": "key", "key": "a", "state": "sideways"})["kind"] == KIND_INVALID
absent = Dispatcher(KeyboardlessSink(), us)
assert absent.handle({"op": "type", "text": "a"})["kind"] == KIND_REFUSED
assert absent.handle({"op": "key", "key": "a", "state": "down"})["kind"] == KIND_REFUSED
def test_without_a_keymap_at_all_the_keyboard_ops_refuse_and_the_cursor_works(sink):
"""A driver started with no layout still moves the cursor."""
driver = Dispatcher(sink, None)
assert warp(driver)["ok"] is True
assert driver.handle({"op": "button", "button": "left", "state": "down"})["ok"] is True
reply = driver.handle({"op": "type", "text": "a"})
assert reply["ok"] is False and reply["kind"] == KIND_REFUSED
# -- release_all, with keys ------------------------------------------------
def test_release_all_lifts_keys_in_press_order_then_zeroes_the_mask(driver, sink):
driver.handle({"op": "key", "key": "Control_L", "state": "down"})
driver.handle({"op": "key", "key": "a", "state": "down"})
sink.calls.clear()
assert driver.handle({"op": "release_all"}) == {
"ok": True,
"lifted": [],
"lifted_keys": ["Control_L", "a"],
}
assert sink.calls == [
("key", KEY_LEFTCTRL, UP),
("key", KEY_A, UP),
# The part that is easy to leave out. A virtual key-up clears no
# modifier state, so without this the next holder gets a keyboard
# where every letter is a capital.
("modifiers", 0, 0, 0, 0),
]
assert driver.handle({"op": "pressed"})["keys"] == []
def test_release_all_lifts_keys_after_buttons_and_adds_no_keyboard_frame(driver, sink):
warp(driver)
driver.handle({"op": "button", "button": "left", "state": "down"})
driver.handle({"op": "key", "key": "Shift_L", "state": "down"})
sink.calls.clear()
driver.handle({"op": "release_all"})
assert sink.calls == [
("button", "hh-alpha", LEFT, UP),
("frame", "hh-alpha"),
("key", KEY_LEFTSHIFT, UP),
("modifiers", 0, 0, 0, 0),
]
# Exactly one frame, for the pointer. `zwp_virtual_keyboard_v1` has none,
# and a key that waited for one would never arrive.
assert sum(1 for call in sink.calls if call[0] == "frame") == 1
def test_release_all_lifts_keys_even_after_a_warp_to_another_output(driver, sink):
"""Keys are not per output, and this is the test that says so.
The button path has to lift through the pointer the press went to; the key
path has nothing to choose, and a sink that silently ignored an output
argument would make a per-output implementation look correct here.
"""
warp(driver, output="hh-alpha")
driver.handle({"op": "key", "key": "a", "state": "down"})
warp(driver, output="hh-beta")
sink.calls.clear()
assert driver.handle({"op": "release_all"})["lifted_keys"] == ["a"]
assert sink.calls == [("key", KEY_A, UP)]
def test_release_all_without_a_keyboard_still_lifts_buttons(us):
"""The review's change 3, and the reason the mask is conditional.
`SessionManager._expire_pointer` calls `release_all` exactly once, so an
exception from the key half would abandon the buttons -- and a lease that
expired with a mouse button down is the failure the whole TTL exists to
prevent.
"""
sink = KeyboardlessSink()
driver = Dispatcher(sink, us)
warp(driver)
driver.handle({"op": "button", "button": "left", "state": "down"})
sink.calls.clear()
assert driver.handle({"op": "release_all"}) == {
"ok": True,
"lifted": ["left"],
"lifted_keys": [],
}
assert sink.calls == [("button", "hh-alpha", LEFT, UP), ("frame", "hh-alpha")]
def test_release_all_after_a_type_zeroes_the_mask_once_more(driver, sink):
"""A `type` restored the baseline itself, and `release_all` still zeroes.
Cheap, and it is the crash-mid-string case: the mask the last character set
is the compositor's until something says otherwise.
"""
driver.handle({"op": "type", "text": "A"})
sink.calls.clear()
driver.handle({"op": "release_all"})
assert sink.calls == [("modifiers", 0, 0, 0, 0)]