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