Files
hyprland-headless-stream-pl…/tests/pointer/test_ops.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

854 lines
31 KiB
Python

"""The driver's protocol (CONTRACT-sessions.md §3.4).
The dispatcher is tested against a recording sink rather than a compositor, so
these assertions are about the exact events that would go on the wire: which
pointer they go to, in what order, and which requests are refused instead.
The driver is an executor. It is *not* tested for serialisation, authority, or
any notion of who may ask — none of that is here, on purpose. The lease is in
``hhstreamd.pointer`` and the broker owns it.
"""
from __future__ import annotations
import pytest
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.
``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] = []
def motion_absolute(self, output, x, y):
self.calls.append(("motion", output, x, y))
def button(self, output, code, state):
self.calls.append(("button", output, code, state))
def axis(self, output, axis, value):
self.calls.append(("axis", output, axis, value))
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."""
class Boom(Exception):
pass
def motion_absolute(self, output, x, y):
raise FailingSink.Boom(output)
@pytest.fixture
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, us) -> Dispatcher:
return Dispatcher(sink, us)
def warp(driver, output="hh-alpha", x=0.5, y=0.5):
return driver.handle({"op": "warp", "output": output, "x": x, "y": y})
# -- happy paths ------------------------------------------------------------
def test_warp_sends_one_motion_and_no_implicit_frame(driver, sink):
assert warp(driver, x=0.42, y=0.61) == {"ok": True}
assert sink.calls == [("motion", "hh-alpha", 0.42, 0.61)]
def test_frame_is_a_separate_op(driver, sink):
warp(driver)
assert driver.handle({"op": "frame"}) == {"ok": True}
assert sink.calls[-1] == ("frame", "hh-alpha")
def test_a_click_is_warp_button_frame(driver, sink):
warp(driver, x=0.25, y=0.75)
driver.handle({"op": "button", "button": "left", "state": "down"})
driver.handle({"op": "button", "button": "left", "state": "up"})
driver.handle({"op": "frame"})
assert sink.calls == [
("motion", "hh-alpha", 0.25, 0.75),
("button", "hh-alpha", LEFT, DOWN),
("button", "hh-alpha", LEFT, UP),
("frame", "hh-alpha"),
]
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": [], "keys": []}
def test_the_boundary_coordinates_are_accepted(driver, sink):
assert warp(driver, x=0.0, y=0.0) == {"ok": True}
assert warp(driver, x=1.0, y=1.0) == {"ok": True}
# Integers are numbers too; 0 and 1 are the corners.
assert warp(driver, x=0, y=1) == {"ok": True}
assert [c[2:] for c in sink.calls] == [(0.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
def test_buttons_follow_the_last_warp_not_the_first(driver, sink):
warp(driver, output="hh-alpha")
warp(driver, output="hh-beta")
driver.handle({"op": "button", "button": "left", "state": "down"})
assert sink.calls[-1] == ("button", "hh-beta", LEFT, DOWN)
# -- axis (scrolling) -------------------------------------------------------
def test_axis_scrolls_the_aimed_output_and_sends_no_implicit_frame(driver, sink):
warp(driver)
sink.calls.clear()
assert driver.handle({"op": "axis", "axis": "vertical", "value": 3}) == {"ok": True}
assert sink.calls == [("axis", "hh-alpha", buttons.AXES["vertical"], 3.0)]
def test_axis_defaults_to_one_vertical_click(driver, sink):
warp(driver)
sink.calls.clear()
assert driver.handle({"op": "axis"}) == {"ok": True}
assert sink.calls == [("axis", "hh-alpha", buttons.AXES["vertical"], 1.0)]
def test_a_horizontal_scroll_is_the_other_axis_and_keeps_the_sign(driver, sink):
warp(driver)
sink.calls.clear()
assert driver.handle({"op": "axis", "axis": "horizontal", "value": -2}) == {"ok": True}
assert sink.calls == [("axis", "hh-alpha", buttons.AXES["horizontal"], -2.0)]
# Two names, two axes -- and positive is down/right, per the protocol rather
# than per us, which is why direction travels in the sign and not the name.
assert buttons.AXES["vertical"] != buttons.AXES["horizontal"]
def test_a_scroll_goes_to_the_pointer_the_last_warp_aimed(driver, sink):
warp(driver, output="hh-alpha")
warp(driver, output="hh-beta")
sink.calls.clear()
driver.handle({"op": "axis", "value": 5})
assert sink.calls == [("axis", "hh-beta", buttons.AXES["vertical"], 5.0)]
def test_scroll_before_any_warp_is_refused(driver, sink):
assert driver.handle({"op": "axis", "value": 3})["ok"] is False
assert sink.calls == [], "a scroll with nothing aimed must emit nothing"
# -- pressed / release_all --------------------------------------------------
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"],
"keys": [],
}
def test_release_all_lifts_everything_and_frames_once(driver, sink):
warp(driver)
driver.handle({"op": "button", "button": "left", "state": "down"})
driver.handle({"op": "button", "button": "right", "state": "down"})
sink.calls.clear()
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": [], "keys": []}
def test_release_all_on_a_quiet_driver_lifts_nothing(driver, sink):
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 == []
def test_release_all_lifts_through_the_pointer_the_press_went_to(driver, sink):
"""The expiry path: the broker lifts after the cursor has moved on.
A button pressed on one output must come up on that output's pointer, not
on whatever is aimed now, or the first session keeps a stuck drag.
"""
warp(driver, output="hh-alpha")
driver.handle({"op": "button", "button": "left", "state": "down"})
warp(driver, output="hh-beta")
driver.handle({"op": "button", "button": "right", "state": "down"})
sink.calls.clear()
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),
("frame", "hh-alpha"),
("frame", "hh-beta"),
]
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": [],
"lifted_keys": [],
}
def test_every_known_button_name_round_trips(driver, sink):
warp(driver)
for name in buttons.NAMES:
assert driver.handle({"op": "button", "button": name, "state": "down"}) == {"ok": True}
assert driver.handle({"op": "pressed"})["buttons"] == list(buttons.NAMES)
assert driver.handle({"op": "release_all"})["lifted"] == list(buttons.NAMES)
# -- refusals ---------------------------------------------------------------
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 == []
def test_frame_before_any_warp_is_refused(driver, sink):
assert driver.handle({"op": "frame"})["ok"] is False
assert sink.calls == []
def test_a_failed_warp_does_not_change_the_aim():
"""Otherwise the next button lands on a session we never reached."""
driver = Dispatcher(RecordingSink())
warp(driver, output="hh-alpha")
driver._sink = FailingSink()
with pytest.raises(FailingSink.Boom):
warp(driver, output="hh-beta")
driver._sink = sink = RecordingSink()
driver.handle({"op": "button", "button": "left", "state": "down"})
assert sink.calls == [("button", "hh-alpha", LEFT, DOWN)]
@pytest.mark.parametrize(
"request_, fragment",
[
({}, "no 'op'"),
({"op": 7}, "no 'op'"),
({"op": "nonsense"}, "unknown op 'nonsense'"),
({"op": "warp", "x": 0.5, "y": 0.5}, "'output' must be"),
({"op": "warp", "output": "", "x": 0.5, "y": 0.5}, "'output' must be"),
({"op": "warp", "output": "hh-a", "y": 0.5}, "'x' must be a number"),
({"op": "warp", "output": "hh-a", "x": "0.5", "y": 0.5}, "'x' must be a number"),
({"op": "warp", "output": "hh-a", "x": True, "y": 0.5}, "'x' must be a number"),
({"op": "warp", "output": "hh-a", "x": 1.5, "y": 0.5}, "outside 0..1"),
({"op": "warp", "output": "hh-a", "x": 0.5, "y": -0.1}, "outside 0..1"),
({"op": "button", "state": "down"}, "'button' must be a string"),
({"op": "button", "button": "left"}, "'state' must be"),
({"op": "button", "button": "pinky", "state": "down"}, "unknown button 'pinky'"),
({"op": "button", "button": "left", "state": "sideways"}, "unknown button state"),
({"op": "axis", "axis": "diagonal"}, "unknown axis 'diagonal'"),
({"op": "axis", "axis": 0}, "'axis' must be a string"),
({"op": "axis", "value": "a lot"}, "'value' must be a number"),
({"op": "axis", "value": True}, "'value' must be a number"),
({"op": "axis", "value": float("nan")}, "'value' must be finite"),
({"op": "axis", "value": 101}, "wheel-click limit"),
({"op": "axis", "value": -1e9}, "wheel-click limit"),
],
)
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()
response = driver.handle(request_)
assert response["ok"] is False
assert fragment in response["error"]
assert sink.calls == [], "a refused request must emit nothing"
@pytest.mark.parametrize("request_", [[], "warp", None, 7])
def test_a_non_object_request_is_refused(driver, request_):
assert driver.handle(request_)["ok"] is False
assert "must be a JSON object" in driver.handle(request_)["error"]
def test_the_contracts_ops_are_exactly_what_is_implemented() -> None:
"""The op set cannot drift quietly.
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`` 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) == {
"warp",
"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)]
def test_key_of_a_capital_sends_the_mask_the_symbol_needs(driver, sink, us):
"""`keyboard key A` must type `A`, not `a`.
The bug this locks: `key` resolved the action and then used only its
`code`, so a keysym above level 0 went on the wire as a bare keypress and
the window received the level-0 character. `A` typed `a`; on `de`, `at`
lost its level-three mask and typed `q`. `type` was the only path that used
the mask, so every `type` test stayed green.
"""
assert driver.handle({"op": "key", "key": "A", "state": "down"})["keys"] == ["A"]
assert sink.calls == [
# Mask first, exactly as `type` does it: a client that decodes with the
# mask from the last `wl_keyboard.modifiers` emits `a` otherwise.
("modifiers", us.modifier_mask("Shift_L"), 0, 0, 0),
("key", KEY_A, DOWN),
]
# And still no Shift keycode.
assert not any(c[0] == "key" and c[1] == KEY_LEFTSHIFT for c in sink.calls)
def test_the_up_of_a_capital_restores_the_baseline(driver, sink, us):
driver.handle({"op": "key", "key": "A", "state": "down"})
sink.calls.clear()
driver.handle({"op": "key", "key": "A", "state": "up"})
assert sink.calls == [("key", KEY_A, UP), ("modifiers", 0, 0, 0, 0)]
assert driver.handle({"op": "pressed"})["keys"] == []
def test_a_capital_is_not_treated_as_a_held_modifier(driver, sink):
"""`A` held is a held *letter*, so `type` must refuse under it.
The distinction is why the held record stores what a key *contributes*
rather than what it needs: storing `A`'s Shift requirement there would make
a held capital look like a held modifier, and `type` would carry on and OR
a Shift it did not ask for into every character.
"""
driver.handle({"op": "key", "key": "A", "state": "down"})
sink.calls.clear()
reply = driver.handle({"op": "type", "text": "b"})
assert reply["ok"] is False
assert reply["kind"] == KIND_INVALID
assert sink.calls == []
def test_two_names_for_one_keycode_cannot_both_be_held(driver, sink):
"""`A` and `a` are the same keycode at two levels.
Holding both sent `key(30, pressed)` twice. Hyprland drops the second
because the code is already in its `m_pressed`, then `release_all` sends
two ups of which one is also dropped -- so nothing visibly breaks and the
held set is a lie for as long as the lease lasts. A refusal is better.
"""
driver.handle({"op": "key", "key": "A", "state": "down"})
sink.calls.clear()
reply = driver.handle({"op": "key", "key": "a", "state": "down"})
assert reply["ok"] is False
assert reply["kind"] == KIND_INVALID
assert "same key" in reply["error"]
assert sink.calls == []
assert driver.handle({"op": "pressed"})["keys"] == ["A"]
def test_the_same_name_down_twice_is_still_one_key(driver):
"""Not a clash with itself: a repeated `down` is idempotent, as for buttons."""
driver.handle({"op": "key", "key": "a", "state": "down"})
assert driver.handle({"op": "key", "key": "a", "state": "down"})["ok"] is True
assert driver.handle({"op": "pressed"})["keys"] == ["a"]
def test_a_key_is_only_forgotten_after_the_up_reaches_the_sink(us):
"""Order matters here for the same reason it does for `button`.
If the name were dropped before the send, a raise from the sink would leave
us believing the key is up while the compositor still has it down -- and
`release_all` would not try again, because the set is empty.
"""
class _Breaking(RecordingSink):
def key(self, code, state):
if state == UP:
raise RuntimeError("the keyboard went away")
super().key(code, state)
driver = Dispatcher(_Breaking(), us)
driver.handle({"op": "key", "key": "Shift_L", "state": "down"})
with pytest.raises(RuntimeError):
driver.handle({"op": "key", "key": "Shift_L", "state": "up"})
# Still held, so the next `release_all` will try the up again.
assert driver.handle({"op": "pressed"})["keys"] == ["Shift_L"]
# -- 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")
# The whole sequence, not just the two masks: `modifiers(both)` followed by
# `modifiers(control)` with no key events in between would satisfy a
# first-and-last assertion while typing nothing at all.
assert sink.calls == [
("modifiers", both, 0, 0, 0),
("key", KEY_A, DOWN),
("key", KEY_A, UP),
("modifiers", us.modifier_mask("Control_L"), 0, 0, 0),
]
# And no second Control down, and no Shift keycode.
assert not any(c[0] == "key" and c[1] in (KEY_LEFTCTRL, KEY_LEFTSHIFT) for c in sink.calls)
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()
reply = driver.handle({"op": "type", "text": "a"})
assert reply["ok"] is False
# The caller's mistake, so exit 2 -- not `refused`, which would report a
# held Caps_Lock as a compositor failure.
assert reply["kind"] == KIND_INVALID
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
assert reply["kind"] == KIND_INVALID
# 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)]