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
This commit is contained in:
1 parent
b1f2744cf0
commit
e6f4c3bb3f
24 files changed
+2474
-105
No files matched your search
@@ -16,6 +16,9 @@ exit 10 sends them to the wrong unit.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstream_pointer import __main__ as entry
|
||||
@@ -139,6 +142,222 @@ def test_a_usable_layout_gets_as_far_as_the_compositor(no_compositor):
|
||||
|
||||
|
||||
def test_the_exit_codes_match_the_brokers_table():
|
||||
# Mirrored, not imported: the driver is a separate package on purpose
|
||||
# (see the module docstring in __main__).
|
||||
assert (entry.EXIT_OK, entry.EXIT_USAGE, entry.EXIT_COMPOSITOR) == (0, 2, 10)
|
||||
"""Mirrored constants, compared against the table they mirror.
|
||||
|
||||
The driver keeps its own copies on purpose -- it is a separate package and
|
||||
must not import the broker's internals -- so the two can drift, and
|
||||
asserting the literals alone would not notice. This imports the broker's
|
||||
enum to compare, which a test may do where the shipped driver may not.
|
||||
"""
|
||||
|
||||
from hhstreamd.protocol import ExitCode
|
||||
|
||||
assert entry.EXIT_OK == ExitCode.OK
|
||||
assert entry.EXIT_USAGE == ExitCode.USAGE
|
||||
assert entry.EXIT_COMPOSITOR == ExitCode.COMPOSITOR
|
||||
|
||||
|
||||
def test_the_module_passes_the_same_defaults_this_binary_has():
|
||||
"""The drift this guards is silent: a unit and a hand-run binary that type
|
||||
different characters, with nothing to compare them against but prose."""
|
||||
|
||||
module = Path(__file__).resolve().parents[2] / "nix/module.nix"
|
||||
if not module.is_file():
|
||||
pytest.skip("not running from a checkout")
|
||||
text = module.read_text()
|
||||
assert f'default = "{entry.DEFAULT_LAYOUT}";' in text
|
||||
assert f'default = "{entry.DEFAULT_MODEL}";' in text
|
||||
# And the unit really passes them, rather than relying on these defaults:
|
||||
# a unit that relied on them would stop matching the contract's command
|
||||
# line the moment either moved.
|
||||
for flag in ("--xkb-layout", "--xkb-model", "--xkb-variant", "--xkb-options"):
|
||||
assert f'"{flag}"' in text, f"{flag} is not on the unit's ExecStart"
|
||||
|
||||
|
||||
# -- the keymap upload, which nothing else in the suite can see --------------
|
||||
#
|
||||
# The dispatcher tests record tuples from a sink, so they are blind to the
|
||||
# Wayland `keymap` request: its format, its fd and its size never reach them.
|
||||
# That is the review's finding 3 -- a `main` that connected and listened
|
||||
# WITHOUT ever uploading passed every other test in this tree, and so did a
|
||||
# backend that re-uploaded on every `type`.
|
||||
|
||||
|
||||
#: One ordering log shared by the sink and the server stand-ins, because the
|
||||
#: assertion is about the order of events *between* the two objects: an upload
|
||||
#: after `listen` is a socket that promised a working device before it had one.
|
||||
ORDER: list[str] = []
|
||||
|
||||
|
||||
class _UploadingSink:
|
||||
"""A sink whose connect succeeds, recording what it was asked to upload."""
|
||||
|
||||
def __init__(self, runtime_dir, display_name=None) -> None:
|
||||
self.uploads: list[str] = []
|
||||
self.connected = 0
|
||||
_UploadingSink.last = self
|
||||
|
||||
def connect(self) -> None:
|
||||
self.connected += 1
|
||||
ORDER.append("connect")
|
||||
|
||||
def upload_keymap(self, text: str) -> None:
|
||||
self.uploads.append(text)
|
||||
ORDER.append("upload")
|
||||
|
||||
def has_keyboard(self) -> bool:
|
||||
return True
|
||||
|
||||
def outputs(self) -> list[str]:
|
||||
return []
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class _RecordingServer:
|
||||
"""Stands in for `PointerServer`, so no socket is bound.
|
||||
|
||||
`serve_forever` raises, which is how the test gets control back at exactly
|
||||
the point the real process would start answering requests -- and therefore
|
||||
how it can assert the upload happened *before* that.
|
||||
"""
|
||||
|
||||
class Served(Exception):
|
||||
pass
|
||||
|
||||
def __init__(self, socket_path, handle, *, socket_mode=0o660) -> None:
|
||||
self.events: list[str] = []
|
||||
_RecordingServer.last = self
|
||||
|
||||
def listen(self) -> None:
|
||||
self.events.append("listen")
|
||||
ORDER.append("listen")
|
||||
|
||||
def serve_forever(self) -> None:
|
||||
self.events.append("serve")
|
||||
ORDER.append("serve")
|
||||
raise _RecordingServer.Served
|
||||
|
||||
def close(self) -> None:
|
||||
self.events.append("close")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def uploading(monkeypatch):
|
||||
ORDER.clear()
|
||||
monkeypatch.setattr(entry, "WaylandSink", _UploadingSink)
|
||||
monkeypatch.setattr(entry, "PointerServer", _RecordingServer)
|
||||
return _UploadingSink
|
||||
|
||||
|
||||
def test_the_keymap_is_uploaded_once_before_the_socket_listens(uploading):
|
||||
"""The ordering rule, asserted rather than described.
|
||||
|
||||
`key` or `modifiers` before `keymap` is the protocol error `no_keymap`,
|
||||
which kills the connection instead of returning something the broker could
|
||||
report. So the upload has to happen between `connect` and `listen` -- a
|
||||
listening socket is a promise that the device works.
|
||||
"""
|
||||
|
||||
with pytest.raises(_RecordingServer.Served):
|
||||
entry.main([])
|
||||
|
||||
sink = _UploadingSink.last
|
||||
assert sink.connected == 1
|
||||
assert len(sink.uploads) == 1, "uploaded once, not per request"
|
||||
# The order across both objects, which is the whole assertion. A `main`
|
||||
# that never uploaded, or uploaded after `listen`, fails here -- and before
|
||||
# this test existed, both passed every other test in the tree.
|
||||
assert ORDER == ["connect", "upload", "listen", "serve"]
|
||||
|
||||
|
||||
def test_the_uploaded_text_is_the_keymap_for_the_flag(uploading):
|
||||
with pytest.raises(_RecordingServer.Served):
|
||||
entry.main(["--xkb-layout", "de"])
|
||||
|
||||
(text,) = _UploadingSink.last.uploads
|
||||
assert text.lstrip().startswith("xkb_keymap {")
|
||||
# The symbols name, which is what the VM check greps: a `de` layout that
|
||||
# silently compiled as `us` would say `pc_us_inet(evdev)` here.
|
||||
assert 'xkb_symbols "pc_de_inet(evdev)"' in text
|
||||
|
||||
|
||||
def test_the_payload_is_nul_terminated_and_the_size_counts_the_nul():
|
||||
"""The one value Hyprland reads off the end of the mapping if it is wrong.
|
||||
|
||||
It `mmap`s exactly `size` bytes and hands the pointer to
|
||||
`xkb_keymap_new_from_string`, which wants a C string. A `size` of
|
||||
`len(text)` therefore has no terminator inside the mapping. The symptom is
|
||||
a keymap that will not compile, which from our side looks exactly like a
|
||||
compositor that has no keyboard at all -- so this is asserted on the real
|
||||
`WaylandSink.upload_keymap`, against a keyboard object that records the
|
||||
request.
|
||||
"""
|
||||
|
||||
pytest.importorskip("pywayland")
|
||||
from hhstream_pointer import keymap as keymaps
|
||||
from hhstream_pointer.backend import WaylandSink
|
||||
|
||||
class _Keyboard:
|
||||
def __init__(self) -> None:
|
||||
self.keymap_calls: list[tuple[int, bytes, int]] = []
|
||||
self.modifier_calls: list[tuple] = []
|
||||
|
||||
def keymap(self, format_: int, fd: int, size: int) -> None:
|
||||
# Read it back through the fd the compositor is handed, not through
|
||||
# the string we started from: that is what the compositor sees.
|
||||
with os.fdopen(os.dup(fd), "rb", closefd=True) as handle:
|
||||
handle.seek(0)
|
||||
self.keymap_calls.append((format_, handle.read(size), size))
|
||||
|
||||
def modifiers(self, *args) -> None:
|
||||
self.modifier_calls.append(args)
|
||||
|
||||
class _Manager:
|
||||
def __init__(self, keyboard) -> None:
|
||||
self.keyboard = keyboard
|
||||
|
||||
def create_virtual_keyboard(self, seat):
|
||||
return self.keyboard
|
||||
|
||||
keyboard = _Keyboard()
|
||||
sink = WaylandSink(Path("/nonexistent"))
|
||||
sink._keyboard_manager = _Manager(keyboard)
|
||||
sink._display = _NullDisplay()
|
||||
|
||||
text = keymaps.build(layout="us").text()
|
||||
sink.upload_keymap(text)
|
||||
|
||||
(format_, payload, size) = keyboard.keymap_calls[0]
|
||||
assert format_ == keymaps.XKB_V1 == 1
|
||||
assert payload.endswith(b"\0"), "no terminator inside the mapping"
|
||||
assert payload.count(b"\0") == 1, "one terminator, not two"
|
||||
assert size == len(text.encode("utf-8")) + 1
|
||||
assert payload[:-1].decode("utf-8") == text
|
||||
# And the mask is zeroed straight afterwards, because `destroy` of a
|
||||
# previous driver's keyboard cleared no mask and a client keeps the last
|
||||
# one it was sent.
|
||||
assert keyboard.modifier_calls == [(0, 0, 0, 0)]
|
||||
assert sink.has_keyboard() is True
|
||||
|
||||
|
||||
def test_a_compositor_with_no_keyboard_manager_uploads_nothing_and_still_works():
|
||||
pytest.importorskip("pywayland")
|
||||
from hhstream_pointer.backend import WaylandSink
|
||||
|
||||
sink = WaylandSink(Path("/nonexistent"))
|
||||
sink._display = _NullDisplay()
|
||||
# No `_keyboard_manager`: the global was never advertised.
|
||||
sink.upload_keymap("xkb_keymap {};")
|
||||
assert sink.has_keyboard() is False
|
||||
|
||||
|
||||
class _NullDisplay:
|
||||
"""Enough of `pywayland.client.Display` for the two calls upload makes."""
|
||||
|
||||
def roundtrip(self) -> None:
|
||||
pass
|
||||
|
||||
def flush(self) -> None:
|
||||
pass
|
||||
@@ -95,6 +95,20 @@ def test_the_two_allowed_control_characters_are_named_keys(us, character, 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("") == []
|
||||
|
||||
@@ -132,6 +146,18 @@ def test_an_unknown_keysym_name_is_refused(us):
|
||||
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:
|
||||
@@ -191,8 +217,18 @@ def test_a_lock_is_not_a_modifier(us):
|
||||
assert us.modifier_mask(name) == 0
|
||||
|
||||
|
||||
def test_control_contributes_a_mask_that_is_not_shifts(us):
|
||||
assert us.modifier_mask("Control_L") not in (0, shift_mask(us))
|
||||
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 ---------------
|
||||
@@ -227,10 +263,12 @@ def test_a_character_us_cannot_type_is_ordinary_on_de(us, de):
|
||||
|
||||
def test_the_keymap_text_is_an_xkb_keymap_naming_its_layout(us, de):
|
||||
assert us.text().lstrip().startswith("xkb_keymap {")
|
||||
# The symbols section names the layout, which is what the VM check greps to
|
||||
# prove the keymap a client decoded with is the one we uploaded.
|
||||
assert "us" in _symbols_line(us)
|
||||
assert "de" in _symbols_line(de)
|
||||
# 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:
|
||||
|
||||
+120
-3
@@ -507,6 +507,109 @@ def test_an_ordinary_key_down_sends_no_mask(driver, sink):
|
||||
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 -------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -574,8 +677,17 @@ def test_type_of_a_capital_under_a_held_control_ors_both_masks(driver, sink, us)
|
||||
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)
|
||||
# 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):
|
||||
@@ -601,13 +713,18 @@ def test_type_while_a_lock_is_held_is_refused_too(driver, sink):
|
||||
driver.handle({"op": "key", "key": "Caps_Lock", "state": "down"})
|
||||
sink.calls.clear()
|
||||
|
||||
assert driver.handle({"op": "type", "text": "a"})["ok"] is False
|
||||
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 == []
|
||||
|
||||
|
||||
+56
-4
@@ -22,6 +22,12 @@ What they prove and what they do not:
|
||||
recorder. So the protocol, the framing, the driver's own button bookkeeping
|
||||
and — importantly — which backend failures become ``ok: false`` and which
|
||||
kill the connection are the shipped ones; only the compositor is absent.
|
||||
|
||||
The **keymap is real too**, a compiled ``us`` layout rather than a stub,
|
||||
because what these tests assert about the keyboard is which evdev code and
|
||||
which modifier mask went on the wire — and a stub would answer whatever the
|
||||
test expected. ``keyboard=False`` builds a driver with no keyboard at all,
|
||||
which is the compositor-has-no-global case.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,10 +40,36 @@ from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstream_pointer import keymap as keymaps
|
||||
from hhstream_pointer.__main__ import _handler
|
||||
from hhstream_pointer.ops import Dispatcher
|
||||
from hhstream_pointer.server import PointerServer
|
||||
|
||||
#: evdev codes the keyboard tests name. From ``linux/input-event-codes.h``,
|
||||
#: and the values that cross the Wayland request -- never XKB keycodes, which
|
||||
#: are 8 higher and never leave the driver.
|
||||
KEY_A = 30
|
||||
KEY_LEFTSHIFT = 42
|
||||
KEY_LEFTCTRL = 29
|
||||
|
||||
_us_keymap: keymaps.Keymap | None = None
|
||||
|
||||
|
||||
def us_keymap() -> keymaps.Keymap:
|
||||
"""One compiled ``us`` keymap, shared.
|
||||
|
||||
Compiling is the slow part (xkbcommon reads the rules files), and the
|
||||
object is immutable once built -- it is a lookup table plus the keymap text
|
||||
-- so one per process is right. Shared deliberately rather than per-fixture
|
||||
for the same reason the driver builds it once at start-up: a *second*
|
||||
keymap in a process would be a second answer to "which code is `z`".
|
||||
"""
|
||||
|
||||
global _us_keymap
|
||||
if _us_keymap is None:
|
||||
_us_keymap = keymaps.build(layout="us")
|
||||
return _us_keymap
|
||||
|
||||
#: Linux's sun_path is 108 bytes including the NUL.
|
||||
SUN_PATH_MAX = 107
|
||||
|
||||
@@ -390,8 +422,11 @@ class FakeCompositor:
|
||||
class RecordingSink:
|
||||
"""A :class:`hhstream_pointer.ops.PointerSink` that writes nothing anywhere."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, *, keyboard: bool = True) -> None:
|
||||
self.calls: list[tuple] = []
|
||||
#: Whether a virtual keyboard was created at start-up. False is the
|
||||
#: compositor-with-no-global case, which must leave the cursor working.
|
||||
self.keyboard = keyboard
|
||||
#: An exception to raise from the next call. The shipped driver
|
||||
#: answers an ``OutputUnknown`` on the wire and lets anything else
|
||||
#: take the connection down, so which one is raised here decides which
|
||||
@@ -414,6 +449,23 @@ class RecordingSink:
|
||||
self._check()
|
||||
self.calls.append(("frame", output))
|
||||
|
||||
# -- the keyboard half -------------------------------------------------
|
||||
#
|
||||
# No output on either of these, and that is the assertion as much as the
|
||||
# recording: a virtual keyboard is seat-global, so a sink that accepted an
|
||||
# output would let a per-output implementation look correct.
|
||||
|
||||
def has_keyboard(self) -> bool:
|
||||
return self.keyboard
|
||||
|
||||
def key(self, code: int, state: int) -> None:
|
||||
self._check()
|
||||
self.calls.append(("key", code, state))
|
||||
|
||||
def modifiers(self, depressed: int, latched: int, locked: int, group: int) -> None:
|
||||
self._check()
|
||||
self.calls.append(("modifiers", depressed, latched, locked, group))
|
||||
|
||||
def _check(self) -> None:
|
||||
if self.fail is not None:
|
||||
raise self.fail
|
||||
@@ -433,11 +485,11 @@ class FakeDriver:
|
||||
everything a test is actually asserting about still runs the real code.
|
||||
"""
|
||||
|
||||
def __init__(self, socket_path: Path) -> None:
|
||||
def __init__(self, socket_path: Path, *, keyboard: bool = True) -> None:
|
||||
check_path(Path(socket_path))
|
||||
self.socket_path = Path(socket_path)
|
||||
self.sink = RecordingSink()
|
||||
self.dispatcher = Dispatcher(self.sink)
|
||||
self.sink = RecordingSink(keyboard=keyboard)
|
||||
self.dispatcher = Dispatcher(self.sink, us_keymap() if keyboard else None)
|
||||
self.server = PointerServer(self.socket_path, _handler(self.dispatcher))
|
||||
self.server.listen()
|
||||
self.connections: list[socket.socket] = []
|
||||
|
||||
@@ -172,6 +172,30 @@ def test_every_pointer_verb_that_moves_something_is_cached():
|
||||
assert "container.list" not in protocol.MUTATING_VERBS
|
||||
|
||||
|
||||
def test_every_keyboard_verb_is_cached_for_the_same_reason():
|
||||
"""A retried `type` that typed twice is also unrecoverable.
|
||||
|
||||
And `pointer.state`, which now reports held keys, stays out of the set: it
|
||||
mutates nothing, and a cached one would be a stale one.
|
||||
"""
|
||||
|
||||
assert {"keyboard.key", "keyboard.type"} <= protocol.MUTATING_VERBS
|
||||
assert {"keyboard.key", "keyboard.type"} <= set(protocol.VERBS)
|
||||
assert "pointer.state" not in protocol.MUTATING_VERBS
|
||||
|
||||
|
||||
def test_there_is_no_keyboard_acquire_verb():
|
||||
"""One seat, one keyboard focus, one lease.
|
||||
|
||||
A `keyboard.acquire` would let session B warp the pointer while session A
|
||||
believed it was typing into its own window, because `follow_mouse = 1`
|
||||
means a warp retargets the keys.
|
||||
"""
|
||||
|
||||
assert not any(verb.startswith("keyboard.acquire") for verb in protocol.VERBS)
|
||||
assert "keyboard.release" not in protocol.VERBS
|
||||
|
||||
|
||||
def test_every_verb_the_protocol_names_is_one_the_daemon_answers():
|
||||
"""One list, so a verb cannot be added to the dispatcher alone.
|
||||
|
||||
|
||||
@@ -105,12 +105,82 @@ def test_every_verb_the_contract_names_is_registered(host_cli):
|
||||
["session", "pointer", "release", "foo-aaaaaa"],
|
||||
["session", "pointer", "state"],
|
||||
["session", "pointer", "state", "--json"],
|
||||
["session", "keyboard", "type", "foo-aaaaaa", "hello"],
|
||||
["session", "keyboard", "type", "foo-aaaaaa", "hello", "--lease", "abc"],
|
||||
["session", "keyboard", "key", "foo-aaaaaa", "Return"],
|
||||
["session", "keyboard", "down", "foo-aaaaaa", "Control_L"],
|
||||
["session", "keyboard", "up", "foo-aaaaaa", "Control_L"],
|
||||
]
|
||||
for argv in surface:
|
||||
args = host_cli.parse_args(argv)
|
||||
assert callable(args.func), argv
|
||||
|
||||
|
||||
def test_the_keyboard_help_says_the_pointer_lease_is_required(host_cli, capsys):
|
||||
"""Exit 9 until `pointer acquire` is the one fact an agent gets wrong here.
|
||||
|
||||
Asserted on the `keyboard` group's own help and on a leaf's, because
|
||||
`--help` on a leaf is what an agent actually reads -- and the group help is
|
||||
what a human skims.
|
||||
"""
|
||||
|
||||
for argv in (["session", "keyboard", "--help"], ["session", "keyboard", "type", "--help"]):
|
||||
with pytest.raises(SystemExit):
|
||||
host_cli.parse_args(argv)
|
||||
out = capsys.readouterr().out
|
||||
assert "pointer acquire" in out
|
||||
assert "9" in out, "the exit code an agent has to branch on"
|
||||
|
||||
|
||||
def test_the_keyboard_help_warns_that_a_held_key_floods(host_cli, capsys):
|
||||
"""Unconditionally, and not because a probe saw repeats on the wire.
|
||||
|
||||
It did not: the compositor sends one event and the application repeats, so
|
||||
the flood is real and is not ours to rate-limit.
|
||||
"""
|
||||
|
||||
with pytest.raises(SystemExit):
|
||||
host_cli.parse_args(["session", "keyboard", "down", "--help"])
|
||||
out = capsys.readouterr().out.lower()
|
||||
assert "flood" in out
|
||||
|
||||
|
||||
def test_the_pointer_help_does_not_grow_a_keyboard_tutorial(host_cli, capsys):
|
||||
"""`pointer --help` stays about the cursor.
|
||||
|
||||
Narrow on purpose: `acquire`'s *stderr* had to start mentioning keyboard
|
||||
verbs (they refresh the lease), so a test that grepped the whole binary's
|
||||
help for the word would pass for the wrong reason. This reads the pointer
|
||||
group's description only.
|
||||
"""
|
||||
|
||||
with pytest.raises(SystemExit):
|
||||
host_cli.parse_args(["session", "pointer", "--help"])
|
||||
out = capsys.readouterr().out
|
||||
assert "keysym" not in out
|
||||
assert "keyboard type" not in out
|
||||
|
||||
|
||||
def test_type_takes_its_text_as_one_argument_and_does_not_interpret_it(host_cli):
|
||||
r"""A newline is a newline; a backslash-n is a backslash and an n.
|
||||
|
||||
Interpreting escapes here would make a literal backslash-n untypeable,
|
||||
and the shell has already done the quoting.
|
||||
"""
|
||||
|
||||
# A real newline survives as a real newline.
|
||||
args = host_cli.parse_args(["session", "keyboard", "type", "foo-aaaaaa", "a\nb"])
|
||||
assert args.text == "a\nb"
|
||||
assert len(args.text) == 3
|
||||
|
||||
# And a backslash followed by an n stays two characters: interpreting it
|
||||
# would make a literal backslash-n untypeable.
|
||||
args = host_cli.parse_args(["session", "keyboard", "type", "foo-aaaaaa", r"a\nb"])
|
||||
assert args.text == r"a\nb"
|
||||
assert len(args.text) == 4
|
||||
assert "\n" not in args.text
|
||||
|
||||
|
||||
def test_a_move_needs_exactly_one_target(host_cli):
|
||||
with pytest.raises(SystemExit):
|
||||
host_cli.parse_args(["session", "pointer", "move", "x"])
|
||||
|
||||
@@ -77,7 +77,10 @@ def test_release_all_lifts_everything_and_says_what_it_lifted(driver):
|
||||
client.button("left", "down")
|
||||
client.button("right", "down")
|
||||
|
||||
assert client.release_all() == ["left", "right"]
|
||||
# One call, two lists: there is one `release_all` op and one expiry call
|
||||
# site, so buttons and keys come back together rather than needing a
|
||||
# second request that could be forgotten.
|
||||
assert client.release_all() == (["left", "right"], [])
|
||||
assert client.pressed() == []
|
||||
# Lifted through the pointer each went down on, then one frame for it.
|
||||
assert fake.sink.calls[-3:] == [
|
||||
@@ -91,7 +94,7 @@ def test_release_all_on_an_idle_driver_is_an_empty_list_not_an_error(driver):
|
||||
"""The expiry path calls this unconditionally; it must be safe."""
|
||||
|
||||
client, _ = driver
|
||||
assert client.release_all() == []
|
||||
assert client.release_all() == ([], [])
|
||||
|
||||
|
||||
def test_a_refusal_is_carried_back_and_is_not_a_lost_connection(driver):
|
||||
@@ -215,7 +218,7 @@ def test_a_reply_that_is_not_the_protocol_is_unavailable_not_an_empty_answer(
|
||||
try:
|
||||
with pytest.raises(DriverUnavailable) as exc:
|
||||
client.pressed()
|
||||
assert "list of button names" in str(exc.value)
|
||||
assert "list of names" in str(exc.value)
|
||||
finally:
|
||||
client.close()
|
||||
thread.join(timeout=5.0)
|
||||
|
||||
@@ -0,0 +1,663 @@
|
||||
"""The keyboard verbs: the pointer lease, the key mirror, and the exit codes.
|
||||
|
||||
Harness copied from ``test_pointer_verbs.py``, and the same things are real:
|
||||
the manager, the lease, the driver client, and the shipped dispatcher and
|
||||
server over a real ``AF_UNIX`` socket — plus a real compiled ``us`` keymap, so
|
||||
an assertion about which evdev code went on the wire is an assertion about the
|
||||
layout and not about a stub that agreed with it. Only the Wayland sink and the
|
||||
clock are substituted.
|
||||
|
||||
Two things these tests are careful about, both of them false passes the
|
||||
verification doc names:
|
||||
|
||||
* **the clock does not advance anything by itself.** A test that moves
|
||||
``ManualClock`` and then asserts the lease is gone would pass against a
|
||||
broker that never expires anything: expiry runs in ``_expire_pointer``, from
|
||||
the sweeper or from the next verb, so every expiry case here calls one of
|
||||
those explicitly.
|
||||
* **a refusal is asserted by its exit code and by the sink.** "The reply said
|
||||
`ok: false`" is satisfied by a handler that typed the string and then
|
||||
errored, so the sink's call list is checked too.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fakes import KEY_A, KEY_LEFTCTRL, KEY_LEFTSHIFT, FakeDriver, us_keymap
|
||||
|
||||
from hhstreamd.clock import ManualClock
|
||||
from hhstreamd.manager import ManagerConfig, ManagerError, SessionManager
|
||||
from hhstreamd.policy import Policy
|
||||
from hhstreamd.protocol import ExitCode, exit_code_for
|
||||
from hhstreamd.registry import ContainerState, Session, State, container_record
|
||||
|
||||
DOWN, UP = 1, 0
|
||||
|
||||
|
||||
def make_session(session_id: str = "foot-aaaaaa", *, container: bool = True) -> Session:
|
||||
return Session(
|
||||
id=session_id,
|
||||
app="foot",
|
||||
argv=["/usr/bin/foot"],
|
||||
pid=4242,
|
||||
pgid=4242,
|
||||
sid=4242,
|
||||
pid_starttime=918342,
|
||||
cmdline_sha256="9f2c",
|
||||
home="/home/someone",
|
||||
runtime_dir=f"/run/hhstream/sessions/{session_id}",
|
||||
created_at="2026-10-01T09:14:02Z",
|
||||
created_boottime=1000.0,
|
||||
last_activity_at="2026-10-01T09:14:02Z",
|
||||
last_activity_boottime=1000.0,
|
||||
idle_timeout_s=10800.0,
|
||||
state=State.READY,
|
||||
container=(
|
||||
container_record(
|
||||
output=f"hh-{session_id}",
|
||||
workspace=1000,
|
||||
mode=(1280, 720),
|
||||
created_by="broker",
|
||||
state=ContainerState.OWNED,
|
||||
)
|
||||
if container
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class Harness:
|
||||
def __init__(self, manager: SessionManager, fake: FakeDriver, clock: ManualClock) -> None:
|
||||
self.manager = manager
|
||||
self.fake = fake
|
||||
self.clock = clock
|
||||
|
||||
def add(self, session_id: str = "foot-aaaaaa", **kwargs) -> Session:
|
||||
return self.manager.registry.add(make_session(session_id, **kwargs))
|
||||
|
||||
def run(self, coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
def acquire(self, session_id: str = "foot-aaaaaa") -> str:
|
||||
"""Add the session if it is not there yet, then take the lease.
|
||||
|
||||
Convenience, and deliberate: almost every test here is about what
|
||||
happens *after* a lease exists, and spelling out the `add` each time
|
||||
buys nothing. The tests that care about two sessions add them by hand.
|
||||
"""
|
||||
|
||||
if self.manager.registry.get(session_id) is None:
|
||||
self.add(session_id)
|
||||
lease = self.run(self.manager.pointer_acquire(session_id))["lease_id"]
|
||||
# Acquire's own two focus warps are not what any of these tests are
|
||||
# about, so they are dropped here rather than skipped past in every
|
||||
# assertion.
|
||||
self.fake.sink.calls.clear()
|
||||
return lease
|
||||
|
||||
def keys(self) -> list[str]:
|
||||
return self.manager.pointer_state()["keys"]
|
||||
|
||||
|
||||
def _harness(short_tmpdir: Path, *, keyboard: bool = True):
|
||||
fake = FakeDriver(short_tmpdir / "p.sock", keyboard=keyboard)
|
||||
clock = ManualClock(boottime=1000.0)
|
||||
manager = SessionManager(
|
||||
ManagerConfig(
|
||||
state_dir=short_tmpdir / "state",
|
||||
runtime_dir=short_tmpdir / "run",
|
||||
policy=Policy(),
|
||||
pointer_socket=fake.socket_path,
|
||||
pointer_ttl_s=30.0,
|
||||
pointer_max_s=300.0,
|
||||
),
|
||||
clock=clock,
|
||||
)
|
||||
try:
|
||||
yield Harness(manager, fake, clock)
|
||||
finally:
|
||||
if manager.driver is not None:
|
||||
manager.driver.close()
|
||||
fake.stop()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def harness(short_tmpdir: Path):
|
||||
yield from _harness(short_tmpdir)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def keyboardless(short_tmpdir: Path):
|
||||
"""A driver whose compositor advertises no virtual-keyboard global."""
|
||||
|
||||
yield from _harness(short_tmpdir, keyboard=False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# the lease is the pointer's
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_typing_without_a_lease_is_no_lease_and_not_busy(harness):
|
||||
"""Exit 9 and not 8: 9 says "acquire one", 8 says "wait for someone"."""
|
||||
|
||||
harness.add()
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
harness.run(harness.manager.keyboard_type("foot-aaaaaa", "nonesuch", "hello"))
|
||||
|
||||
assert exc.value.error == "no_lease"
|
||||
assert exit_code_for(exc.value.error) == ExitCode.NO_LEASE
|
||||
assert harness.fake.sink.calls == []
|
||||
|
||||
|
||||
def test_another_sessions_lease_is_also_no_lease(harness):
|
||||
harness.add("foot-aaaaaa")
|
||||
harness.add("foot-bbbbbb")
|
||||
lease = harness.acquire("foot-aaaaaa")
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
harness.run(harness.manager.keyboard_type("foot-bbbbbb", lease, "hello"))
|
||||
|
||||
# Not `pointer_busy`: B is not being told to wait its turn, it is being
|
||||
# told this lease id is not its own.
|
||||
assert exc.value.error == "no_lease"
|
||||
assert harness.fake.sink.calls == []
|
||||
|
||||
|
||||
def test_a_second_acquire_while_a_key_is_held_is_busy_and_leaves_the_key(harness):
|
||||
harness.add("foot-aaaaaa")
|
||||
harness.add("foot-bbbbbb")
|
||||
lease = harness.acquire("foot-aaaaaa")
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down"))
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
harness.run(harness.manager.pointer_acquire("foot-bbbbbb"))
|
||||
|
||||
assert exc.value.error == "pointer_busy"
|
||||
assert exit_code_for(exc.value.error) == ExitCode.BUSY
|
||||
# Still the first holder's, and still held: a refused acquire must not
|
||||
# disturb a chord someone is in the middle of.
|
||||
assert harness.manager.pointer.state()["holder"] == "foot-aaaaaa"
|
||||
assert harness.keys() == ["Shift_L"]
|
||||
|
||||
|
||||
def test_the_holder_cannot_acquire_a_second_lease_either(harness):
|
||||
"""Unchanged by the keyboard, and asserted here because typing is where a
|
||||
second id would do the most damage: a half-typed chord whose lease was
|
||||
silently replaced fails with "stale lease" for no visible reason."""
|
||||
|
||||
harness.add()
|
||||
harness.acquire()
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
|
||||
assert exc.value.error == "pointer_busy"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# what goes on the wire
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_typing_a_capital_sends_the_mask_then_the_key(harness):
|
||||
lease = harness.acquire()
|
||||
|
||||
reply = harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "A"))
|
||||
|
||||
shift = us_keymap().modifier_mask("Shift_L")
|
||||
assert harness.fake.sink.calls == [
|
||||
("modifiers", shift, 0, 0, 0),
|
||||
("key", KEY_A, DOWN),
|
||||
("key", KEY_A, UP),
|
||||
("modifiers", 0, 0, 0, 0),
|
||||
]
|
||||
# No synthetic Shift keycode: this compositor does not derive the mask from
|
||||
# an injected key, and sending both is how a toolkit shifts twice.
|
||||
assert not any(c[0] == "key" and c[1] == KEY_LEFTSHIFT for c in harness.fake.sink.calls)
|
||||
assert reply["chars"] == 1
|
||||
assert reply["keys"] == []
|
||||
|
||||
|
||||
def test_typing_leaves_nothing_held(harness):
|
||||
lease = harness.acquire()
|
||||
harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "hello"))
|
||||
assert harness.keys() == []
|
||||
|
||||
|
||||
def test_a_held_modifier_survives_a_type_and_ors_into_it(harness):
|
||||
lease = harness.acquire()
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Control_L", "down"))
|
||||
harness.fake.sink.calls.clear()
|
||||
|
||||
reply = harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "c"))
|
||||
|
||||
control = us_keymap().modifier_mask("Control_L")
|
||||
assert harness.fake.sink.calls[0] == ("modifiers", control, 0, 0, 0)
|
||||
# Restored to the baseline, not to zero: Control was not this type's to
|
||||
# lift, and `down Control_L` + `type c` + `up Control_L` is how a chord is
|
||||
# spelled across three CLI invocations.
|
||||
assert harness.fake.sink.calls[-1] == ("modifiers", control, 0, 0, 0)
|
||||
assert reply["keys"] == ["Control_L"]
|
||||
assert harness.keys() == ["Control_L"]
|
||||
|
||||
|
||||
def test_a_key_down_is_mirrored_in_the_lease_by_name(harness):
|
||||
lease = harness.acquire()
|
||||
|
||||
reply = harness.run(
|
||||
harness.manager.keyboard_key("foot-aaaaaa", lease, "Control_L", "down")
|
||||
)
|
||||
|
||||
# The reply and the lease both speak names; only the sink sees the code.
|
||||
assert reply["keys"] == ["Control_L"]
|
||||
assert harness.keys() == ["Control_L"]
|
||||
assert ("key", KEY_LEFTCTRL, DOWN) in harness.fake.sink.calls
|
||||
|
||||
|
||||
def test_pointer_state_reports_held_keys_beside_held_buttons(harness):
|
||||
lease = harness.acquire()
|
||||
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down"))
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down"))
|
||||
|
||||
state = harness.manager.pointer_state()
|
||||
|
||||
assert state["buttons"] == ["left"]
|
||||
assert state["keys"] == ["Shift_L"]
|
||||
|
||||
|
||||
def test_an_up_of_a_key_that_was_not_down_changes_nothing(harness):
|
||||
lease = harness.acquire()
|
||||
|
||||
reply = harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "up"))
|
||||
|
||||
assert reply["keys"] == []
|
||||
# Nothing on the wire either: a key-up the compositor has no matching
|
||||
# key-down for puts its `m_pressed` out of step with ours.
|
||||
assert harness.fake.sink.calls == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# exit codes (the verification doc's change 1)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_an_unmappable_character_is_exit_2_and_types_nothing(harness):
|
||||
"""The driver's token is what makes this 2 rather than 10.
|
||||
|
||||
Without it the refusal arrives as `driver_refused`, which is exit 10 and
|
||||
says "the compositor failed" about a character that is simply not on the
|
||||
layout. `é` is the case: perfectly well formed, unmappable on `us`.
|
||||
"""
|
||||
|
||||
lease = harness.acquire()
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "café"))
|
||||
|
||||
assert exc.value.error == "invalid_argument"
|
||||
assert exit_code_for(exc.value.error) == ExitCode.USAGE
|
||||
# No prefix: "c", "a" and "f" must not have been typed.
|
||||
assert harness.fake.sink.calls == []
|
||||
|
||||
|
||||
def test_the_refusal_does_not_carry_the_string_it_refused(harness):
|
||||
"""A typed string is a password as often as not, and this reason is logged."""
|
||||
|
||||
lease = harness.acquire()
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "hunter2é"))
|
||||
|
||||
assert "hunter2" not in exc.value.reason
|
||||
assert "é" not in exc.value.reason
|
||||
assert "scalar 7" in exc.value.reason
|
||||
|
||||
|
||||
def test_an_unknown_keysym_is_exit_2(harness):
|
||||
lease = harness.acquire()
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
harness.run(
|
||||
harness.manager.keyboard_key("foot-aaaaaa", lease, "NoSuchKeysym", "down")
|
||||
)
|
||||
|
||||
assert exit_code_for(exc.value.error) == ExitCode.USAGE
|
||||
assert harness.keys() == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text, fragment",
|
||||
[(None, "must be a string"), (7, "must be a string"), (["a"], "must be a string")],
|
||||
)
|
||||
def test_a_text_that_is_not_a_string_is_exit_2_before_the_driver(harness, text, fragment):
|
||||
lease = harness.acquire()
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, text))
|
||||
|
||||
assert exc.value.error == "invalid_argument"
|
||||
assert fragment in exc.value.reason
|
||||
assert harness.fake.sink.calls == []
|
||||
|
||||
|
||||
def test_a_string_over_the_cap_is_exit_2_at_the_broker(harness):
|
||||
"""Checked here and not only in the driver, because only a broker-side
|
||||
`invalid_argument` produces exit 2 — a driver-side length refusal would
|
||||
arrive as a compositor failure unless it carried the token."""
|
||||
|
||||
from hhstreamd.manager import MAX_TYPE_SCALARS
|
||||
|
||||
lease = harness.acquire()
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
harness.run(
|
||||
harness.manager.keyboard_type("foot-aaaaaa", lease, "a" * (MAX_TYPE_SCALARS + 1))
|
||||
)
|
||||
|
||||
assert exc.value.error == "invalid_argument"
|
||||
assert str(MAX_TYPE_SCALARS) in exc.value.reason
|
||||
assert harness.fake.sink.calls == []
|
||||
|
||||
|
||||
def test_exactly_the_cap_is_accepted(harness):
|
||||
from hhstreamd.manager import MAX_TYPE_SCALARS
|
||||
|
||||
lease = harness.acquire()
|
||||
reply = harness.run(
|
||||
harness.manager.keyboard_type("foot-aaaaaa", lease, "a" * MAX_TYPE_SCALARS)
|
||||
)
|
||||
assert reply["chars"] == MAX_TYPE_SCALARS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state", [None, "sideways", "DOWN", 1])
|
||||
def test_a_bad_key_state_is_exit_2(harness, state):
|
||||
lease = harness.acquire()
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "a", state))
|
||||
|
||||
assert exc.value.error == "invalid_argument"
|
||||
assert harness.fake.sink.calls == []
|
||||
|
||||
|
||||
def test_no_keyboard_global_is_exit_10_and_the_cursor_still_works(keyboardless):
|
||||
"""A compositor with no `zwp_virtual_keyboard_manager_v1`.
|
||||
|
||||
Exit 10 and not 2: the caller's request was fine. And the pointer half has
|
||||
to keep working, which is the whole reason a missing keyboard global does
|
||||
not abort the driver's start-up the way a version-1 pointer manager does.
|
||||
"""
|
||||
|
||||
keyboardless.add()
|
||||
lease = keyboardless.acquire()
|
||||
|
||||
with pytest.raises(ManagerError) as exc:
|
||||
keyboardless.run(keyboardless.manager.keyboard_type("foot-aaaaaa", lease, "hi"))
|
||||
assert exc.value.error == "driver_refused"
|
||||
assert exit_code_for(exc.value.error) == ExitCode.COMPOSITOR
|
||||
|
||||
# The cursor is unaffected.
|
||||
moved = keyboardless.run(
|
||||
keyboardless.manager.pointer_move("foot-aaaaaa", lease, x=0.25, y=0.75)
|
||||
)
|
||||
assert moved["bookmark"]["x"] == 0.25
|
||||
|
||||
|
||||
def test_a_refused_key_is_not_recorded_as_held(harness):
|
||||
"""The driver first, then the mirror — the `pointer_button` order.
|
||||
|
||||
The reverse mistake is harmless (`release_all` lifts what the *driver*
|
||||
recorded), but recording a key the driver refused means `release_all` later
|
||||
asks it to lift something it never pressed.
|
||||
"""
|
||||
|
||||
lease = harness.acquire()
|
||||
|
||||
with pytest.raises(ManagerError):
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "NoSuchKeysym", "down"))
|
||||
|
||||
assert harness.keys() == []
|
||||
assert harness.manager.pointer_state()["keys"] == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# the TTL
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_typing_refreshes_the_lease(harness):
|
||||
"""`type` goes through `_refresh`, so it moves the idle deadline.
|
||||
|
||||
The clock is advanced in two steps with a `type` between them: 20s, type,
|
||||
20s. Without the refresh that is 40s against a 30s TTL and the lease is
|
||||
gone; with it, the second 20s is measured from the type.
|
||||
"""
|
||||
|
||||
harness.add()
|
||||
lease = harness.acquire()
|
||||
|
||||
harness.clock.advance(20.0)
|
||||
harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "hello"))
|
||||
harness.clock.advance(20.0)
|
||||
# The next verb is what notices an expiry, so this is the honest way to ask
|
||||
# "is the lease still alive" -- not reading `state()`, which never expires
|
||||
# anything.
|
||||
harness.run(harness.manager._expire_pointer())
|
||||
|
||||
assert harness.manager.pointer.state()["holder"] == "foot-aaaaaa"
|
||||
|
||||
|
||||
def test_the_hard_cap_still_beats_a_typing_loop(harness):
|
||||
harness.add()
|
||||
lease = harness.acquire()
|
||||
|
||||
for _ in range(20):
|
||||
harness.clock.advance(20.0)
|
||||
with __import__("contextlib").suppress(ManagerError):
|
||||
harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "x"))
|
||||
|
||||
assert harness.manager.pointer.state()["holder"] is None
|
||||
|
||||
|
||||
def test_an_expired_lease_lifts_the_key_it_left_down(harness):
|
||||
"""The expiry contract, with a key: read before `expire()`, then one
|
||||
`release_all` on the driver, and the mask zeroed after the key-up."""
|
||||
|
||||
harness.add()
|
||||
lease = harness.acquire()
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down"))
|
||||
harness.fake.sink.calls.clear()
|
||||
harness.clock.advance(31.0)
|
||||
|
||||
expired = harness.run(harness.manager._expire_pointer())
|
||||
|
||||
assert expired["keys_lifted"] == ["Shift_L"]
|
||||
assert harness.fake.sink.calls == [
|
||||
("key", KEY_LEFTSHIFT, UP),
|
||||
# Not optional. A virtual key-up clears no modifier state on this
|
||||
# compositor, so without this the next holder inherits Shift.
|
||||
("modifiers", 0, 0, 0, 0),
|
||||
]
|
||||
assert harness.manager.pointer.state()["holder"] is None
|
||||
assert harness.keys() == []
|
||||
|
||||
|
||||
def test_expiry_lifts_buttons_and_keys_in_one_release_all(harness):
|
||||
harness.add()
|
||||
lease = harness.acquire()
|
||||
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down"))
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Control_L", "down"))
|
||||
harness.fake.sink.calls.clear()
|
||||
harness.clock.advance(31.0)
|
||||
|
||||
expired = harness.run(harness.manager._expire_pointer())
|
||||
|
||||
assert expired["buttons_lifted"] == ["left"]
|
||||
assert expired["keys_lifted"] == ["Control_L"]
|
||||
# Buttons first with their frame, then keys, then the mask. One round trip.
|
||||
assert [c[0] for c in harness.fake.sink.calls] == [
|
||||
"button",
|
||||
"frame",
|
||||
"key",
|
||||
"modifiers",
|
||||
]
|
||||
|
||||
|
||||
def test_a_held_key_does_not_leak_to_the_next_holder(harness):
|
||||
harness.add("foot-aaaaaa")
|
||||
harness.add("foot-bbbbbb")
|
||||
lease = harness.acquire("foot-aaaaaa")
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down"))
|
||||
harness.clock.advance(31.0)
|
||||
harness.run(harness.manager._expire_pointer())
|
||||
|
||||
harness.acquire("foot-bbbbbb")
|
||||
|
||||
assert harness.keys() == []
|
||||
|
||||
|
||||
def test_typing_does_not_count_as_activity(harness):
|
||||
"""`touch` is the only mark of activity, and typing is not it.
|
||||
|
||||
Both halves are asserted: the timestamp and the counter. A future change
|
||||
that moved the timestamp without counting a command would pass a
|
||||
counter-only test.
|
||||
"""
|
||||
|
||||
session = harness.add()
|
||||
lease = harness.acquire()
|
||||
before_at = session.last_activity_at
|
||||
before_boottime = session.last_activity_boottime
|
||||
before_count = session.command_count
|
||||
harness.clock.advance(5.0)
|
||||
|
||||
harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "hello"))
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down"))
|
||||
|
||||
assert session.last_activity_boottime == before_boottime
|
||||
assert session.last_activity_at == before_at
|
||||
assert session.command_count == before_count
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# release, kill, and the audit
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_release_lifts_held_keys_and_reports_them(harness):
|
||||
harness.add()
|
||||
lease = harness.acquire()
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down"))
|
||||
|
||||
reply = harness.run(harness.manager.pointer_release("foot-aaaaaa", lease))
|
||||
|
||||
assert reply["keys_lifted"] == ["Shift_L"]
|
||||
assert reply["buttons_lifted"] == []
|
||||
assert harness.manager.pointer_state()["keys"] == []
|
||||
|
||||
|
||||
def test_killing_the_holder_lifts_its_keys(harness):
|
||||
harness.add()
|
||||
lease = harness.acquire()
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Control_L", "down"))
|
||||
harness.fake.sink.calls.clear()
|
||||
|
||||
harness.run(harness.manager._drop_lease_for(harness.manager.registry.get("foot-aaaaaa"), "kill"))
|
||||
|
||||
assert ("key", KEY_LEFTCTRL, UP) in harness.fake.sink.calls
|
||||
assert ("modifiers", 0, 0, 0, 0) in harness.fake.sink.calls
|
||||
assert harness.manager.pointer.state()["holder"] is None
|
||||
assert lease # the id is still the one we were given; nothing replayed it
|
||||
|
||||
|
||||
def test_the_audit_records_a_character_count_and_never_the_text(harness):
|
||||
harness.add()
|
||||
lease = harness.acquire()
|
||||
secret = "hunter2"
|
||||
|
||||
harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, secret))
|
||||
|
||||
events = harness.manager.audit.tail(50, session="foot-aaaaaa")
|
||||
typed = [e for e in events if e.get("event") == "keyboard_type"]
|
||||
assert len(typed) == 1
|
||||
assert typed[0]["chars"] == len(secret)
|
||||
assert "text" not in typed[0]
|
||||
# And not hiding anywhere else in the line either.
|
||||
assert secret not in str(typed[0])
|
||||
|
||||
|
||||
def test_the_audit_records_a_keysym_name_which_is_not_a_secret(harness):
|
||||
harness.add()
|
||||
lease = harness.acquire()
|
||||
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Return", "down"))
|
||||
|
||||
events = harness.manager.audit.tail(50, session="foot-aaaaaa")
|
||||
pressed = [e for e in events if e.get("event") == "keyboard_key"]
|
||||
assert pressed[-1]["key"] == "Return"
|
||||
assert pressed[-1]["state"] == "down"
|
||||
|
||||
|
||||
def test_the_expiry_audit_event_records_the_keys_it_lifted(harness):
|
||||
harness.add()
|
||||
lease = harness.acquire()
|
||||
harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down"))
|
||||
harness.clock.advance(31.0)
|
||||
|
||||
harness.run(harness.manager._expire_pointer())
|
||||
|
||||
events = harness.manager.audit.tail(50)
|
||||
timeout = [e for e in events if e.get("event") == "pointer_lease_timeout"][-1]
|
||||
assert timeout["keys_pressed"] == ["Shift_L"]
|
||||
assert timeout["keys_lifted"] == ["Shift_L"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# acquire takes the keyboard, not only the cursor
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_acquire_sends_two_motions_so_keyboard_focus_moves(harness):
|
||||
"""One warp is not enough, and that is measured, not assumed.
|
||||
|
||||
Hyprland zeroes `m_mousePosDelta` when the previous cursor movement was
|
||||
over 0.5s ago and compares it against `follow_mouse_threshold` (0) to
|
||||
decide keyboard focus, so a single warp onto an idle cursor delivers
|
||||
`wl_pointer.enter` and no `wl_keyboard.enter`. The aimed window gets the
|
||||
cursor and the previously focused one keeps the keys — and then the first
|
||||
key of the lease goes to the wrong window.
|
||||
|
||||
A check that only looked for pointer delivery would pass while that
|
||||
happened, which is why this asserts the *pair*.
|
||||
"""
|
||||
|
||||
harness.add()
|
||||
|
||||
reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
|
||||
|
||||
warps = harness.fake.sink.of("warp")
|
||||
assert len(warps) == 2, "a single warp does not move keyboard focus"
|
||||
# The second one is the bookmark, so a restore is not a few pixels off.
|
||||
assert (warps[1][2], warps[1][3]) == (0.5, 0.5)
|
||||
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.5, 0.5)
|
||||
# And they are different *floored* pixels at the frozen 1280x720 container
|
||||
# mode: `mouseMoveUnified` returns before it touches the delta when the
|
||||
# floored position has not changed.
|
||||
assert round(warps[0][3] * 720) != round(warps[1][3] * 720)
|
||||
assert reply["focus"] == "warp"
|
||||
|
||||
|
||||
def test_the_focus_mechanism_is_recorded_in_the_audit(harness):
|
||||
harness.add()
|
||||
|
||||
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
|
||||
|
||||
events = harness.manager.audit.tail(50, session="foot-aaaaaa")
|
||||
acquired = [e for e in events if e.get("event") == "pointer_acquired"][-1]
|
||||
# So a session that ends up typing into the wrong window can be told apart
|
||||
# from one that never tried to take focus.
|
||||
assert acquired["focus"] == "warp"
|
||||
@@ -114,10 +114,25 @@ def test_acquire_with_no_bookmark_aims_at_the_centre_of_the_container(harness):
|
||||
"output": "hh-foot-aaaaaa",
|
||||
"at": reply["bookmark"]["at"],
|
||||
}
|
||||
# TWO motions, and the order is the point. One warp onto an idle cursor
|
||||
# delivers wl_pointer.enter and no wl_keyboard.enter: Hyprland zeroes
|
||||
# `m_mousePosDelta` when the previous movement was over 0.5s ago, and
|
||||
# keyboard focus is that delta against `follow_mouse_threshold`. So the
|
||||
# nudge goes first and the real target second, the second motion carries a
|
||||
# non-zero delta, and the cursor finishes at the bookmark.
|
||||
assert harness.fake.sink.calls == [
|
||||
("warp", "hh-foot-aaaaaa", 0.5, 0.504),
|
||||
("frame", "hh-foot-aaaaaa"),
|
||||
("warp", "hh-foot-aaaaaa", 0.5, 0.5),
|
||||
("frame", "hh-foot-aaaaaa"),
|
||||
]
|
||||
# And the two really are different pixels at the frozen 1280x720 container
|
||||
# mode: `mouseMoveUnified` returns before it touches the delta when the
|
||||
# floored position has not changed, so a sub-pixel nudge would move the
|
||||
# cursor and leave the keys where they were.
|
||||
first, second = harness.fake.sink.of("warp")
|
||||
assert round(first[3] * 720) != round(second[3] * 720)
|
||||
assert reply["focus"] == "warp"
|
||||
|
||||
|
||||
def test_acquire_restores_the_position_the_session_was_left_at(harness):
|
||||
@@ -130,8 +145,15 @@ def test_acquire_restores_the_position_the_session_was_left_at(harness):
|
||||
reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
|
||||
|
||||
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.25, 0.75)
|
||||
assert harness.fake.sink.of("warp") == [("warp", "hh-foot-aaaaaa", 0.25, 0.75)]
|
||||
# The nudge, then the restored position. The bookmark is where the cursor
|
||||
# is left, so the second warp is the one that has to be the bookmark --
|
||||
# the reverse order would restore the session a few pixels off, every time.
|
||||
assert harness.fake.sink.of("warp") == [
|
||||
("warp", "hh-foot-aaaaaa", 0.25, 0.754),
|
||||
("warp", "hh-foot-aaaaaa", 0.25, 0.75),
|
||||
]
|
||||
assert session.pointer["bookmark"]["x"] == 0.25
|
||||
assert session.pointer["bookmark"]["y"] == 0.75
|
||||
|
||||
|
||||
def test_restore_false_goes_to_the_centre_even_with_a_bookmark(harness):
|
||||
@@ -365,6 +387,10 @@ def test_an_idle_lease_expires_and_the_button_it_left_down_is_lifted(harness):
|
||||
"session": "foot-aaaaaa",
|
||||
"lease_id": lease,
|
||||
"buttons_lifted": ["left"],
|
||||
# Empty, and reported rather than omitted: this lease held no key, and
|
||||
# "no keys were lifted" is a different answer from "keys were not
|
||||
# considered".
|
||||
"keys_lifted": [],
|
||||
}
|
||||
assert harness.manager.pointer.state()["holder"] is None
|
||||
assert harness.fake.sink.calls[-2:] == [
|
||||
@@ -441,7 +467,8 @@ def test_expiry_with_no_driver_is_loud_rather_than_silent(harness, caplog):
|
||||
with caplog.at_level("ERROR"):
|
||||
harness.run(harness.manager._expire_pointer())
|
||||
|
||||
assert "a button may still be down" in caplog.text
|
||||
assert "they may still be held" in caplog.text
|
||||
assert "buttons ['left']" in caplog.text
|
||||
assert harness.manager.pointer.state()["holder"] is None
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user