Merge keyboard input (feat/keyboard-input @561e0c2) for a live trial on this machine
The same shape as the merge that branch got on 2026-10-05 (edbf15f on
feat/session-live-stream): this machine's own config sets
`sessions.keyboard.layout`, so a ref without the keyboard work does not
evaluate -- and the point of this branch is to be consumed here.
The stream branch's own commit is the first parent, so PR #2 stays based on
main and carries none of this merge. Conflicts were additive on both sides
(new option blocks, new checks, new README rows) and are resolved by keeping
both.
This commit is contained in:
commit
994fdb1cfb
51 files changed
+8994
-233
No files matched your search
@@ -0,0 +1,260 @@
|
||||
# `keyboard_probe.py` — Stage 0 of the keyboard plan
|
||||
|
||||
Stage 0 of [`docs/plans/2026-10-03-keyboard-input.md`](../docs/plans/2026-10-03-keyboard-input.md),
|
||||
written to the probe spec in
|
||||
[`docs/plans/2026-10-04-keyboard-verification.md`](../docs/plans/2026-10-04-keyboard-verification.md)
|
||||
§B1. It measures the things neither plan would let Stage 1 guess at, and prints
|
||||
what it saw.
|
||||
|
||||
It is **throwaway**: delete it once `checks/vm-keyboard.nix` asserts the same
|
||||
properties in a VM. The review says not to commit it at all; the brief that
|
||||
commissioned this work says to commit it under `examples/` or `tests/` with a
|
||||
README, and that is what this is. Nothing downstream imports it.
|
||||
|
||||
It speaks to the compositor and to nothing else — **no broker, no lease, no
|
||||
`hhstreamd` control socket, no `hhstream` CLI, no session**. Read-only
|
||||
`hyprctl` (`clients -j`, `getoption -j`) is used so the warp hits a box it
|
||||
knows the coordinates of; `hyprctl dispatch` is never used, because
|
||||
`dispatch focuswindow` would answer (a) by cheating.
|
||||
|
||||
It does two things that are not read-only, because keyboard focus cannot be
|
||||
measured without them: it opens two small windows of its own, and it moves the
|
||||
one cursor. It refuses to send a key until it has seen `wl_keyboard.enter` on a
|
||||
surface it owns, and it lifts everything it pressed on the way out — including
|
||||
through a fresh virtual keyboard, because of what (b) turned out to be.
|
||||
|
||||
## Running it
|
||||
|
||||
It needs `pywayland` (the dev shell has it), `xkbcommon` (the dev shell does
|
||||
not, until Stage 1 adds it), `hyprctl`, and the protocol XML. One command, in
|
||||
the shape `hhstream_pointer._protocol.regenerate`'s docstring already uses for
|
||||
"this needs something the dev shell lacks":
|
||||
|
||||
```bash
|
||||
cd /var/lib/hermes/projects/hhstream-keyboard # or wherever this checkout is
|
||||
XML="$(nix eval --raw nixpkgs#hyprland.src)/protocols"
|
||||
|
||||
sg hhstream -c "HHSTREAM_PROTOCOL_DIR='$XML' PYTHONPATH=src \
|
||||
nix shell --impure --expr 'with (builtins.getFlake \"nixpkgs\").legacyPackages.\${builtins.currentSystem}; [ (python3.withPackages (p: [ p.pywayland p.xkbcommon ])) hyprland ]' \
|
||||
--command python3 tests/keyboard_probe.py"
|
||||
```
|
||||
|
||||
`sg hhstream` is not optional: `/run/hypr-stream` is `0750 hhstream:hhstream`,
|
||||
so a login that predates the group membership cannot open the Wayland socket at
|
||||
all. (The review's `sudo -u hermes -g hhstream env …` form does the same thing
|
||||
and also works; `sg` is what the brief asked for and needs no root.)
|
||||
`PYTHONPATH=src` is how it reaches the driver's already-vendored wlr *pointer*
|
||||
protocol rather than growing a second copy.
|
||||
|
||||
Flags: `--runtime-dir` (default `/run/hypr-stream`), `--xml`, `--output` (only
|
||||
needed if the compositor has more than one), `--xkb-layout`, `--xkb-model`.
|
||||
|
||||
### Where it deviates from the review's §B1 sequence
|
||||
|
||||
All three are visible in the transcript and none of them changes an answer:
|
||||
|
||||
- the keymap is uploaded **before** the windows are opened, not after. It has
|
||||
to be: the seat has no libinput keyboard, so `wl_seat.capabilities` does not
|
||||
include `keyboard` until a virtual one exists (the setup block goes `1` then
|
||||
`3`), and a listener bound any later would have seen nothing at all;
|
||||
- the idle wait before (a1) is 0.8 s rather than 0.6 s;
|
||||
- (a2) follows (a1) after the settle window and a print — measured at 0.401 s
|
||||
rather than being "immediate", and still inside the 0.5 s that matters.
|
||||
|
||||
Exit codes: **2** if `zwp_virtual_keyboard_manager_v1` is missing or is not
|
||||
version 1 — the gate the plan says stops the project — and 0 otherwise. The
|
||||
answers are in the output, not in the exit status: a measurement that came back
|
||||
"no" is still a successful measurement.
|
||||
|
||||
### Where the XML is, and where both plans say it is
|
||||
|
||||
Both plans say the XML is wayland-protocols'
|
||||
`unstable/virtual-keyboard/virtual-keyboard-unstable-v1.xml`, and the review's
|
||||
objection 4 says specifically *not* to use Hyprland's copy. **Neither is
|
||||
possible here.** Checked, on this machine:
|
||||
|
||||
| Source | Has it? |
|
||||
| --- | --- |
|
||||
| `wayland-protocols` 1.49 (this flake's own nixpkgs input), `unstable/`, `staging/`, `stable/` | no — there is no `virtual-keyboard` directory at all |
|
||||
| `pkgs.wlr-protocols` (nixpkgs' 2022-09-05 snapshot), output *and* `.src` | no — ten XMLs, the virtual *pointer* among them, not this one |
|
||||
| `pkgs.wlroots.src` | no |
|
||||
| `pkgs.hyprland.src` → `protocols/virtual-keyboard-unstable-v1.xml` | **yes, and it is the only copy** |
|
||||
|
||||
```bash
|
||||
echo "$(nix eval --raw nixpkgs#hyprland.src)/protocols/virtual-keyboard-unstable-v1.xml"
|
||||
```
|
||||
|
||||
So the probe, and Stage 1's vendoring, use the Hyprland copy. The review's
|
||||
reason for avoiding it is real and is handled rather than ignored: that copy
|
||||
*names* `keymap_format` and `key_state` in prose and never defines them, so the
|
||||
generated module carries no enum for either. Both are therefore written down as
|
||||
constants with a citation — in this file as `XKB_FORMAT_TEXT_V1` and
|
||||
`RELEASED`/`PRESSED`, and in the driver as `hhstream_pointer.keymap.XKB_V1`
|
||||
beside the existing `buttons.STATES` (which already holds the same two
|
||||
integers, as the review notes). Same class of correction
|
||||
`docs/CONTRACT-sessions.md` §3.4 already had to make for the wlr pointer XML
|
||||
path.
|
||||
|
||||
## What it answered
|
||||
|
||||
One run, 2026-10-04, against the live `/run/hypr-stream`: Hyprland 0.56.2, one
|
||||
output `Virtual-1` at 1280x720, two Chromium windows already on screen. The
|
||||
committed transcript is that run and nothing else —
|
||||
[`keyboard-probe-2026-10-04.txt`](keyboard-probe-2026-10-04.txt) — and every
|
||||
excerpt below is copied from it, with the line numbers to check it against. An
|
||||
earlier draft of this file claimed several reproductions and quoted a serial
|
||||
from a run it had not kept. If a claim here is not in that file, it is not
|
||||
evidence.
|
||||
|
||||
The configuration the answers depend on, as the compositor reports it:
|
||||
|
||||
```
|
||||
input:follow_mouse = 1 (set)
|
||||
input:follow_mouse_threshold = 0.0 (default)
|
||||
input:virtualkeyboard:release_pressed_on_close = 0 (default)
|
||||
input:repeat_rate = 25 (default)
|
||||
input:repeat_delay = 600 (default)
|
||||
input:kb_layout = us (default)
|
||||
```
|
||||
|
||||
### 1. The global — the gate the whole project hangs on
|
||||
|
||||
**`zwp_virtual_keyboard_manager_v1` is present at version 1** (transcript
|
||||
line 71, answered on line 76). §6.7's `[RAN]` claim holds against the running
|
||||
binary. `wp_virtual_keyboard_v1` is not
|
||||
advertised, as both plans predicted. `zwlr_virtual_pointer_manager_v1` is at
|
||||
v2, so the driver's existing version-2 requirement is still met. The project
|
||||
continues.
|
||||
|
||||
### (a) Does a virtual-pointer warp move `wl_keyboard` focus?
|
||||
|
||||
**One idle warp onto an unfocused window: NO.** It moved the cursor and
|
||||
nothing else. The keyboard focus change arrived only after a *later*
|
||||
`motion_absolute`, and it belongs to that motion rather than to the first.
|
||||
|
||||
Transcript, lines 104–120, unedited:
|
||||
|
||||
```
|
||||
box kb-probe-a at 0,0 size 1280x720
|
||||
box kb-probe-b at 120,80 size 1040x560
|
||||
focus at map time: kb-probe-b (expected kb-probe-b: it mapped last)
|
||||
(a1) target 0.0100,0.0100 (inside kb-probe-a only)
|
||||
(a2) target 0.0100,0.0140 — about 3px lower, so the FLOORED pixel changes. A second warp to the same point would return before mouseMoveUnified touched the delta, and would prove nothing.
|
||||
(a1) one warp after 0.8s of stillness
|
||||
(a1) -> wl_pointer.enter surface=kb-probe-a at 13,7
|
||||
(a2) a second warp, to the (a2) target above
|
||||
(a2) -> modifiers depressed=0 latched=0 locked=0 group=0
|
||||
(a2) -> leave surface=kb-probe-b
|
||||
(a2) -> enter surface=kb-probe-a serial=406 keys=[]
|
||||
(a2) -> modifiers depressed=0 latched=0 locked=0 group=0
|
||||
(a2) -> configured surface=kb-probe-b 1040x560
|
||||
(a2) -> configured surface=kb-probe-a 1280x720
|
||||
gap between the two motion_absolute calls: 0.401s (under Hyprland's 0.5s delta window)
|
||||
a1_enter=no a2_enter=yes pointer_reached_kb-probe-a=yes
|
||||
```
|
||||
|
||||
The sentence this supports, and no stronger one: **an idle `motion_absolute`
|
||||
onto unfocused `kb-probe-a` delivered `wl_pointer.enter` and no
|
||||
`wl_keyboard.enter`; `kb-probe-b`'s `leave` and `kb-probe-a`'s `enter` were
|
||||
observed only in the settle window after a later `motion_absolute` that stayed
|
||||
inside `kb-probe-a`.** Map-time focus was `kb-probe-b`, and the two boxes
|
||||
genuinely differ (`0,0 1280x720` against `120,80 1040x560`), so this is not the
|
||||
one-window false pass.
|
||||
|
||||
It is **not** "the enter was one warp late", which is what an earlier draft of
|
||||
this file said. The mechanism is in `InputManager.cpp` at v0.56.2:
|
||||
`mouseMoveUnified` returns before it touches `m_mousePosDelta` when the floored
|
||||
pixel did not change; the delta is *set to* 0 when the previous movement was
|
||||
more than 0.5 s ago; and keyboard focus compares that delta against
|
||||
`input:follow_mouse_threshold`, which the options block above shows is `0.0`
|
||||
and unset. So the first warp contributed nothing to the delta, and the second
|
||||
warp's own non-zero delta is what focused. Two consequences the draft got
|
||||
wrong:
|
||||
|
||||
- **A second warp to the same point is not the fix.** It returns early. (a2)
|
||||
moves about 3 px, deliberately, and the report prints both targets so a
|
||||
reader can see that it moved.
|
||||
- **"Immediately" was never measured.** The gap is 0.401 s, now printed, and it
|
||||
matters only because it is under the 0.5 s window.
|
||||
|
||||
**`pointer acquire` is one warp** (`src/hhstreamd/manager.py`, the `_warp` in
|
||||
`pointer_acquire`), so the first key of a lease can be delivered to whatever
|
||||
was already focused. Neither plan permits building the fallback in Stages 1–2
|
||||
(`docs/plans/2026-10-03-keyboard-input.md` §6 risk 1; the review's "Do not
|
||||
build it in Stage 1"), so Stages 1–2 do not, and the final report carries the
|
||||
objection. **Stage 3's enter subtest must not be written against acquire's
|
||||
single warp**, and it must not be made to pass by warping twice to the same
|
||||
bookmark.
|
||||
|
||||
Two false passes this probe itself walked into, both worth carrying into the VM
|
||||
check:
|
||||
|
||||
- `"enter surface=kb-probe-a" in line` also matches
|
||||
`wl_pointer.enter surface=kb-probe-a`, and an earlier version reported
|
||||
`a1_enter=yes` off a *pointer* event. The match is `startswith` now.
|
||||
- An earlier version used one window. A single mapped window is focused at map
|
||||
time, so it prints `enter` whatever the warp does.
|
||||
|
||||
### (b) Does destroying the virtual keyboard release a held key?
|
||||
|
||||
**No release: `release_on_destroy=no`** (transcript line 131), measured with a
|
||||
second virtual keyboard keeping the seat's keyboard capability up so a release
|
||||
had somewhere to be delivered, and with nothing of ours having sent a key-up
|
||||
before `destroy`. `input:virtualkeyboard:release_pressed_on_close` is `0` and
|
||||
unset, which is the default the review read out of `ConfigValues.cpp`.
|
||||
|
||||
**Read `mask_cleared=no` narrowly.** It says only that the post-destroy window
|
||||
contained no `modifiers` event. The held key was `KEY_A`, a letter, so the
|
||||
depressed mask was 0 for the whole run — **this is not a measurement of a
|
||||
non-zero mask surviving `destroy`**, and an earlier draft of this file claimed
|
||||
it was. `releasePressed` in `VirtualKeyboard.cpp` emits key-ups only and never
|
||||
a `modifiers`, so the source still says a mask would survive; it is simply not
|
||||
what this transcript shows. `release_all` sends `modifiers(0, 0, 0, 0)` for
|
||||
that reason, not because of this line.
|
||||
|
||||
The confirming evidence is the *cleanup*, transcript lines 136–138:
|
||||
|
||||
```
|
||||
cleanup -> uploaded keymap format=1 size=35572
|
||||
cleanup -> key code=30 state=0 sym=a
|
||||
cleanup -> modifiers depressed=0 latched=0 locked=0 group=0
|
||||
```
|
||||
|
||||
`InputManager::onKeyboardKey` **drops** a release whose code is not in the
|
||||
seat's `m_pressed`. A `state=0` for code 30 that the client actually received,
|
||||
sent from a *brand new* virtual keyboard, therefore means 30 was still in that
|
||||
set after `destroy`. Had destroy released it, that cleanup key-up would have
|
||||
been dropped and nothing would have reached the client.
|
||||
|
||||
One thing the transcript does **not** contain, and which this file used to cite:
|
||||
an earlier, unkept run whose first `wl_keyboard.enter` carried
|
||||
`keys=[42, 0, 0, 0]`. Every `enter` in the committed log is `keys=[]`.
|
||||
|
||||
So this is worse than "a key stays down": the code stays in `m_pressed`, and
|
||||
`onKeyboardKey` also drops a *press* whose code is already there — the next
|
||||
driver's `key down` for it is ignored, and the key is dead until something
|
||||
sends a matching up. Handled in Stage 2 by
|
||||
`input:virtualkeyboard:release_pressed_on_close = true` in
|
||||
`nix/hyprland-conf.nix` (the review's change 4), with the explicit note that
|
||||
the setting releases keys and still does not clear the modifier mask — which is
|
||||
why `release_all` ends with `modifiers(0, 0, 0, 0)` on the clean path
|
||||
regardless.
|
||||
|
||||
### (c) Does Hyprland auto-repeat a held virtual key?
|
||||
|
||||
**`press_count=1`, `repeat_info rate=25 delay=600`** (transcript lines
|
||||
124–125). A key left down for `REPEAT_HOLD_S = 1.5` s — longer than the 600 ms
|
||||
delay, not shorter — produced exactly one `key code=30 state=1` and no
|
||||
`state=2`. A compositor repeating at 25 Hz after 600 ms would have added about
|
||||
twenty more lines in the remaining 0.9 s; it added none. `repeat_info` arrives
|
||||
at bind time, before the hold, and is printed next to the count because the
|
||||
review asked for both — not because the compositor repeated.
|
||||
|
||||
This is **not** "`keyboard down` will not flood a text field", and reading it
|
||||
that way is the review's named false pass. The compositor does not repeat on
|
||||
the wire; it publishes a rate and the *client* repeats. A focused foot, GTK or
|
||||
Qt text field will insert characters from that one press until the key-up or
|
||||
the lease TTL (default 30 s). So `keyboard down` of a non-modifier warns
|
||||
unconditionally in the CLI help, and v1 has no repeat rate to offer because we
|
||||
do not generate the repeats. `zwp_virtual_keyboard_v1` has no `repeated` state
|
||||
and there is nothing to ask the compositor for.
|
||||
@@ -0,0 +1,141 @@
|
||||
keyboard_probe.py, run 2026-10-04 against the live /run/hypr-stream.
|
||||
Hyprland 0.56.2, one output Virtual-1 at 1280x720, two Chromium windows
|
||||
already on screen. Verbatim; nothing edited.
|
||||
|
||||
=== 1. globals on this compositor ===
|
||||
global ext_background_effect_manager_v1 v1
|
||||
global ext_data_control_manager_v1 v1
|
||||
global ext_foreign_toplevel_image_capture_source_manager_v1 v1
|
||||
global ext_foreign_toplevel_list_v1 v1
|
||||
global ext_idle_notifier_v1 v2
|
||||
global ext_image_copy_capture_manager_v1 v1
|
||||
global ext_output_image_capture_source_manager_v1 v1
|
||||
global ext_session_lock_manager_v1 v1
|
||||
global ext_workspace_manager_v1 v1
|
||||
global hyprland_ctm_control_manager_v1 v2
|
||||
global hyprland_focus_grab_manager_v1 v1
|
||||
global hyprland_global_shortcuts_manager_v1 v1
|
||||
global hyprland_input_capture_manager_v1 v1
|
||||
global hyprland_lock_notifier_v1 v1
|
||||
global hyprland_surface_manager_v1 v2
|
||||
global hyprland_toplevel_export_manager_v1 v2
|
||||
global hyprland_toplevel_mapping_manager_v1 v1
|
||||
global org_kde_kwin_server_decoration_manager v1
|
||||
global vicinae_hotkey_manager_v1 v1
|
||||
global wl_compositor v6
|
||||
global wl_data_device_manager v3
|
||||
global wl_drm v2
|
||||
global wl_output v4
|
||||
global wl_seat v9
|
||||
global wl_shm v2
|
||||
global wl_subcompositor v1
|
||||
global wp_alpha_modifier_v1 v1
|
||||
global wp_color_manager_v1 v3
|
||||
global wp_commit_timing_manager_v1 v1
|
||||
global wp_content_type_manager_v1 v1
|
||||
global wp_cursor_shape_manager_v1 v2
|
||||
global wp_drm_lease_device_v1 v1
|
||||
global wp_fifo_manager_v1 v1
|
||||
global wp_fractional_scale_manager_v1 v1
|
||||
global wp_pointer_warp_v1 v1
|
||||
global wp_presentation v2
|
||||
global wp_security_context_manager_v1 v1
|
||||
global wp_single_pixel_buffer_manager_v1 v1
|
||||
global wp_tearing_control_manager_v1 v1
|
||||
global wp_viewporter v1
|
||||
global xdg_activation_v1 v1
|
||||
global xdg_system_bell_v1 v1
|
||||
global xdg_toplevel_tag_manager_v1 v1
|
||||
global xdg_wm_base v7
|
||||
global xdg_wm_dialog_v1 v1
|
||||
global xwayland_shell_v1 v1
|
||||
global zwlr_data_control_manager_v1 v2
|
||||
global zwlr_foreign_toplevel_manager_v1 v3
|
||||
global zwlr_gamma_control_manager_v1 v1
|
||||
global zwlr_layer_shell_v1 v5
|
||||
global zwlr_output_manager_v1 v4
|
||||
global zwlr_output_power_manager_v1 v1
|
||||
global zwlr_screencopy_manager_v1 v3
|
||||
global zwlr_virtual_pointer_manager_v1 v2
|
||||
global zwp_idle_inhibit_manager_v1 v1
|
||||
global zwp_input_method_manager_v2 v1
|
||||
global zwp_keyboard_shortcuts_inhibit_manager_v1 v1
|
||||
global zwp_linux_dmabuf_v1 v5
|
||||
global zwp_pointer_constraints_v1 v1
|
||||
global zwp_pointer_gestures_v1 v3
|
||||
global zwp_primary_selection_device_manager_v1 v1
|
||||
global zwp_relative_pointer_manager_v1 v1
|
||||
global zwp_tablet_manager_v2 v1
|
||||
global zwp_text_input_manager_v1 v1
|
||||
global zwp_text_input_manager_v3 v1
|
||||
global zwp_virtual_keyboard_manager_v1 v1
|
||||
global zxdg_decoration_manager_v1 v2
|
||||
global zxdg_exporter_v2 v1
|
||||
global zxdg_importer_v2 v1
|
||||
global zxdg_output_manager_v1 v3
|
||||
ANSWER 1: zwp_virtual_keyboard_manager_v1 is present at version 1.
|
||||
zwlr_virtual_pointer_manager_v1 v2 (needed for (a)).
|
||||
setup -> seat capabilities=1
|
||||
setup -> seat capabilities=3
|
||||
setup -> uploaded keymap format=1 size=35572
|
||||
setup -> wl_keyboard.keymap format=1 bytes=35572 symbols=xkb_symbols "pc_us_inet(evdev)" {
|
||||
setup -> repeat_info rate=25 delay=600
|
||||
setup -> configured surface=kb-probe-a 640x360
|
||||
setup -> enter surface=kb-probe-a serial=392 keys=[]
|
||||
setup -> modifiers depressed=0 latched=0 locked=0 group=0
|
||||
setup -> configured surface=kb-probe-a 1280x720
|
||||
setup -> configured surface=kb-probe-b 640x360
|
||||
setup -> modifiers depressed=0 latched=0 locked=0 group=0
|
||||
setup -> leave surface=kb-probe-a
|
||||
setup -> enter surface=kb-probe-b serial=400 keys=[]
|
||||
setup -> modifiers depressed=0 latched=0 locked=0 group=0
|
||||
setup -> configured surface=kb-probe-b 1040x560
|
||||
setup -> configured surface=kb-probe-a 1280x720
|
||||
|
||||
=== (a) does a virtual-pointer warp move wl_keyboard focus? ===
|
||||
options this measurement depends on:
|
||||
input:follow_mouse = {"int": 1, "option": "input:follow_mouse", "set": true}
|
||||
input:follow_mouse_threshold = {"float": 0.0, "option": "input:follow_mouse_threshold", "set": false}
|
||||
input:virtualkeyboard:release_pressed_on_close = {"int": 0, "option": "input:virtualkeyboard:release_pressed_on_close", "set": false}
|
||||
input:repeat_rate = {"int": 25, "option": "input:repeat_rate", "set": false}
|
||||
input:repeat_delay = {"int": 600, "option": "input:repeat_delay", "set": false}
|
||||
input:kb_layout = {"option": "input:kb_layout", "set": false, "str": "us"}
|
||||
output Virtual-1 mode 1280x720
|
||||
box kb-probe-a at 0,0 size 1280x720
|
||||
box kb-probe-b at 120,80 size 1040x560
|
||||
focus at map time: kb-probe-b (expected kb-probe-b: it mapped last)
|
||||
(a1) target 0.0100,0.0100 (inside kb-probe-a only)
|
||||
(a2) target 0.0100,0.0140 — about 3px lower, so the FLOORED pixel changes. A second warp to the same point would return before mouseMoveUnified touched the delta, and would prove nothing.
|
||||
(a1) one warp after 0.8s of stillness
|
||||
(a1) -> wl_pointer.enter surface=kb-probe-a at 13,7
|
||||
(a2) a second warp, to the (a2) target above
|
||||
(a2) -> modifiers depressed=0 latched=0 locked=0 group=0
|
||||
(a2) -> leave surface=kb-probe-b
|
||||
(a2) -> enter surface=kb-probe-a serial=406 keys=[]
|
||||
(a2) -> modifiers depressed=0 latched=0 locked=0 group=0
|
||||
(a2) -> configured surface=kb-probe-b 1040x560
|
||||
(a2) -> configured surface=kb-probe-a 1280x720
|
||||
gap between the two motion_absolute calls: 0.401s (under Hyprland's 0.5s delta window)
|
||||
a1_enter=no a2_enter=yes pointer_reached_kb-probe-a=yes
|
||||
ANSWER (a): the idle warp onto unfocused kb-probe-a delivered wl_pointer.enter and NO wl_keyboard.enter. kb-probe-b's leave and kb-probe-a's enter arrived only after the LATER motion_absolute, the one that changed the floored pixel -- so the enter belongs to that motion's non-zero m_mousePosDelta and is NOT a delayed effect of the first warp.
|
||||
Consequence: `pointer acquire` is one warp, so the first key of a lease can land in whatever was already focused. Stage 3's enter subtest must not be written against acquire's single warp, and warping twice to the same bookmark is not the fix -- the same floored pixel returns early.
|
||||
|
||||
=== (c) is one held virtual key one wl_keyboard.key? ===
|
||||
key code=30 state=1 sym=a
|
||||
press_count=1 repeat_info=(25, 600)
|
||||
ANSWER (c): press_count=1 — the compositor does not repeat on the wire; it published repeat_info (25, 600) and the CLIENT repeats. This is NOT 'keyboard down will not flood a text field': foot/GTK/Qt will insert characters from this one press until the key-up or the lease TTL. The help text must warn unconditionally.
|
||||
(key code=30 deliberately left down, for (b))
|
||||
|
||||
=== (b) does destroying the virtual keyboard release a held key? ===
|
||||
spare -> uploaded keymap format=1 size=35572
|
||||
release_on_destroy=no mask_cleared=no
|
||||
(compare with input:virtualkeyboard:release_pressed_on_close, printed above)
|
||||
ANSWER (b): NO RELEASE — destroy delivered no key-up, with a second keyboard keeping the seat's capability up and with nothing of ours having sent an up beforehand.
|
||||
Read `mask_cleared` narrowly: it says only that destroy emitted no `modifiers` event. The held key is a letter, so the depressed mask was 0 throughout -- this is NOT a measurement of a non-zero mask surviving destroy. releasePressed emits key-ups only (VirtualKeyboard.cpp), which is why release_all sends modifiers(0,0,0,0) regardless.
|
||||
The confirming evidence is the cleanup below: onKeyboardKey DROPS a release whose code is not in the seat's m_pressed, so a `key code=30 state=0` arriving from a BRAND NEW keyboard means the code was still in that set after destroy. A driver killed with -9 leaves it there and the next driver's press of it is dropped: dead, not merely stuck. _lift_everything is the only guard on the clean path and SIGKILL skips it.
|
||||
cleanup -> uploaded keymap format=1 size=35572
|
||||
cleanup -> key code=30 state=0 sym=a
|
||||
cleanup -> modifiers depressed=0 latched=0 locked=0 group=0
|
||||
cleanup=sent
|
||||
|
||||
Done. Nothing here touched the broker, the lease or any session.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,363 @@
|
||||
"""The driver's XKB flags — the only path a layout has to the uploaded keymap.
|
||||
|
||||
This file exists where a `tests/sessions/unit/test_settings.py` case would have
|
||||
gone, and that is the point. The broker's TOML is read by `hhstreamd` for its
|
||||
lease numbers; `hhstream-pointer` is a different unit and never opens that
|
||||
file. So a `[keyboard]` table there would be a setting an operator could change
|
||||
with no effect at all, and a test asserting its default would be green while
|
||||
every injected key stayed on `us`.
|
||||
|
||||
The layout therefore arrives as `--xkb-layout`, and these are the assertions
|
||||
about that flag: what it defaults to, that a bad value is exit **2**, and that
|
||||
a bad value is exit 2 **without the compositor being touched** — because a
|
||||
layout xkbcommon will not compile is the operator's typo, and reporting it as
|
||||
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
|
||||
|
||||
|
||||
class _Unreached(Exception):
|
||||
"""Raised if the Wayland side is reached when it should not have been."""
|
||||
|
||||
|
||||
class _RefusingSink:
|
||||
"""A sink that fails the test if anything asks it to talk to a compositor.
|
||||
|
||||
The review asked for an injected connect that can be asserted *not* to have
|
||||
been called; this is that, as a type rather than a flag, so a future code
|
||||
path that connects earlier fails loudly instead of silently reordering
|
||||
start-up.
|
||||
"""
|
||||
|
||||
instances = 0
|
||||
|
||||
def __init__(self, runtime_dir, display_name=None) -> None:
|
||||
type(self).instances += 1
|
||||
|
||||
def connect(self) -> None:
|
||||
raise _Unreached("connect")
|
||||
|
||||
def upload_keymap(self, text: str) -> None:
|
||||
raise _Unreached("upload_keymap")
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def no_compositor(monkeypatch):
|
||||
_RefusingSink.instances = 0
|
||||
monkeypatch.setattr(entry, "WaylandSink", _RefusingSink)
|
||||
return _RefusingSink
|
||||
|
||||
|
||||
# -- defaults ---------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_xkb_flags_default_to_the_frozen_values():
|
||||
args = entry.build_parser().parse_args([])
|
||||
assert args.xkb_layout == "us"
|
||||
assert args.xkb_model == "pc105"
|
||||
assert (args.xkb_variant, args.xkb_options) == ("", "")
|
||||
|
||||
|
||||
def test_the_defaults_are_the_ones_the_module_option_defaults_to():
|
||||
# Stated as constants so the NixOS option and the hand-run binary cannot
|
||||
# drift into typing different characters.
|
||||
assert (entry.DEFAULT_LAYOUT, entry.DEFAULT_MODEL) == ("us", "pc105")
|
||||
|
||||
|
||||
def test_a_layout_is_taken_from_the_flag():
|
||||
assert entry.build_parser().parse_args(["--xkb-layout", "de"]).xkb_layout == "de"
|
||||
|
||||
|
||||
def test_the_contract_command_line_still_parses():
|
||||
"""CONTRACT-sessions.md §3.4's exact line, plus the keymap flags."""
|
||||
|
||||
args = entry.build_parser().parse_args(
|
||||
[
|
||||
"--socket",
|
||||
"/run/hhstream/pointer.sock",
|
||||
"--compositor-runtime-dir",
|
||||
"/run/hypr-stream",
|
||||
"--xkb-layout",
|
||||
"us",
|
||||
"--xkb-model",
|
||||
"pc105",
|
||||
"--xkb-variant",
|
||||
"",
|
||||
"--xkb-options",
|
||||
"",
|
||||
]
|
||||
)
|
||||
assert str(args.socket) == "/run/hhstream/pointer.sock"
|
||||
assert str(args.compositor_runtime_dir) == "/run/hypr-stream"
|
||||
assert args.xkb_layout == "us"
|
||||
|
||||
|
||||
# -- refusals, before any Wayland call --------------------------------------
|
||||
|
||||
|
||||
def test_a_comma_separated_layout_exits_2_without_connecting(no_compositor, caplog):
|
||||
"""v1 sends group 0 in every `modifiers`, so a second group is unreachable.
|
||||
|
||||
xkbcommon accepts `us,ru` and hands back a two-group keymap, so nothing
|
||||
downstream would notice: a caller asking for Cyrillic would get Latin and
|
||||
no error. Refused here, and the NixOS option's type refuses it too — this
|
||||
one is for the binary run by hand, which that type cannot reach.
|
||||
"""
|
||||
|
||||
code = entry.main(["--xkb-layout", "us,ru"])
|
||||
|
||||
assert code == entry.EXIT_USAGE
|
||||
assert no_compositor.instances == 0, "the compositor must not be touched"
|
||||
|
||||
|
||||
def test_a_layout_xkbcommon_rejects_exits_2_without_connecting(no_compositor):
|
||||
code = entry.main(["--xkb-layout", "zzz-no-such-layout"])
|
||||
|
||||
assert code == entry.EXIT_USAGE
|
||||
assert no_compositor.instances == 0
|
||||
|
||||
|
||||
def test_a_usable_layout_gets_as_far_as_the_compositor(no_compositor):
|
||||
"""The other half: exit 2 must not be how a *good* layout fails.
|
||||
|
||||
A test that only asserted the refusals would pass against a `main` that
|
||||
returned 2 for everything, so this one proves the good path reaches the
|
||||
Wayland side and fails there instead.
|
||||
"""
|
||||
|
||||
with pytest.raises(_Unreached, match="connect"):
|
||||
entry.main(["--xkb-layout", "us"])
|
||||
assert no_compositor.instances == 1
|
||||
|
||||
|
||||
def test_the_exit_codes_match_the_brokers_table():
|
||||
"""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
|
||||
@@ -0,0 +1,331 @@
|
||||
"""Keysym names and text to ``(evdev code, modifier mask)``, against real xkbcommon.
|
||||
|
||||
A real keymap, not a stub, and that is the whole design of this file. A stub
|
||||
can be made to agree with any resolver; only xkbcommon can tell you that ``é``
|
||||
is unmappable on ``us``, that ``@`` on ``de`` is a *level-three* symbol rather
|
||||
than a shifted one, and that ``y`` and ``z`` swap keycodes between the two.
|
||||
Those three facts are what the resolver exists for, so ``xkbcommon`` is a hard
|
||||
dependency (``pyproject.toml`` says why) and these tests do not skip.
|
||||
|
||||
Codes here are **evdev**, never XKB. ``a`` is 30 and not 38: 30 is what
|
||||
``zwp_virtual_keyboard_v1.key`` carries and what the client reads back off
|
||||
``wl_keyboard.key``, and asserting 38 would be asserting an internal index that
|
||||
never reaches the wire.
|
||||
|
||||
Masks are read out of the keymap, never written down. ``A`` needs
|
||||
``1 << mod_get_index("Shift")``, which happens to be 1 on every layout here —
|
||||
so the test computes it, because a hard-coded 1 passes today and is wrong the
|
||||
first time a resolver is asked for a level-three character.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstream_pointer import keymap as keymaps
|
||||
from hhstream_pointer.ops import KIND_INVALID, Dispatcher
|
||||
|
||||
#: evdev codes from ``linux/input-event-codes.h``, spelled out so a failure
|
||||
#: reads against the header rather than against another part of this suite.
|
||||
KEY_A = 30
|
||||
KEY_ENTER = 28
|
||||
KEY_TAB = 15
|
||||
KEY_LEFTSHIFT = 42
|
||||
KEY_Y = 21 # the physical key that is `y` on us and `z` on de
|
||||
KEY_Z = 44 # ...and `z` on us, `y` on de
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def us() -> keymaps.Keymap:
|
||||
return keymaps.build(layout="us")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def de() -> keymaps.Keymap:
|
||||
return keymaps.build(layout="de")
|
||||
|
||||
|
||||
def shift_mask(keymap: keymaps.Keymap) -> int:
|
||||
"""Shift's bit, asked of the keymap rather than assumed to be 1."""
|
||||
|
||||
return 1 << keymap._keymap.mod_get_index("Shift")
|
||||
|
||||
|
||||
# -- the letter path --------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_lower_case_letter_is_its_evdev_code_and_no_modifier(us):
|
||||
action = us.resolve_name("a")
|
||||
assert (action.code, action.mask) == (KEY_A, 0)
|
||||
|
||||
|
||||
def test_a_capital_is_the_same_code_with_shift_in_the_mask(us):
|
||||
action = us.resolve_name("A")
|
||||
assert action.code == KEY_A
|
||||
assert action.mask == shift_mask(us)
|
||||
# The point of the mask: a capital is NOT a Shift keycode. Hyprland's
|
||||
# virtual keyboard never runs updateXkbStateWithKey, so a synthetic
|
||||
# KEY_LEFTSHIFT would change no modifier state at all.
|
||||
assert action.code != KEY_LEFTSHIFT
|
||||
|
||||
|
||||
def test_shift_is_a_key_in_its_own_right_with_no_mask_of_its_own(us):
|
||||
action = us.resolve_name("Shift_L")
|
||||
# Pressing Shift needs no modifier held; what it *contributes* is separate.
|
||||
assert (action.code, action.mask) == (KEY_LEFTSHIFT, 0)
|
||||
assert us.is_modifier("Shift_L")
|
||||
assert us.modifier_mask("Shift_L") == shift_mask(us)
|
||||
|
||||
|
||||
# -- the named keys ---------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name, code",
|
||||
[("Return", KEY_ENTER), ("Tab", KEY_TAB), ("BackSpace", 14), ("Left", 105)],
|
||||
)
|
||||
def test_a_named_keysym_resolves_to_its_evdev_code(us, name, code):
|
||||
assert us.resolve_name(name).code == code
|
||||
|
||||
|
||||
@pytest.mark.parametrize("character, code", [("\n", KEY_ENTER), ("\t", KEY_TAB)])
|
||||
def test_the_two_allowed_control_characters_are_named_keys(us, character, code):
|
||||
(action,) = us.resolve_text(character)
|
||||
assert action.code == code
|
||||
assert action.mask == 0
|
||||
|
||||
|
||||
def test_a_carriage_return_is_refused_rather_than_aliased_to_return(us):
|
||||
"""Only `\n` and `\t` are exempt from the C0 rule.
|
||||
|
||||
A `\r` silently typed as Return means a caller who pasted CRLF gets two
|
||||
newlines per line and no way to find out, so it is refused with the rest
|
||||
of the C0 block.
|
||||
"""
|
||||
|
||||
with pytest.raises(keymaps.UnknownKey) as caught:
|
||||
us.resolve_text("\r")
|
||||
assert "scalar 0" in str(caught.value)
|
||||
assert "U+000D" in str(caught.value)
|
||||
|
||||
|
||||
def test_an_empty_string_is_no_actions_and_not_an_error(us):
|
||||
assert us.resolve_text("") == []
|
||||
|
||||
|
||||
# -- refusals ---------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("character", ["é", "ü", "😀", "\x01", "\x1b", "\x7f"])
|
||||
def test_a_character_this_layout_cannot_produce_is_refused(us, character):
|
||||
with pytest.raises(keymaps.UnknownKey) as caught:
|
||||
us.resolve_text(character)
|
||||
message = str(caught.value)
|
||||
# The index and the codepoint, and NOT the character: this message reaches
|
||||
# the driver's log, and the string it came from is a password as often as
|
||||
# not.
|
||||
assert "scalar 0" in message
|
||||
assert character not in message
|
||||
|
||||
|
||||
def test_the_refusal_names_the_index_of_the_offending_scalar(us):
|
||||
with pytest.raises(keymaps.UnknownKey) as caught:
|
||||
us.resolve_text("abcé")
|
||||
assert "scalar 3" in str(caught.value)
|
||||
assert "é" not in str(caught.value)
|
||||
|
||||
|
||||
def test_a_dead_keysym_is_refused_by_name(us):
|
||||
with pytest.raises(keymaps.UnknownKey) as caught:
|
||||
us.resolve_name("dead_acute")
|
||||
assert "dead key" in str(caught.value)
|
||||
|
||||
|
||||
def test_an_unknown_keysym_name_is_refused(us):
|
||||
with pytest.raises(keymaps.UnknownKey):
|
||||
us.resolve_name("NoSuchKeysymAtAll")
|
||||
|
||||
|
||||
def test_an_empty_layout_is_refused_rather_than_compiled_as_us():
|
||||
"""xkbcommon compiles `""` as the *same keymap as `us`*.
|
||||
|
||||
So `--xkb-layout ''` would look configured, type `us`, and never say
|
||||
otherwise -- the same class of silent-wrong-layout as the comma below.
|
||||
"""
|
||||
|
||||
with pytest.raises(keymaps.KeymapError) as caught:
|
||||
keymaps.build(layout="")
|
||||
assert "layout" in str(caught.value)
|
||||
|
||||
|
||||
def test_a_comma_separated_layout_is_refused_before_anything_is_compiled():
|
||||
# xkbcommon accepts `us,ru` happily and hands back a two-group keymap. v1
|
||||
# always sends group 0, so the second group would be silently unreachable:
|
||||
# a caller asking for Cyrillic would get Latin and no error.
|
||||
with pytest.raises(keymaps.KeymapError) as caught:
|
||||
keymaps.build(layout="us,ru")
|
||||
assert "group" in str(caught.value)
|
||||
|
||||
|
||||
def test_a_layout_xkbcommon_rejects_is_a_keymap_error_naming_it():
|
||||
with pytest.raises(keymaps.KeymapError) as caught:
|
||||
keymaps.build(layout="zzz-no-such-layout")
|
||||
assert "zzz-no-such-layout" in str(caught.value)
|
||||
|
||||
|
||||
# -- the cap ----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_cap_is_exactly_at_the_limit(us):
|
||||
assert len(us.resolve_text("a" * keymaps.MAX_TEXT_SCALARS)) == keymaps.MAX_TEXT_SCALARS
|
||||
|
||||
|
||||
def test_one_scalar_over_the_cap_is_refused(us):
|
||||
with pytest.raises(keymaps.UnknownKey) as caught:
|
||||
us.resolve_text("a" * (keymaps.MAX_TEXT_SCALARS + 1))
|
||||
assert str(keymaps.MAX_TEXT_SCALARS) in str(caught.value)
|
||||
|
||||
|
||||
def test_the_cap_counts_scalars_and_not_bytes(us):
|
||||
# 4096 astral-plane scalars are 16384 UTF-8 bytes. A byte cap would refuse
|
||||
# this for being too long; the scalar cap lets it through to the character
|
||||
# check, which refuses it for being unmappable instead. The distinction is
|
||||
# the whole test: a byte cap and a scalar cap agree on ASCII, so only a
|
||||
# non-ASCII case can tell them apart.
|
||||
text = "😀" * keymaps.MAX_TEXT_SCALARS
|
||||
assert len(text) == keymaps.MAX_TEXT_SCALARS
|
||||
assert len(text.encode("utf-8")) > keymaps.MAX_TEXT_SCALARS
|
||||
with pytest.raises(keymaps.UnknownKey) as caught:
|
||||
us.resolve_text(text)
|
||||
assert "scalar 0" in str(caught.value)
|
||||
assert "limit" not in str(caught.value)
|
||||
|
||||
|
||||
# -- the modifier set -------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_modifier_set_is_measured_and_not_empty(us):
|
||||
assert us.modifier_names() == keymaps.EXPECTED_MODIFIERS
|
||||
|
||||
|
||||
def test_a_lock_is_not_a_modifier(us):
|
||||
# Caps_Lock reports a *locked* mask, so `type` refuses while it is held
|
||||
# rather than producing a case nobody asked for.
|
||||
assert us.lock_names() == keymaps.EXPECTED_LOCKS
|
||||
for name in keymaps.EXPECTED_LOCKS:
|
||||
assert not us.is_modifier(name)
|
||||
assert us.modifier_mask(name) == 0
|
||||
|
||||
|
||||
def test_control_contributes_the_bit_the_keymap_gives_control(us):
|
||||
"""The *right* bit, not merely a different one from Shift's.
|
||||
|
||||
"not 0 and not Shift" is satisfied by Alt's bit, and every wire assertion
|
||||
compares against `modifier_mask(...)` -- so a consistently wrong bit would
|
||||
be consistently wrong and green. This asks the keymap for the index.
|
||||
"""
|
||||
|
||||
expected = 1 << us._keymap.mod_get_index("Control")
|
||||
assert us.modifier_mask("Control_L") == expected
|
||||
assert us.modifier_mask("Control_R") == expected
|
||||
assert expected not in (0, shift_mask(us))
|
||||
|
||||
|
||||
# -- a second layout, which is what stops a Shift special case ---------------
|
||||
|
||||
|
||||
def test_de_swaps_y_and_z_against_us(us, de):
|
||||
assert (us.resolve_name("y").code, us.resolve_name("z").code) == (KEY_Y, KEY_Z)
|
||||
# Same keysyms, other codes: a resolver with a table beside the keymap
|
||||
# rather than inside it would return the us answer here.
|
||||
assert (de.resolve_name("y").code, de.resolve_name("z").code) == (KEY_Z, KEY_Y)
|
||||
|
||||
|
||||
def test_on_de_the_at_sign_needs_a_level_three_mask_not_shift(us, de):
|
||||
at_us = us.resolve_text("@")[0]
|
||||
at_de = de.resolve_text("@")[0]
|
||||
assert at_us.mask == shift_mask(us)
|
||||
# The case a Shift-only special case gets wrong: `@` is AltGr+q on de.
|
||||
assert at_de.mask not in (0, shift_mask(de))
|
||||
assert at_de.mask == de.modifier_mask("ISO_Level3_Shift")
|
||||
|
||||
|
||||
def test_a_character_us_cannot_type_is_ordinary_on_de(us, de):
|
||||
with pytest.raises(keymaps.UnknownKey):
|
||||
us.resolve_text("ü")
|
||||
(action,) = de.resolve_text("ü")
|
||||
assert action.name == "udiaeresis"
|
||||
assert action.mask == 0
|
||||
|
||||
|
||||
# -- the keymap text we upload ----------------------------------------------
|
||||
|
||||
|
||||
def test_the_keymap_text_is_an_xkb_keymap_naming_its_layout(us, de):
|
||||
assert us.text().lstrip().startswith("xkb_keymap {")
|
||||
# The exact symbols names, not `"us" in ...` -- which is true of every
|
||||
# us-family map and would stay true of a `de` keymap that had silently
|
||||
# compiled as `us`. These are also the strings the VM check should grep,
|
||||
# so they are written down once here.
|
||||
assert 'xkb_symbols "pc_us_inet(evdev)"' in _symbols_line(us)
|
||||
assert 'xkb_symbols "pc_de_inet(evdev)"' in _symbols_line(de)
|
||||
|
||||
|
||||
def _symbols_line(keymap: keymaps.Keymap) -> str:
|
||||
return next(line for line in keymap.text().splitlines() if "xkb_symbols" in line)
|
||||
|
||||
|
||||
# -- through the dispatcher: nothing is emitted for a bad string -------------
|
||||
|
||||
|
||||
class _Sink:
|
||||
"""Just enough of :class:`hhstream_pointer.ops.PointerSink` to count calls."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple] = []
|
||||
|
||||
def has_keyboard(self) -> bool:
|
||||
return True
|
||||
|
||||
def key(self, code, state):
|
||||
self.calls.append(("key", code, state))
|
||||
|
||||
def modifiers(self, depressed, latched, locked, group):
|
||||
self.calls.append(("modifiers", depressed, latched, locked, group))
|
||||
|
||||
|
||||
def test_an_unmappable_character_emits_nothing_through_the_dispatcher(us):
|
||||
sink = _Sink()
|
||||
reply = Dispatcher(sink, us).handle({"op": "type", "text": "abcé"})
|
||||
assert reply["ok"] is False
|
||||
# The assertion that matters: not "no event carried é" -- which would also
|
||||
# pass if a, b and c had been typed -- but that the sink was never called.
|
||||
assert sink.calls == []
|
||||
assert reply["kind"] == KIND_INVALID
|
||||
|
||||
|
||||
def test_a_string_over_the_cap_emits_nothing_through_the_dispatcher(us):
|
||||
sink = _Sink()
|
||||
reply = Dispatcher(sink, us).handle(
|
||||
{"op": "type", "text": "a" * (keymaps.MAX_TEXT_SCALARS + 1)}
|
||||
)
|
||||
assert reply["ok"] is False
|
||||
assert reply["kind"] == KIND_INVALID
|
||||
assert sink.calls == []
|
||||
|
||||
|
||||
def test_the_keymap_object_is_built_once_and_reused_across_types(us):
|
||||
"""Two ``type``s, one keymap.
|
||||
|
||||
The false pass this guards is a backend that recompiles and re-*uploads*
|
||||
per string: a second ``keymap`` request replaces Hyprland's XKB state
|
||||
without walking the keys it believes are down, so re-uploading under a held
|
||||
modifier strands it. The dispatcher is handed one object and never asks for
|
||||
another, which is what makes the single upload in ``__main__`` sufficient.
|
||||
"""
|
||||
|
||||
sink = _Sink()
|
||||
dispatcher = Dispatcher(sink, us)
|
||||
assert dispatcher.handle({"op": "type", "text": "a"})["ok"] is True
|
||||
assert dispatcher.handle({"op": "type", "text": "b"})["ok"] is True
|
||||
assert dispatcher._keymap is us
|
||||
@@ -243,3 +243,102 @@ def test_a_new_lease_starts_without_the_previous_bookmark(lease):
|
||||
def test_defaults_match_the_contract():
|
||||
lease = PointerLease()
|
||||
assert (lease.ttl_s, lease.max_s) == (30.0, 300.0)
|
||||
|
||||
|
||||
# -- keys: the same mirror, and the same ordering rule ----------------------
|
||||
#
|
||||
# PLAN §6.7 proposed a `keyboard` flag on the lease. These tests are the
|
||||
# argument against it: a boolean cannot say to lift `Control_L` and not `a`,
|
||||
# and it cannot say which went down first.
|
||||
|
||||
|
||||
def test_press_and_lift_one_key(lease):
|
||||
lease_id = lease.acquire("alpha")
|
||||
lease.press_key("alpha", "Shift_L")
|
||||
assert lease.keys_pressed() == ["Shift_L"]
|
||||
assert lease.unpress_key("alpha", "Shift_L") == ["Shift_L"]
|
||||
assert lease.keys_pressed() == []
|
||||
assert lease.release("alpha", lease_id, "done").keys_lifted == []
|
||||
|
||||
|
||||
def test_lifting_a_key_that_is_not_down_reports_nothing(lease):
|
||||
lease.acquire("alpha")
|
||||
assert lease.unpress_key("alpha", "Shift_L") == []
|
||||
lease.press_key("alpha", "Shift_L")
|
||||
lease.unpress_key("alpha", "Shift_L")
|
||||
assert lease.unpress_key("alpha", "Shift_L") == []
|
||||
|
||||
|
||||
def test_keys_are_kept_in_press_order(lease):
|
||||
lease_id = lease.acquire("alpha")
|
||||
for name in ("Control_L", "Shift_L", "a"):
|
||||
lease.press_key("alpha", name)
|
||||
assert lease.keys_pressed() == ["Control_L", "Shift_L", "a"]
|
||||
|
||||
assert lease.unpress_key("alpha", "Shift_L") == ["Shift_L"]
|
||||
assert lease.keys_pressed() == ["Control_L", "a"]
|
||||
|
||||
outcome = lease.release("alpha", lease_id, "timeout")
|
||||
assert outcome.keys_lifted == ["Control_L", "a"]
|
||||
assert lease.keys_pressed() == []
|
||||
|
||||
|
||||
def test_pressing_a_key_twice_leaves_one_down(lease):
|
||||
lease.acquire("alpha")
|
||||
lease.press_key("alpha", "a")
|
||||
lease.press_key("alpha", "a")
|
||||
assert lease.keys_pressed() == ["a"]
|
||||
|
||||
|
||||
def test_keys_and_buttons_are_tracked_separately(lease):
|
||||
lease_id = lease.acquire("alpha")
|
||||
lease.press("alpha", "left")
|
||||
lease.press_key("alpha", "Shift_L")
|
||||
assert (lease.pressed(), lease.keys_pressed()) == (["left"], ["Shift_L"])
|
||||
|
||||
outcome = lease.release("alpha", lease_id, "done")
|
||||
assert (outcome.buttons_lifted, outcome.keys_lifted) == (["left"], ["Shift_L"])
|
||||
|
||||
|
||||
def test_a_non_holder_cannot_press_a_key(lease):
|
||||
lease.acquire("alpha")
|
||||
with pytest.raises(LeaseInvalid):
|
||||
lease.press_key("beta", "a")
|
||||
with pytest.raises(LeaseInvalid):
|
||||
lease.unpress_key("beta", "a")
|
||||
|
||||
|
||||
def test_expire_still_returns_no_key_list_so_the_broker_must_read_first(lease, clock):
|
||||
"""CONTRACT-sessions.md §3.3, unchanged by the keyboard.
|
||||
|
||||
`expire()` is still `LeaseInfo` and carries neither buttons nor keys. The
|
||||
ordering it forces -- read, *then* expire -- is the only thing stopping a
|
||||
key from being forgotten before the driver has been told to lift it, and
|
||||
widening the return would make that ordering optional.
|
||||
"""
|
||||
|
||||
lease.acquire("alpha")
|
||||
lease.press_key("alpha", "Shift_L")
|
||||
clock.advance(31.0)
|
||||
|
||||
# The broker's order, and it is not interchangeable.
|
||||
held = lease.keys_pressed()
|
||||
info = lease.expire()
|
||||
|
||||
assert held == ["Shift_L"]
|
||||
assert info is not None
|
||||
assert not hasattr(info, "keys_lifted")
|
||||
assert not hasattr(info, "buttons_lifted")
|
||||
assert lease.keys_pressed() == []
|
||||
|
||||
|
||||
def test_expiry_does_not_leak_keys_to_the_next_holder(lease, clock):
|
||||
"""A held Shift must not become the next session's Shift."""
|
||||
|
||||
lease.acquire("alpha")
|
||||
lease.press_key("alpha", "Shift_L")
|
||||
clock.advance(31.0)
|
||||
assert lease.expire() is not None
|
||||
|
||||
lease.acquire("beta")
|
||||
assert lease.keys_pressed() == []
|
||||
+555
-17
@@ -13,17 +13,34 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from hhstream_pointer import buttons
|
||||
from hhstream_pointer.ops import Dispatcher
|
||||
from hhstream_pointer import buttons, keymap as keymaps
|
||||
from hhstream_pointer.ops import KIND_INVALID, KIND_REFUSED, Dispatcher
|
||||
|
||||
LEFT = buttons.CODES["left"]
|
||||
RIGHT = buttons.CODES["right"]
|
||||
DOWN = buttons.STATES["down"]
|
||||
UP = buttons.STATES["up"]
|
||||
|
||||
#: evdev codes, from ``linux/input-event-codes.h``. Asserted as the integers
|
||||
#: the wire carries, never as XKB codes: ``a`` is 30 there and 38 in xkbcommon's
|
||||
#: tables, and only one of the two ever leaves this process.
|
||||
KEY_A = 30
|
||||
KEY_B = 48
|
||||
KEY_ENTER = 28
|
||||
KEY_LEFTSHIFT = 42
|
||||
KEY_LEFTCTRL = 29
|
||||
|
||||
|
||||
class RecordingSink:
|
||||
"""Every call, in order, as a tuple. Nothing else."""
|
||||
"""Every call, in order, as a tuple. Nothing else.
|
||||
|
||||
``has_keyboard`` answers True by default because most tests want one. The
|
||||
keyboard calls carry **no output**: a virtual keyboard is seat-global, and
|
||||
a sink that tagged them with one would be hiding the fact that a key after
|
||||
a warp to another output still goes to whatever has focus.
|
||||
"""
|
||||
|
||||
keyboard = True
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple] = []
|
||||
@@ -40,6 +57,31 @@ class RecordingSink:
|
||||
def frame(self, output):
|
||||
self.calls.append(("frame", output))
|
||||
|
||||
def has_keyboard(self):
|
||||
return self.keyboard
|
||||
|
||||
def key(self, code, state):
|
||||
self.calls.append(("key", code, state))
|
||||
|
||||
def modifiers(self, depressed, latched, locked, group):
|
||||
self.calls.append(("modifiers", depressed, latched, locked, group))
|
||||
|
||||
|
||||
class KeyboardlessSink(RecordingSink):
|
||||
"""A compositor with no ``zwp_virtual_keyboard_manager_v1``.
|
||||
|
||||
Not a failing sink: the methods are simply never meant to be reached, and
|
||||
a call that got through would be the bug.
|
||||
"""
|
||||
|
||||
keyboard = False
|
||||
|
||||
def key(self, code, state):
|
||||
raise AssertionError("no virtual keyboard exists; key must not be sent")
|
||||
|
||||
def modifiers(self, depressed, latched, locked, group):
|
||||
raise AssertionError("no virtual keyboard exists; modifiers must not be sent")
|
||||
|
||||
|
||||
class FailingSink(RecordingSink):
|
||||
"""A sink whose motion raises, standing in for an output that vanished."""
|
||||
@@ -56,9 +98,21 @@ def sink() -> RecordingSink:
|
||||
return RecordingSink()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def us() -> keymaps.Keymap:
|
||||
"""A real ``us`` keymap.
|
||||
|
||||
Real, not a fake, for the reason ``test_keymap.py`` gives at length: the
|
||||
mask for ``A`` and the refusal of ``é`` are properties of the layout, and a
|
||||
fake that agreed with the dispatcher would prove only that they agree.
|
||||
"""
|
||||
|
||||
return keymaps.build(layout="us")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver(sink) -> Dispatcher:
|
||||
return Dispatcher(sink)
|
||||
def driver(sink, us) -> Dispatcher:
|
||||
return Dispatcher(sink, us)
|
||||
|
||||
|
||||
def warp(driver, output="hh-alpha", x=0.5, y=0.5):
|
||||
@@ -90,7 +144,7 @@ def test_a_click_is_warp_button_frame(driver, sink):
|
||||
("button", "hh-alpha", LEFT, UP),
|
||||
("frame", "hh-alpha"),
|
||||
]
|
||||
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": []}
|
||||
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": [], "keys": []}
|
||||
|
||||
|
||||
def test_the_boundary_coordinates_are_accepted(driver, sink):
|
||||
@@ -160,7 +214,11 @@ def test_pressed_reports_what_is_down_oldest_first(driver):
|
||||
warp(driver)
|
||||
driver.handle({"op": "button", "button": "right", "state": "down"})
|
||||
driver.handle({"op": "button", "button": "left", "state": "down"})
|
||||
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": ["right", "left"]}
|
||||
assert driver.handle({"op": "pressed"}) == {
|
||||
"ok": True,
|
||||
"buttons": ["right", "left"],
|
||||
"keys": [],
|
||||
}
|
||||
|
||||
|
||||
def test_release_all_lifts_everything_and_frames_once(driver, sink):
|
||||
@@ -169,17 +227,28 @@ def test_release_all_lifts_everything_and_frames_once(driver, sink):
|
||||
driver.handle({"op": "button", "button": "right", "state": "down"})
|
||||
sink.calls.clear()
|
||||
|
||||
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": ["left", "right"]}
|
||||
assert driver.handle({"op": "release_all"}) == {
|
||||
"ok": True,
|
||||
"lifted": ["left", "right"],
|
||||
"lifted_keys": [],
|
||||
}
|
||||
assert sink.calls == [
|
||||
("button", "hh-alpha", LEFT, UP),
|
||||
("button", "hh-alpha", RIGHT, UP),
|
||||
("frame", "hh-alpha"),
|
||||
]
|
||||
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": []}
|
||||
assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": [], "keys": []}
|
||||
|
||||
|
||||
def test_release_all_on_a_quiet_driver_lifts_nothing(driver, sink):
|
||||
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": []}
|
||||
assert driver.handle({"op": "release_all"}) == {
|
||||
"ok": True,
|
||||
"lifted": [],
|
||||
"lifted_keys": [],
|
||||
}
|
||||
# Including no zeroed `modifiers`: a mask nothing ever set is not ours to
|
||||
# clear, and on a sink with no keyboard at all sending one would raise and
|
||||
# abandon the button lifting above.
|
||||
assert sink.calls == []
|
||||
|
||||
|
||||
@@ -196,7 +265,11 @@ def test_release_all_lifts_through_the_pointer_the_press_went_to(driver, sink):
|
||||
driver.handle({"op": "button", "button": "right", "state": "down"})
|
||||
sink.calls.clear()
|
||||
|
||||
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": ["left", "right"]}
|
||||
assert driver.handle({"op": "release_all"}) == {
|
||||
"ok": True,
|
||||
"lifted": ["left", "right"],
|
||||
"lifted_keys": [],
|
||||
}
|
||||
assert sink.calls == [
|
||||
("button", "hh-alpha", LEFT, UP),
|
||||
("button", "hh-beta", RIGHT, UP),
|
||||
@@ -209,7 +282,11 @@ def test_a_lifted_button_is_forgotten(driver):
|
||||
warp(driver)
|
||||
driver.handle({"op": "button", "button": "left", "state": "down"})
|
||||
driver.handle({"op": "button", "button": "left", "state": "up"})
|
||||
assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": []}
|
||||
assert driver.handle({"op": "release_all"}) == {
|
||||
"ok": True,
|
||||
"lifted": [],
|
||||
"lifted_keys": [],
|
||||
}
|
||||
|
||||
|
||||
def test_every_known_button_name_round_trips(driver, sink):
|
||||
@@ -227,6 +304,10 @@ def test_button_before_any_warp_is_refused(driver, sink):
|
||||
assert driver.handle({"op": "button", "button": "left", "state": "down"}) == {
|
||||
"ok": False,
|
||||
"error": "no output is aimed; warp before button or frame",
|
||||
# `refused` and not `invalid_argument`: the request was well formed,
|
||||
# what is missing is a warp, and the broker reports that as exit 10
|
||||
# exactly as it already does for an unknown button.
|
||||
"kind": "refused",
|
||||
}
|
||||
assert sink.calls == []
|
||||
|
||||
@@ -277,8 +358,8 @@ def test_a_failed_warp_does_not_change_the_aim():
|
||||
({"op": "axis", "value": -1e9}, "wheel-click limit"),
|
||||
],
|
||||
)
|
||||
def test_malformed_requests_are_answered_not_fatal(sink, request_, fragment):
|
||||
driver = Dispatcher(sink)
|
||||
def test_malformed_requests_are_answered_not_fatal(sink, us, request_, fragment):
|
||||
driver = Dispatcher(sink, us)
|
||||
# Aim first, so a refusal is about the field under test rather than the aim.
|
||||
warp(driver)
|
||||
sink.calls.clear()
|
||||
@@ -300,9 +381,11 @@ def test_the_contracts_ops_are_exactly_what_is_implemented() -> None:
|
||||
|
||||
An op that exists here and nowhere in the contract -- or the reverse --
|
||||
fails this test rather than surprising whoever reads the contract next.
|
||||
``axis`` is the one addition since the freeze, made deliberately so that a
|
||||
session can scroll; the set is edited by hand, which is the reminder to
|
||||
write it down.
|
||||
``axis`` was the first addition since the freeze, so a session could
|
||||
scroll; ``key`` and ``type`` are the second, and there is deliberately no
|
||||
keyboard ``frame`` or ``release_all_keys`` beside them -- the protocol has
|
||||
no frame, and expiry has exactly one call site. The set is edited by hand,
|
||||
which is the reminder to write it down.
|
||||
"""
|
||||
|
||||
assert set(Dispatcher._ops) == {
|
||||
@@ -310,6 +393,461 @@ def test_the_contracts_ops_are_exactly_what_is_implemented() -> None:
|
||||
"button",
|
||||
"axis",
|
||||
"frame",
|
||||
"key",
|
||||
"type",
|
||||
"pressed",
|
||||
"release_all",
|
||||
}
|
||||
|
||||
|
||||
# -- key: one keysym at a time ----------------------------------------------
|
||||
#
|
||||
# Names on this socket, evdev codes on the Wayland request -- the same division
|
||||
# `buttons.py` draws, and the reason `pressed` answers "Control_L" rather than
|
||||
# 29. These tests assert both halves: the response names, the sink codes.
|
||||
|
||||
|
||||
def test_key_down_sends_the_code_and_lists_the_name(driver, sink):
|
||||
assert driver.handle({"op": "key", "key": "Return", "state": "down"}) == {
|
||||
"ok": True,
|
||||
"keys": ["Return"],
|
||||
"lifted": [],
|
||||
}
|
||||
assert sink.calls == [("key", KEY_ENTER, DOWN)]
|
||||
assert driver.handle({"op": "pressed"})["keys"] == ["Return"]
|
||||
|
||||
|
||||
def test_key_needs_no_warp(sink, us):
|
||||
"""A keyboard has no output, so `type` must not demand an aim.
|
||||
|
||||
Deliberately the one test in this file that never warps: a virtual keyboard
|
||||
is seat-global, so requiring a warp first would refuse a caller who only
|
||||
ever wanted to type -- and every other test here warps out of habit, which
|
||||
is exactly how that bug would survive.
|
||||
"""
|
||||
|
||||
driver = Dispatcher(sink, us)
|
||||
assert driver.handle({"op": "type", "text": "Hi"})["ok"] is True
|
||||
assert driver.handle({"op": "key", "key": "a", "state": "down"})["ok"] is True
|
||||
assert ("key", KEY_A, DOWN) in sink.calls
|
||||
|
||||
|
||||
def test_a_key_is_not_tagged_with_an_output_even_after_a_warp(driver, sink):
|
||||
warp(driver, output="hh-beta")
|
||||
sink.calls.clear()
|
||||
driver.handle({"op": "key", "key": "a", "state": "down"})
|
||||
# Two items, not three: no output travels with a key. A sink that accepted
|
||||
# one would let a future change route keys per output, which the protocol
|
||||
# cannot do.
|
||||
assert sink.calls == [("key", KEY_A, DOWN)]
|
||||
|
||||
|
||||
def test_key_up_forgets_the_key(driver, sink):
|
||||
driver.handle({"op": "key", "key": "a", "state": "down"})
|
||||
assert driver.handle({"op": "key", "key": "a", "state": "up"}) == {
|
||||
"ok": True,
|
||||
"keys": [],
|
||||
"lifted": ["a"],
|
||||
}
|
||||
assert sink.calls == [("key", KEY_A, DOWN), ("key", KEY_A, UP)]
|
||||
|
||||
|
||||
def test_up_of_a_key_that_was_never_down_lifts_nothing_and_emits_nothing(driver, sink):
|
||||
"""Same rule as `unpress` for a button that was never pressed.
|
||||
|
||||
Reported rather than invented, and silent on the wire: a key-up the
|
||||
compositor has no matching key-down for puts its own `m_pressed` out of
|
||||
step with ours, and on this build that makes the *next* press of the code
|
||||
a no-op.
|
||||
"""
|
||||
|
||||
assert driver.handle({"op": "key", "key": "a", "state": "up"}) == {
|
||||
"ok": True,
|
||||
"keys": [],
|
||||
"lifted": [],
|
||||
}
|
||||
assert sink.calls == []
|
||||
|
||||
|
||||
def test_keys_are_reported_oldest_first(driver):
|
||||
for name in ("Control_L", "Shift_L", "a"):
|
||||
driver.handle({"op": "key", "key": name, "state": "down"})
|
||||
assert driver.handle({"op": "pressed"})["keys"] == ["Control_L", "Shift_L", "a"]
|
||||
|
||||
|
||||
# -- the modifier half, which a key-up does not undo ------------------------
|
||||
|
||||
|
||||
def test_a_modifier_down_sends_the_key_and_the_mask(driver, sink, us):
|
||||
driver.handle({"op": "key", "key": "Shift_L", "state": "down"})
|
||||
assert sink.calls == [
|
||||
("key", KEY_LEFTSHIFT, DOWN),
|
||||
("modifiers", us.modifier_mask("Shift_L"), 0, 0, 0),
|
||||
]
|
||||
|
||||
|
||||
def test_a_modifier_up_restores_the_mask_of_whatever_is_still_held(driver, sink, us):
|
||||
driver.handle({"op": "key", "key": "Shift_L", "state": "down"})
|
||||
driver.handle({"op": "key", "key": "Control_L", "state": "down"})
|
||||
sink.calls.clear()
|
||||
|
||||
driver.handle({"op": "key", "key": "Shift_L", "state": "up"})
|
||||
|
||||
# Not zero: Control is still down, so the mask drops to Control's bit
|
||||
# alone. A key-up changes no modifier state on this compositor, so the
|
||||
# mask is only ever what we last said it was.
|
||||
assert sink.calls == [
|
||||
("key", KEY_LEFTSHIFT, UP),
|
||||
("modifiers", us.modifier_mask("Control_L"), 0, 0, 0),
|
||||
]
|
||||
|
||||
|
||||
def test_an_ordinary_key_down_sends_no_mask(driver, sink):
|
||||
driver.handle({"op": "key", "key": "a", "state": "down"})
|
||||
assert sink.calls == [("key", KEY_A, DOWN)]
|
||||
|
||||
|
||||
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)]
|
||||
@@ -78,7 +78,7 @@ class _Client:
|
||||
|
||||
def test_one_request_gets_one_response(connection):
|
||||
client, _ = connection
|
||||
assert client.call({"op": "pressed"}) == {"ok": True, "buttons": []}
|
||||
assert client.call({"op": "pressed"}) == {"ok": True, "buttons": [], "keys": []}
|
||||
|
||||
|
||||
def test_many_requests_share_one_connection(connection):
|
||||
@@ -86,8 +86,16 @@ def test_many_requests_share_one_connection(connection):
|
||||
assert client.call({"op": "warp", "output": "hh-a", "x": 0.5, "y": 0.5}) == {"ok": True}
|
||||
assert client.call({"op": "button", "button": "left", "state": "down"}) == {"ok": True}
|
||||
assert client.call({"op": "frame"}) == {"ok": True}
|
||||
assert client.call({"op": "pressed"}) == {"ok": True, "buttons": ["left"]}
|
||||
assert client.call({"op": "release_all"}) == {"ok": True, "lifted": ["left"]}
|
||||
assert client.call({"op": "pressed"}) == {
|
||||
"ok": True,
|
||||
"buttons": ["left"],
|
||||
"keys": [],
|
||||
}
|
||||
assert client.call({"op": "release_all"}) == {
|
||||
"ok": True,
|
||||
"lifted": ["left"],
|
||||
"lifted_keys": [],
|
||||
}
|
||||
assert [c[0] for c in sink.calls] == ["motion", "button", "frame", "button", "frame"]
|
||||
|
||||
|
||||
|
||||
@@ -29,6 +29,9 @@ assert _spec is not None and _spec.origin, "hhstream_pointer is not importable"
|
||||
PACKAGE = Path(_spec.origin).parent
|
||||
PROTOCOL_DIR = PACKAGE / "_protocol/wlr_virtual_pointer_unstable_v1"
|
||||
MANAGER = PROTOCOL_DIR / "zwlr_virtual_pointer_manager_v1.py"
|
||||
KEYBOARD_DIR = PACKAGE / "_protocol/virtual_keyboard_unstable_v1"
|
||||
KEYBOARD_MANAGER = KEYBOARD_DIR / "zwp_virtual_keyboard_manager_v1.py"
|
||||
KEYBOARD = KEYBOARD_DIR / "zwp_virtual_keyboard_v1.py"
|
||||
|
||||
#: Only present in a checkout; a build sandbox gets the test directory alone.
|
||||
PYPROJECT = Path(__file__).resolve().parents[2] / "pyproject.toml"
|
||||
@@ -57,10 +60,81 @@ def test_the_shim_resolves_the_generated_relative_import():
|
||||
|
||||
|
||||
@pytest.mark.skipif(not PYPROJECT.is_file(), reason="not running from a checkout")
|
||||
def test_pyproject_declares_the_entry_point_and_the_dependency():
|
||||
def test_pyproject_declares_the_entry_point_and_the_dependencies():
|
||||
pyproject = PYPROJECT.read_text()
|
||||
assert 'hhstream-pointer = "hhstream_pointer.__main__:main"' in pyproject
|
||||
assert "pywayland" in pyproject
|
||||
# Not optional, and the comment beside it in pyproject.toml says why: an
|
||||
# optional xkbcommon would let test_keymap.py skip, and the
|
||||
# unmappable-character path is the one that must not rot.
|
||||
assert "xkbcommon" in pyproject
|
||||
|
||||
|
||||
# -- the virtual keyboard --------------------------------------------------
|
||||
|
||||
|
||||
def test_the_keyboard_protocol_is_vendored_beside_the_pointer_one():
|
||||
assert (KEYBOARD_DIR / "__init__.py").is_file()
|
||||
assert KEYBOARD_MANAGER.is_file()
|
||||
assert KEYBOARD.is_file()
|
||||
for path in KEYBOARD_DIR.glob("*.py"):
|
||||
assert path.read_text().startswith("# This file has been autogenerated")
|
||||
|
||||
|
||||
def test_the_keyboard_manager_is_version_1_with_the_seat_only_request():
|
||||
source = KEYBOARD_MANAGER.read_text()
|
||||
assert 'name = "zwp_virtual_keyboard_manager_v1"' in source
|
||||
assert " version = 1" in source
|
||||
# Seat and nothing else: a virtual keyboard has no output argument, which
|
||||
# is why `ops.py` must not route a key through `_aimed()`.
|
||||
assert "def create_virtual_keyboard(self, seat: WlSeat)" in source
|
||||
assert "WlOutput" not in source
|
||||
|
||||
|
||||
def test_the_keyboard_carries_keymap_key_and_modifiers():
|
||||
source = KEYBOARD.read_text()
|
||||
assert 'name = "zwp_virtual_keyboard_v1"' in source
|
||||
assert " version = 1" in source
|
||||
assert "def keymap(self, format: int, fd: int, size: int)" in source
|
||||
assert "def key(self, time: int, key: int, state: int)" in source
|
||||
assert (
|
||||
"def modifiers(self, mods_depressed: int, mods_latched: int, "
|
||||
"mods_locked: int, group: int)" in source
|
||||
)
|
||||
# The keymap fd really is an fd on the wire, not a number we invented.
|
||||
assert "ArgumentType.FileDescriptor" in source
|
||||
# No frame, and there is nothing to add one from: `ops.py` says why a key
|
||||
# queued until one would never arrive.
|
||||
assert "def frame(" not in source
|
||||
|
||||
|
||||
def test_the_integers_the_xml_names_but_does_not_define_live_in_our_code():
|
||||
"""The one real cost of using Hyprland's copy of the XML.
|
||||
|
||||
It names `keymap_format` and `key_state` in the request descriptions and
|
||||
defines neither enum, so the scanner emits no `IntEnum` for either. Both
|
||||
are therefore written down with a citation, and this test is what notices
|
||||
if a future regeneration against a *complete* XML makes them redundant --
|
||||
at which point they should be deleted rather than left to drift.
|
||||
"""
|
||||
|
||||
source = KEYBOARD.read_text()
|
||||
assert "keymap_format" in source, "the description still refers to it"
|
||||
assert "class keymap_format" not in source, "...and still does not define it"
|
||||
assert "class key_state" not in source
|
||||
|
||||
from hhstream_pointer import buttons
|
||||
from hhstream_pointer.keymap import XKB_V1
|
||||
|
||||
assert XKB_V1 == 1
|
||||
# `wl_pointer.button_state` and `wl_keyboard.key_state` agree on these two,
|
||||
# which is why there is one table rather than a second that can drift.
|
||||
assert buttons.STATES["up"] == 0
|
||||
assert buttons.STATES["down"] == 1
|
||||
|
||||
|
||||
def test_the_shim_resolves_the_keyboard_relative_import():
|
||||
assert "from ..wayland import WlSeat" in KEYBOARD_MANAGER.read_text()
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
@@ -80,6 +154,39 @@ def test_the_protocol_binds_against_the_installed_pywayland():
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not HAVE_PYWAYLAND,
|
||||
reason="pywayland is not in this environment (it is in the built package)",
|
||||
)
|
||||
def test_the_keyboard_protocol_binds_against_the_installed_pywayland():
|
||||
from hhstream_pointer._protocol.virtual_keyboard_unstable_v1 import (
|
||||
ZwpVirtualKeyboardManagerV1,
|
||||
ZwpVirtualKeyboardV1,
|
||||
)
|
||||
|
||||
assert ZwpVirtualKeyboardManagerV1.name == "zwp_virtual_keyboard_manager_v1"
|
||||
assert ZwpVirtualKeyboardManagerV1.version == 1
|
||||
assert ZwpVirtualKeyboardV1.version == 1
|
||||
for request in ("keymap", "key", "modifiers", "destroy"):
|
||||
assert hasattr(ZwpVirtualKeyboardV1.proxy_class, request)
|
||||
assert hasattr(ZwpVirtualKeyboardManagerV1.proxy_class, "create_virtual_keyboard")
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not HAVE_PYWAYLAND,
|
||||
reason="pywayland is not in this environment (it is in the built package)",
|
||||
)
|
||||
def test_the_backend_binds_the_keyboard_manager_at_version_1_and_survives_its_absence():
|
||||
from hhstream_pointer.backend import KEYBOARD_MANAGER_VERSION, WaylandSink
|
||||
|
||||
assert KEYBOARD_MANAGER_VERSION == 1
|
||||
# A sink that never connected has no keyboard and says so rather than
|
||||
# raising: `ops.release_all` asks this question precisely so that a
|
||||
# compositor with no keyboard global still gets its buttons lifted.
|
||||
sink = WaylandSink(Path("/nonexistent"))
|
||||
assert sink.has_keyboard() is False
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not HAVE_PYWAYLAND,
|
||||
reason="pywayland is not in this environment (it is in the built package)",
|
||||
|
||||
+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] = []
|
||||
|
||||
@@ -450,6 +450,11 @@ def test_a_whole_gesture_runs_through_the_broker_and_the_driver(rig: Rig):
|
||||
assert released["buttons_lifted"] == []
|
||||
|
||||
assert rig.driver.sink.calls == [
|
||||
# Acquire is TWO warps: one warp onto an idle cursor moves the cursor
|
||||
# and not keyboard focus, so acquire nudges to a neighbouring pixel and
|
||||
# then lands on the target. The second one is the bookmark.
|
||||
("warp", output, 0.5, 0.504),
|
||||
("frame", output),
|
||||
("warp", output, 0.5, 0.5),
|
||||
("frame", output),
|
||||
("warp", output, 0.25, 0.75),
|
||||
@@ -512,14 +517,42 @@ def test_a_button_left_down_is_lifted_when_the_lease_is_released(rig: Rig):
|
||||
|
||||
|
||||
def test_killing_a_session_that_holds_the_cursor_gives_it_back(rig: Rig):
|
||||
"""Through `kill`, with a button AND a key down.
|
||||
|
||||
The key half is here rather than in a unit test on purpose. The unit test
|
||||
calls `_drop_lease_for` directly, so it proves that helper lifts keys and
|
||||
says nothing about whether `kill` still calls it -- removing the call would
|
||||
leave that test green. This goes through the verb, and it asserts on the
|
||||
SINK rather than on `pointer.state`: the lease forgetting a key is not the
|
||||
same as the compositor being told it came up, and only the second one
|
||||
matters to the application.
|
||||
"""
|
||||
|
||||
first = start(rig.daemon, "sleeper")
|
||||
second = start(rig.daemon, "sleeper")
|
||||
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
|
||||
rig.daemon.call("pointer.button", id=first, lease_id=lease, button="right", state="down")
|
||||
held = rig.daemon.call(
|
||||
"keyboard.key", id=first, lease_id=lease, key="Shift_L", state="down"
|
||||
)
|
||||
assert held["keys"] == ["Shift_L"], held
|
||||
rig.driver.sink.calls.clear()
|
||||
|
||||
rig.daemon.call("kill", id=first, grace_s=0)
|
||||
|
||||
# KEY_LEFTSHIFT, and `state=0`. Shift is the key to use because `type`
|
||||
# never emits code 42, so a release of it cannot be a leftover from
|
||||
# anything else this rig did.
|
||||
assert ("key", 42, 0) in rig.driver.sink.calls, (
|
||||
f"kill did not lift the held key: {rig.driver.sink.calls}. On this "
|
||||
"compositor a code left in the seat's m_pressed makes the NEXT press "
|
||||
"of it a no-op, so the key is dead rather than merely stuck."
|
||||
)
|
||||
# And the mask with it: a virtual key-up clears no modifier state, so
|
||||
# without this the next holder inherits Shift.
|
||||
assert ("modifiers", 0, 0, 0, 0) in rig.driver.sink.calls, rig.driver.sink.calls
|
||||
assert rig.driver.dispatcher._pressed == {}
|
||||
assert rig.driver.dispatcher._keys == {}
|
||||
assert rig.daemon.call("pointer.state")["holder"] is None
|
||||
assert rig.daemon.call("pointer.acquire", id=second)["ok"]
|
||||
|
||||
@@ -556,6 +589,81 @@ def test_a_retried_click_with_the_same_request_id_clicks_once(rig: Rig):
|
||||
assert len(rig.driver.sink.of("button")) == 2, "one press and one release, not two"
|
||||
|
||||
|
||||
def test_a_retried_type_with_the_same_request_id_types_once(rig: Rig):
|
||||
"""A retried `type` is the keyboard's version of a second click.
|
||||
|
||||
Asserted on the SINK and not on the `deduplicated` flag, because the flag
|
||||
alone is the false pass the verification doc names: a handler that typed
|
||||
the string and *then* set the flag would satisfy it. The thing that must
|
||||
not happen twice is the key events, so those are what is counted.
|
||||
|
||||
The cache is not keyboard-specific -- `_dispatch` looks the `request_id` up
|
||||
before the handler and remembers it after, keyed on the id alone -- so what
|
||||
this locks is that `keyboard.type` is in the mutating set and therefore
|
||||
reaches that path at all.
|
||||
"""
|
||||
|
||||
session_id = start(rig.daemon, "sleeper")
|
||||
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
|
||||
rig.driver.sink.calls.clear()
|
||||
|
||||
first = rig.daemon.call(
|
||||
"keyboard.type", id=session_id, lease_id=lease, text="ab", request_id="retry-me"
|
||||
)
|
||||
second = rig.daemon.call(
|
||||
"keyboard.type", id=session_id, lease_id=lease, text="ab", request_id="retry-me"
|
||||
)
|
||||
|
||||
assert first["ok"] and second["ok"]
|
||||
assert second.get("deduplicated") is True
|
||||
assert first["chars"] == 2 and second["chars"] == 2
|
||||
# Two characters, a down and an up each: four key events for one `type`,
|
||||
# and the replay must not add a fifth.
|
||||
assert len(rig.driver.sink.of("key")) == 4, (
|
||||
f"a replayed type sent {rig.driver.sink.of('key')}; the recorded answer "
|
||||
"must be returned without typing again"
|
||||
)
|
||||
|
||||
|
||||
def test_a_retried_unmappable_type_stays_refused_and_types_nothing(rig: Rig):
|
||||
"""The recorded answer includes a recorded refusal.
|
||||
|
||||
An agent that retries a `type` which was refused must see the refusal
|
||||
again, not a second attempt -- and the sink must still be untouched after
|
||||
both calls, because validation happens before the first event either time.
|
||||
"""
|
||||
|
||||
session_id = start(rig.daemon, "sleeper")
|
||||
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
|
||||
rig.driver.sink.calls.clear()
|
||||
|
||||
first = rig.daemon.call(
|
||||
"keyboard.type",
|
||||
id=session_id,
|
||||
lease_id=lease,
|
||||
text="caf\u00e9",
|
||||
request_id="refuse-me",
|
||||
)
|
||||
second = rig.daemon.call(
|
||||
"keyboard.type",
|
||||
id=session_id,
|
||||
lease_id=lease,
|
||||
text="caf\u00e9",
|
||||
request_id="refuse-me",
|
||||
)
|
||||
|
||||
assert first["ok"] is False and second["ok"] is False
|
||||
assert first["error"] == "invalid_argument", first
|
||||
assert second["error"] == "invalid_argument", second
|
||||
assert second.get("deduplicated") is True, (
|
||||
"a recorded failure must be replayed as the failure it was"
|
||||
)
|
||||
assert rig.driver.sink.of("key") == [], (
|
||||
f"an unmappable string typed something: {rig.driver.sink.calls}. There is "
|
||||
"no partial type, on the first call or the replay."
|
||||
)
|
||||
|
||||
|
||||
def test_a_restored_bookmark_survives_a_daemon_restart(short_tmpdir: Path):
|
||||
"""That is what putting it in the record, and not only in the lease, is for."""
|
||||
|
||||
@@ -572,7 +680,12 @@ def test_a_restored_bookmark_survives_a_daemon_restart(short_tmpdir: Path):
|
||||
acquired = rig.daemon.call("pointer.acquire", id=session_id)
|
||||
|
||||
assert (acquired["bookmark"]["x"], acquired["bookmark"]["y"]) == (0.8, 0.2)
|
||||
assert rig.driver.sink.of("warp") == [("warp", f"hh-{session_id}", 0.8, 0.2)]
|
||||
# The nudge, then the restored position: the bookmark has to be the
|
||||
# *second* warp, or every restore would be a few pixels off.
|
||||
assert rig.driver.sink.of("warp") == [
|
||||
("warp", f"hh-{session_id}", 0.8, 0.204),
|
||||
("warp", f"hh-{session_id}", 0.8, 0.2),
|
||||
]
|
||||
finally:
|
||||
_kill_everything(rig.daemon)
|
||||
rig.stop()
|
||||
|
||||
@@ -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