Stage 1 review fixes, and Stage 2: the broker, the CLI and the module

The Stage 1 review (docs/reviews/2026-10-04-stage1-review.md, verdict
yes-with-fixes) found a real bug, and it was the kind Stage 2 would have
cemented. All five findings:

(1) HIGH, and reproduced before fixing: `key` resolved the action and
    then used only its `code`. So `keyboard key A` sent a bare code 30
    and the window received `a`; on `de`, `at` lost its level-three mask
    and typed `q`. `type` was the only path that used the mask, which is
    why every `type` test stayed green. `key` now sends
    modifiers(baseline | mask) before the down and restores the baseline
    on the up -- the one-character `type` sequence -- and `Shift_L`
    keeps its key-then-mask order, which is the other path on purpose.

    The same hole aliased two names onto one keycode: `down A` then
    `down a` recorded both and pressed 30 twice, Hyprland dropped the
    second, and the held set lied until the lease ended. A second name
    for a code already down is now refused.

(2) HIGH: the shutdown comment claimed hyprland-conf.nix sets
    input:virtualkeyboard:release_pressed_on_close. It did not. The line
    is there now, with the note that it releases keys and still never
    clears a mask -- which is why release_all zeroes the mask on every
    path we control rather than relying on it.

(3) MEDIUM: nothing would have noticed the keymap upload stopping. A
    `main` that connected and listened without uploading passed every
    test in the tree. Now asserted on the real sink: uploaded once,
    before `listen` (one shared ordering log across both stand-ins), the
    payload NUL-terminated with `size == len(utf8) + 1` read back
    through the fd, format 1, one terminator not two, and modifiers(0)
    straight after.

(4) LOW: `key` up now forgets the name only after a successful send,
    like `button` -- otherwise a raise between the two leaves us
    believing a key is up that the compositor still has down, and
    release_all will not try again.

(5) LOW: `\r` no longer aliases to Return (CRLF would have become two
    newlines silently), and an empty layout is refused -- xkbcommon
    compiles "" as the same keymap as `us`, so `--xkb-layout ''` looked
    configured and typed `us`.

Several of the review's named false passes are closed too: Control's
mask is compared against mod_get_index("Control") rather than merely
"not Shift's"; the keymap text assertion names pc_us_inet/pc_de_inet
instead of substring-matching "us"; the capital-under-Control case
asserts the whole sequence; the exit-code mirror is compared against
hhstreamd.protocol; and the module's defaults are read out of
nix/module.nix rather than asserted against themselves.

Stage 2 proper:

  * broker verbs keyboard.key / keyboard.type, both in the mutation set,
    both through _refresh (so they refresh the lease and, like every
    pointer verb, do NOT count as activity)
  * the driver's `kind` token mapped: a bad keysym or character is
    invalid_argument (exit 2), a missing keyboard global stays
    driver_refused (exit 10). The 4096-scalar cap and the shape checks
    are broker-side, because only a broker-side invalid_argument is 2
  * keys[] on pointer.state, keys_lifted[] on pointer.release and on
    pointer_lease_timeout, one release_all for both halves
  * CLI `session keyboard type|key|down|up`, reusing the pointer lease
    and its cache; `type` takes one raw argument and interprets nothing;
    the audit records a character count and never the text
  * sessions.keyboard.{layout,model,variant,options} on the unit's argv,
    layout defaulting to "us" with a type that refuses a comma. NO
    [keyboard] TOML table: hhstreamd reads that file and the driver is a
    different unit, so it would be a setting with no effect
  * CONTRACT-sessions.md bumped to v3; README.dev.md item 3 and
    vm-pointer.nix's header corrected (both still said the conf ships
    follow_mouse = 0 and that the keyboard work would choose)

And the operator decision that acquire grabs both devices: it now sends
two warps a real pixel apart, because one warp onto an idle cursor moves
the cursor and not keyboard focus. follow_mouse_threshold = 0 is set
explicitly in hyprland-conf.nix since the second warp depends on it,
`dispatch focuswindow` is the fallback when the nudge cannot be sent,
and the reply and audit carry which mechanism ran. The acquire test
asserts the pair and that they floor to different pixels -- a test that
only saw wl_pointer.enter would pass while the first keystroke went to
the wrong window.

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GhNPM6rGcuzxocM1nATnuM
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-10-04 04:11:24 +00:00
1 parent b1f2744cf0
commit e6f4c3bb3f
24 files changed
+2474 -105

No files matched your search

+96 -19
View File
@@ -232,6 +232,10 @@ tests/
fake_capture.py writes one fixed PNG to stdout: hhs-fake-capture
assert_stream.py independent contract reader/asserter: hhs-assert-stream
hyprland_diagnostics.sh the failure dump: hhs-hyprland-diagnostics
keyboard_probe.py THROWAWAY: measures the compositor's keyboard behaviour
against the live socket. See README-keyboard-probe.md
and the transcript beside it; delete both once
checks/vm-keyboard.nix asserts the same properties.
unit/ ipc/ containers/ pointer/ sessions/ the pytest suite
```
@@ -259,6 +263,72 @@ Adding a unit test: drop a `test_*.py` under `tests/`. Nothing needs
registering, but the basename must be unique across the tree. Adding a check:
one file in `checks/`, one line in `checks/default.nix`.
## Typing into a session: the keyboard layout
Keys reach whichever surface the compositor's one seat has focused. A virtual
keyboard is seat-global and has no output argument, so unlike the pointer there
is nothing to aim — what aims it is the pointer, and `pointer acquire` takes
both (see item 3 under the known gaps for why that is two warps and not one).
```bash
hhstream session pointer acquire <id> # also authorises typing
hhstream session keyboard type <id> 'hello world' # one argument, raw UTF-8
hhstream session keyboard key <id> Return # a tap: down then up
hhstream session keyboard down <id> Control_L # a chord, held
hhstream session keyboard type <id> c # ...is Ctrl+C
hhstream session keyboard up <id> Control_L
hhstream session pointer release <id> # lifts buttons AND keys
```
`hhstream session pointer state` reports held keys beside held buttons.
### The layout is an operator setting
**The driver compiles one XKB keymap at start-up and uploads it once. That
keymap is the only thing that decides what an injected key means.** Every verb
names an XKB *keysym* — `a`, `A`, `Return`, `BackSpace`, `Left`, `Control_L` —
and the driver resolves that name against the keymap to get the evdev code and
the modifier mask the compositor is sent.
| Option | Default | Notes |
| --- | --- | --- |
| `services.hyprland-headless-stream.sessions.keyboard.layout` | `"us"` | One group only: the option's type refuses `us,ru`, and so does the driver |
| `…sessions.keyboard.model` | `"pc105"` | |
| `…sessions.keyboard.variant` | `""` | A variant whose characters are *dead keys* (`us(intl)`) cannot be typed by v1 |
| `…sessions.keyboard.options` | `""` | Passed to `xkb_keymap_new_from_names`; a value it rejects stops the driver with exit 2 |
```nix
services.hyprland-headless-stream.sessions.keyboard.layout = "de";
```
Three things worth knowing before an agent types anything:
1. **Hyprland's own `input:kb_layout` is not read and has no effect on
injected keys.** It describes the layout for physical keyboards, of which a
headless session has none, and reading it would mean a `hyprctl` reload
could silently change what every agent types. The two can therefore
disagree, and only the option above matters.
2. **A character the layout cannot produce fails the whole string.** There is
no partial type: `keyboard type <id> 'café'` on `us` is exit 2 and emits
nothing, rather than typing `caf` and stopping. The refusal names the scalar
*index*, never the character and never the string, because a typed string is
a password as often as not and these messages are logged. The audit log
records a character count and nothing else.
3. **`keyboard down` of a non-modifier floods the window.** The compositor
sends one key event and publishes a repeat rate; the *application* repeats,
so a held `a` inserts characters until the key-up or the lease TTL (default
30 s). Measured on this build at 25/s after 600 ms. It is not ours to
rate-limit — we do not generate the repeats — so the only safe hold is a
modifier, which is what chords are for.
The layout reaches the driver as `--xkb-layout` on `hhstream-pointer`'s command
line, and **only** there. It is deliberately not a key in the broker's TOML:
that file is read by `hhstreamd`, and the driver is a different unit that never
opens it, so a `[keyboard]` table there would be a setting an operator could
change while every injected key stayed on `us`.
## Known gaps in the interface (as of this branch)
Every item the previous revision of this section listed is closed: the module
@@ -289,13 +359,14 @@ when one closes, so this list stays a description of what is still true.
get a container anyway — so the CLI exits 2 and names the disagreement
instead of lying about what it did.
3. **`nix/hyprland-conf.nix` sets `input:follow_mouse = 0`, and that stops
pointer input reaching anything but the focused window.** The comment
justifying it — "No pointer will ever exist; do not let focus depend on
one" — was true before this build and is false now.
3. **Fixed: `nix/hyprland-conf.nix` sets `input:follow_mouse = 1`.** *(This
item previously said it ships `0`, that pointer input therefore reaches
nothing but the focused window, and that whether to change it was a
decision for the keyboard work. The conf file sets `1`, and the keyboard
work has made that decision; what follows is why, and what is left.)*
Measured by `vm-pointer`, with two sessions and the second holding focus
because its window opened last:
The original measurement, by `vm-pointer`, with two sessions and the second
holding focus because its window opened last:
```
aimed at target-le22h7: it reports [] <- the session the warp named
@@ -303,20 +374,26 @@ when one closes, so this list stays a description of what is still true.
cursor now at {'x': 2048, 'y': 288} <- exactly where it was aimed
```
The compositor moved the cursor to the right pixel, inside the right
window, on the right output, and told no client at all. Every warp and
click in the subtests before that one is delivered perfectly, because there
the aimed-at session is also the focused one — which is why nothing noticed
until a check put two sessions on the screen at once.
With `0`, the compositor moved the cursor to the right pixel, inside the
right window, on the right output, and told no client at all. That defeats
the point of containers and the lease, so the conf sets `1`.
It defeats the point of containers and the lease: an agent could only drive
whichever session the compositor last focused. `vm-pointer` overrides the
single line through the module's `extraConfig` and asserts the property
that fails without it, so the check is green and the defect is still
visible. The fix is one line in `nix/hyprland-conf.nix`; whether it should
be `1` (Hyprland's own default, keyboard focus follows the cursor too) or a
looser setting that leaves keyboard focus alone is a decision for the
keyboard work in PLAN §6.7.
**What is left, and it is a real limitation.** `follow_mouse = 1` moves
keyboard focus too — which is what makes typing possible at all, since a
virtual keyboard is seat-global and has no output to aim. But **one warp
does not move it.** Measured directly against the live compositor
(`tests/README-keyboard-probe.md`): an idle `motion_absolute` onto an
unfocused window delivers `wl_pointer.enter` and no `wl_keyboard.enter`,
because `mouseMoveUnified` zeroes `m_mousePosDelta` when the previous
movement was over 0.5 s ago and keyboard focus is that delta compared
against `input:follow_mouse_threshold`.
So `pointer acquire` sends **two** warps, a real pixel apart, and takes the
keyboard as well as the cursor. The conf now sets
`follow_mouse_threshold = 0` explicitly rather than inheriting the default,
because that is what the second warp depends on; raise it and acquire stops
taking keyboard focus. `dispatch focuswindow` is the fallback if the nudge
cannot be sent, and the acquire reply's `focus` field says which ran.
4. **A container's window rule only binds for an application that reads the
environment.** The broker's only lever on an application's class is
+14 -2
View File
@@ -47,8 +47,20 @@
#
# 2. `input:follow_mouse = 0` SENDS POINTER EVENTS TO THE FOCUSED WINDOW ONLY,
# and when the window under the cursor is not the focused one, to nobody at
# all. `nix/hyprland-conf.nix` ships it, justified by "No pointer will ever
# exist; do not let focus depend on one" -- a belief this build makes false.
# all. `nix/hyprland-conf.nix` USED TO ship it, justified by "No pointer
# will ever exist; do not let focus depend on one" -- a belief this build
# made false. **That is fixed: the conf file now sets `1`**, so the
# `extraConfig` override below is belt and braces rather than the only
# thing making this check pass. The measurement is kept because it is the
# reason the conf changed, and because a revert would make it current again.
#
# What `1` does NOT fix, measured later by `tests/keyboard_probe.py`: one
# warp moves the cursor and not KEYBOARD focus, because Hyprland zeroes
# `m_mousePosDelta` when the previous movement was over 0.5s ago. So
# `pointer acquire` sends two warps a real pixel apart, and the conf sets
# `input:follow_mouse_threshold = 0` explicitly because that is what the
# second one depends on. `checks/vm-keyboard.nix` is where that is asserted;
# this check asserts pointer delivery and says nothing about keys.
#
# MEASURED, against the shipped config, with two sessions and the second
# one holding focus because its window opened last:
+119 -20
View File
@@ -1,7 +1,7 @@
# CONTRACT — sessions build (sessions-v1)
# CONTRACT — sessions build (sessions-v3)
This file is the interface for the **session** work: the broker, containers,
compositor IPC and pointer input. It is the sibling of `docs/CONTRACT.md`, which
compositor IPC and pointer **and keyboard** input. It is the sibling of `docs/CONTRACT.md`, which
freezes the *frame-socket* wire format; that one is untouched by this build.
**Immutable without a version bump.** Every slice codes against this and nothing
@@ -9,10 +9,23 @@ else. If something here is wrong or missing, **stop and report it in your final
message** — the parent edits this file, not you. Do not widen your slice to work
around a gap.
Version: sessions-v2 (2026-10-02). v1 was the freeze the four slices built against;
v2 records the decisions their reports asked for. Every v2 change is either a
clarification or an addition — **no v1 signature changed meaning** — so v1 code
stays valid except where noted. Changes:
Version: sessions-v3 (2026-10-04). v1 was the freeze the four slices built
against; v2 recorded the decisions their reports asked for; v3 adds the
keyboard. Every change in both has been an addition or a clarification — **no
v1 or v2 signature changed meaning** — so earlier code stays valid except where
noted.
v3 changes, all of them keyboard (`docs/plans/2026-10-03-keyboard-input.md` as
amended by `docs/plans/2026-10-04-keyboard-verification.md`):
| § | Change | Why |
| --- | --- | --- |
| §3.3 | `PointerLease` gains `press_key` / `unpress_key` / `keys_pressed`; `LeaseOutcome` gains `keys_lifted`. **`expire()` still returns `LeaseInfo` and nothing else.** | One `wl_seat` means one keyboard focus, so the keyboard shares the pointer's lease. §6.7's "the lease gains a `keyboard` flag" is the wrong shape: a boolean cannot say to lift `Control_L` and not `a`, and order matters for the same reason it does for buttons. |
| §3.4 | Driver ops `key` and `type`; `pressed` gains `keys[]`; `release_all` gains `lifted_keys[]`; the frozen command line gains four `--xkb-*` flags. A rejected request may carry a `kind`. | There is no keyboard `frame` and no `release_all_keys`: the protocol has no frame, and expiry has one call site. The flags are the **only** path a layout has to the uploaded keymap — the broker's TOML is read by `hhstreamd`, and the driver is a different unit that never opens it. |
| §4 | Verbs `keyboard.key` and `keyboard.type`, both in the mutation set; `pointer.state` gains `keys[]`; `pointer.release` gains `keys_lifted[]`. | A retried `type` must not type twice, for the reason a retried click must not click twice. |
| §4 | **`pointer.acquire` takes keyboard focus as well as the cursor**, and is two `warp`s on the driver socket rather than one. | Measured (`tests/README-keyboard-probe.md`): one warp onto an idle cursor delivers `wl_pointer.enter` and no `wl_keyboard.enter`, so a one-warp acquire aims the cursor at the session and leaves the keys with whatever was focused before. |
v2 changes:
| § | Change | Why |
| --- | --- | --- |
@@ -236,13 +249,27 @@ class PointerLease:
def press(self, session_id: str, button: str) -> None: ...
def unpress(self, session_id: str, button: str) -> list[str]: ...
def pressed(self) -> list[str]: ...
# v3: the same three for keysym names. A `keys` dict beside `buttons` on
# the held record, not a `keyboard` boolean: `release_all` has to know
# *which* keys went down and in what order.
def press_key(self, session_id: str, key: str) -> None: ...
def unpress_key(self, session_id: str, key: str) -> list[str]: ...
def keys_pressed(self) -> list[str]: ...
**`expire()` carries no bookmark and no lifted buttons** — it returns the lease
that was released, nothing more. The broker therefore has two duties on expiry:
read `pressed()` *before* calling `expire()` if it wants the lease's view of what
was down, and lift those buttons on the driver (`release_all`), because the lease
cannot lift them itself. The bookmark is not `expire()`'s to keep: the broker
already stores it with the session (§1), which is where it belongs.
**`expire()` carries no bookmark, no lifted buttons and no lifted keys** — it
returns the lease that was released, nothing more. The broker therefore has two
duties on expiry: read `pressed()` **and `keys_pressed()`** *before* calling
`expire()` if it wants the lease's view of what was down, and lift them on the
driver (one `release_all`), because the lease cannot lift anything itself. The
bookmark is not `expire()`'s to keep: the broker already stores it with the
session (§1), which is where it belongs.
v3 deliberately did **not** widen this return. 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 on this compositor a forgotten key is
worse than a forgotten button: `InputManager::onKeyboardKey` drops the *next*
press of a code it still believes is down, so the key is dead rather than
merely stuck.
def window_to_absolute(point: tuple[int, int], window: tuple[int, int, int, int],
monitor: tuple[int, int, int, int]) -> tuple[float, float]:
@@ -258,8 +285,27 @@ blocked driver must not stall the broker.
- Entry point `hhstream-pointer` (add to `pyproject.toml`:
`hhstream-pointer = "hhstream_pointer.__main__:main"`).
- Command line the module will pass, exactly:
`hhstream-pointer --socket /run/hhstream/pointer.sock --compositor-runtime-dir /run/hypr-stream`
- Command line the module will pass, exactly (**amended in v3**: the four
`--xkb-*` flags, whose defaults are the values below):
```
hhstream-pointer --socket /run/hhstream/pointer.sock \
--compositor-runtime-dir /run/hypr-stream \
--xkb-layout us --xkb-model pc105 \
--xkb-variant '' --xkb-options ''
```
These flags are the **only** path a layout has to the uploaded keymap. There
is deliberately no `[keyboard]` table in the broker's TOML: that file is read
by `hhstreamd`, and this is a different unit that never opens it, so such a
table would be a setting an operator could change while every injected key
stayed on `us`.
A layout `xkb_keymap_new_from_names` rejects — and a comma-separated one,
and an empty one — is exit **2**, raised *before* the compositor is
contacted. A keymap the compositor refuses is exit **10**, and the socket is
never listened on: `key` before `keymap` is the protocol error `no_keymap`,
which kills the connection rather than returning anything reportable.
- Uses **pywayland** (packaged as `python3Packages.pywayland`) and the **wlr
virtual pointer XML** from `pkgs.wlr-protocols`, which lives at
`share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml` (the v1
@@ -280,10 +326,39 @@ blocked driver must not stall the broker.
{"op": "button", "button": "left", "state": "down"} -> {"ok": true}
{"op": "axis", "axis": "vertical", "value": 3.0} -> {"ok": true}
{"op": "frame"} -> {"ok": true}
{"op": "pressed"} -> {"ok": true, "buttons": ["left"]}
{"op": "release_all"} -> {"ok": true, "lifted": ["left"]}
{"op": "pressed"} -> {"ok": true, "buttons": ["left"], "keys": ["Control_L"]}
{"op": "release_all"} -> {"ok": true, "lifted": ["left"], "lifted_keys": ["Control_L"]}
{"op": "key", "key": "Return", "state": "down"} -> {"ok": true, "keys": ["Return"], "lifted": []}
{"op": "type", "text": "Hello"} -> {"ok": true, "keys": []}
```
**Amended in v3 — `key` and `type`, for the keyboard.** Names on this socket,
evdev codes only on the Wayland request: the driver owns the keymap, so it is
the only thing that can say which keycode `z` is on the uploaded layout. Four
rules that are not interchangeable:
- **No output and no frame.** A virtual keyboard is seat-global, so `key` and
`type` take no output and must not require a prior `warp`. And
`zwp_virtual_keyboard_v1` has no `frame` request — a key queued until one
would never arrive — so each request is flushed the way `button` already is.
- **`pressed` and `release_all` grow key fields** rather than gaining a
parallel `release_all_keys`. Expiry has one call site, and a second op would
be a second thing to forget in the path that runs when nobody is watching.
`release_all` lifts buttons, then keys in press order, then sends
`modifiers(0, 0, 0, 0)` if a mask was ever set — a virtual key-up clears no
modifier state, so without that a lease that ended under Shift hands the
next holder a keyboard where every letter is a capital.
- **`type` is one request for the whole string.** The driver resolves every
character before emitting anything, so an unmappable one types no prefix.
Capped at 4096 Unicode **scalars** (not bytes) in the driver and in the
broker.
- **A rejection may carry `kind`.** `{"ok": false, "error": "…", "kind":
"invalid_argument"}` is the caller's mistake — a keysym the layout does not
have, an unmappable character, a bad `state`, a string over the cap — and the
broker maps it to exit 2. Any other value, and an older driver's absent
field, stay `driver_refused` (exit 10), which is what the button and axis
paths already do.
**Amended after the freeze — `axis`, for scrolling.** Added to the op set above
and to the broker's verbs as `pointer.scroll`. Positive vertical is *down* and
positive horizontal is *right*: the protocol's direction, not a choice of ours,
@@ -316,8 +391,26 @@ code will be called with):
| `pointer.move` | `id`, `lease_id`, `x`, `y` \| `dx`, `dy` | `bookmark` |
| `pointer.button` | `id`, `lease_id`, `button`, `state` | `buttons[]` |
| `pointer.click` | `id`, `lease_id`, `button?`, `count?` | `bookmark` |
| `pointer.release` | `id`, `lease_id` | `bookmark`, `released_by` |
| `pointer.state` | — | `holder`, `since`, `lease_id` |
| `pointer.release` | `id`, `lease_id` | `bookmark`, `released_by`, `buttons_lifted[]`, `keys_lifted[]` |
| `pointer.state` | — | `holder`, `since`, `lease_id`, `buttons[]`, `keys[]` |
| `keyboard.key` (v3) | `id`, `lease_id`, `key`, `state` | `keys[]` |
| `keyboard.type` (v3) | `id`, `lease_id`, `text` | `chars`, `keys[]` |
**v3, the keyboard.** `keyboard.*` verbs take the **pointer** lease: there is
no `keyboard.acquire` and no second lease id. One `wl_seat` means one keyboard
focus, and the shipped `input:follow_mouse = 1` means another session's warp
retargets the keys, so two leases would let session B move the pointer while
session A believed it was typing into its own window. Both verbs are in the
`request_id` mutation set, for the reason `pointer.click` is: a retried `type`
that typed twice is the one failure an agent cannot undo.
**v3, acquire takes the keyboard too.** `pointer.acquire` sends **two** warps
to the driver — a neighbouring pixel, then the real target — because one warp
onto an idle cursor moves the cursor and not keyboard focus. Measured; see
`tests/README-keyboard-probe.md`. The reply gains `focus`, naming which
mechanism took it (`warp`, `focuswindow`, or `none`). This depends on
`input:follow_mouse_threshold` being 0, which `nix/hyprland-conf.nix` now sets
explicitly rather than inheriting.
### Error codes (extend `ExitCode`, do not renumber)
@@ -325,8 +418,13 @@ code will be called with):
| 6 POLICY | 7 TIMEOUT | 8 BUSY | **9 NO_LEASE (new)** | **10 COMPOSITOR (new)** |
Activity accounting is unchanged and load-bearing: **`touch` is the only mark of
activity**; `list`, `status`, `logs`, `gc`, and every `pointer.*` verb do **not**
reset the idle clock.
activity**; `list`, `status`, `logs`, `gc`, and every `pointer.*` **and
`keyboard.*`** verb do **not** reset the idle clock. A session being typed into
is still a session nobody has said they want kept.
The *lease* clock is a different one, and v3 widens it: every `pointer.*` and
`keyboard.*` gesture verb refreshes the lease's idle deadline, because they all
go through the same gate. `pointer acquire`'s own stderr says so.
---
@@ -346,6 +444,7 @@ reset the idle clock.
| Container workspace band | `1000 + slot`, allocated from the registry's free list |
| Container mode | `1280x720` |
| Units | `hyprland-headless`, `hyprland-headless-stream`, `hhstream-sessions`, `hhstream-pointer` |
| Keyboard layout | **option default** `us` (`sessions.keyboard.layout`), reaching the driver as `--xkb-layout`. One group: a comma is refused. Hyprland's `input:kb_layout` is not read. |
| Binaries | `hhstream`, `hhstreamd`, `hhstream-server`, `hhstream-client`, `hhstream-pointer` |
| Service account | `hermes`, supplementary group `hhstream` |
+178
View File
@@ -0,0 +1,178 @@
# Stage 1 review — the driver learns to type
Reviewed `f931858` only (keymap, vendored `zwp_virtual_keyboard_v1`, ops, backend upload, `__main__` flags, the pointer-side lease mirror, and `tests/pointer/`). Uncommitted edits under `src/hhstreamd/`, `src/hhstream_session/`, `nix/module.nix` and `nix/hyprland-conf.nix` are not this commit and were not reviewed. `b1f2744`, which lands after `f931858` and only edits the plan and the Stage 0 write-up, was not reviewed either.
The suite was not re-run. The resolver and the dispatcher were executed against the installed libxkbcommon 1.13.2 (python-xkbcommon 1.5.1) for `us` and `de`. Line numbers below are `f931858`.
## Verdict
**Yes-with-fixes.** `type` of `A` on `us` is the worked example, and it is not a Shift special case: the same path sends level 3 for `de` `@`. The uploaded text is a real XKB keymap (`xkb_symbols "pc_us_inet(evdev)"`, TEXT_V1), and its NUL-inclusive size for `us`/`pc105` is 35572, the same number Stage 0 logged. The layout is `--xkb-layout` (default `us`), not a hardcoded string. Nothing in this commit treats `pointer acquire`'s one warp as keyboard focus.
Two things are wrong enough that Stage 2 will encode them if it starts from this tree. `key` throws away the mask the resolver just computed, so `keyboard key A` types `a`. And the shutdown comment says `nix/hyprland-conf.nix` sets `input:virtualkeyboard:release_pressed_on_close`, which this commit does not do.
## Findings
1. **High. `key` drops `action.mask`, so any keysym above level 0 is sent as the bare key.** `keymap.py` `resolve_name("A")` returns `(code=30, mask=1)` and `resolve_text("@")` on `de` returns `(code=16, mask=128)`, which is `ISO_Level3_Shift`'s bit, not Shift. `_op_type` uses that mask (`ops.py:315`, mask before the down/up, restored after). `_op_key` does not. On down it sends `action.code` and then, only if `is_modifier(name)`, `modifier_mask` (`ops.py:261-266`). `A` and `at` are not modifiers, so the calls are `key(30, pressed)` and `key(16, pressed)` with no `modifiers` at all. Confirmed by running the dispatcher: `{"op":"key","key":"A"}` produces `[("key", 30, 1)]`; `{"op":"key","key":"at"}` on `de` produces `[("key", 16, 1)]`. The plan's `NAME` list includes `A` (`2026-10-03-keyboard-input.md` CLI block). Stage 2's `keyboard key` / `down` / `up` as a thin wrapper of this op will type the level-0 character. Stage 3's `keyboard type` assertion stays green while that is true, because `type` is the path that was tested (`tests/pointer/test_ops.py:513-527`).
The same hole aliases two names onto one evdev code. `down A` then `down a` records both names and sends `key(30, pressed)` twice. Hyprland drops the second press (`m_pressed` already contains 30). `release_all` then emits two ups of 30 (`ops.py:351-352`); the second is dropped because the code is already up. The seat survives. The held set lied the whole time.
Cheapest fix: in `_op_key`, if `action.mask` is non-zero, send `modifiers(baseline | action.mask)` *before* the down and restore the baseline on the matching up — the one-character `type` sequence — and refuse a second held name whose evdev code is already down, `kind=invalid_argument`. Do not store `action.mask` in `_keys` as the contribution: that field means "what this key adds", and `type` treats a zero contribution as "non-modifier, refuse". `Shift_L` must stay key-then-mask; the tests at `test_ops.py:481-486` lock that order, and it is the other path on purpose.
2. **High. The comment says Hyprland releases keys on destroy. The conf file does not.** `__main__.py:186-193` says SIGKILL is safe because `nix/hyprland-conf.nix` sets `input:virtualkeyboard:release_pressed_on_close`. In `f931858` that file's `input` block is `follow_mouse = 1` and nothing else (`nix/hyprland-conf.nix:81-94`). The verification's change 4 was "required before code" because the default is 0 and `releasePressed` emits key-ups only when the option is true: a `kill -9` leaves the code in the seat's `m_pressed`, and the next driver's down of that code is ignored. The clean path is fine — `_lift_everything` calls `release_all`, and `release_all` does send the ups and, when a mask was touched, `modifiers(0,0,0,0)`. The comment describes the path the option exists for, and the option is not there.
Cheapest fix: one line in `nix/hyprland-conf.nix`, `input:virtualkeyboard:release_pressed_on_close = true`, plus the sentence the verification asked for (the true setting still does not clear a mask, which is why `modifiers(0,…)` stays). Delete the claim from `__main__.py` until the line exists. This is not optional follow-up: it is the difference between a killed driver and a key that stays dead.
3. **Medium. The upload is right, and no test would notice if it stopped being right.** `WaylandSink.upload_keymap` (`backend.py:209-253`) creates one keyboard, writes `text.encode("utf-8") + b"\0"`, passes `format=XKB_V1` (1) and `len(payload)`, `_sync()`s, and only then `os.close`s the fd. python-xkbcommon 1.5.1's `get_as_bytes` defaults to `XKB_KEYMAP_FORMAT_TEXT_V1` and `ffi.string` strips the NUL, so the extra byte is exactly one terminator, not two. For `us`/`pc105` that size is 35572. `__main__.py:155-173` calls it once, after `connect`, and returns exit 10 on `CompositorUnavailable` *before* `listen`. `type` never calls it.
Nothing asserts any of that. `test_the_keymap_object_is_built_once_and_reused_across_types` (`test_keymap.py:279-293`) checks `dispatcher._keymap is us`. The sink has no `keymap` method. The verification named this false pass: a backend that uploads on every `type` stays green. `test_a_usable_layout_gets_as_far_as_the_compositor` (`test_driver_flags.py:128-138`) raises at `connect`, so upload, the NUL, format 1, and "before listen" are never reached. A `main` that connects and listens without uploading passes every test in the tree. `test_the_backend_binds_the_keyboard_manager_at_version_1_and_survives_its_absence` (`test_vendored_protocol.py:179-187`) constructs an unconnected `WaylandSink` and checks the flag is false. A `connect` that `ManagerTooOld`s when the keyboard global is missing stays green.
Cheapest fix: one test with a sink whose `connect` succeeds and whose `upload_keymap` records `(text, caller)`. Assert `main` calls it once, with a payload whose last byte is NUL and whose length is `len(text.encode()) + 1`, and that `serve` is what runs next — inject `listen` so it does not need a socket. A second test calls `upload_keymap` on a fake keyboard object and asserts `keymap(1, fd, size)` sees `size == len(payload)` while `fd` still reads back the bytes. Do not assert only that `keymap.py` returns equal strings.
4. **Low. `key` up forgets the name before the send, unlike `button`.** `_op_key` pops `_keys` and then calls `sink.key` (`ops.py:275-276`). `_op_button` updates `_pressed` only after the send (`ops.py:198-203`). A raise from the up — `KeyboardUnavailable` is caught in `__main__.py:211-214` and the process stays up — leaves `_keys` empty while the compositor still has the code down. `release_all` will not repeat the up. Confirmed with a sink that raises on `state=0`: after a failed `Shift_L` up the held set is `[]` and `_mask_touched` is still true, so the next `release_all` sends `modifiers(0,…)` and no key-up. Not reachable today unless the keyboard object disappears between down and up (`close` is the only thing that clears it, and it runs after the lift). Cheapest fix: pop after a successful send, same order as the button.
5. **Low. Two layouts xkbcommon accepts are not the layout the caller named.** `CONTROL_KEYSYMS` maps `\r` to `Return` (`keymap.py:67`). The plan's C0 rule exempts `\n` and `\t` only; `\r` is a `Return` and not a refusal. And `build(layout="")` does not raise: xkbcommon compiles it as `xkb_symbols "pc_us_inet(evdev)"`, the same keymap as `us`. A hand-run `--xkb-layout ''` looks configured. The comma check (`keymap.py:144-153`) is the right idea and does not cover this. Cheapest fix: drop `\r` from `CONTROL_KEYSYMS`, and reject an empty layout in `build()` next to the comma check.
Not defects, checked because they look like them:
- **Shift is not hardcoded.** `A` on `us` is evdev 30 and mask `1 << mod_get_index("Shift")` (index 0, so 1). `de` `@` is evdev 16 and mask 128, equal to `modifier_mask("ISO_Level3_Shift")`, not equal to Shift. `type "@"` emits `modifiers(128), key(16, down), key(16, up), modifiers(0,…)` and no code 42. Control's contribution is 4 (index 2). The measured modifier set on `us`/`pc105` is exactly `EXPECTED_MODIFIERS`; Meta and Hyper are absent because no key produces them. Locks are `Caps_Lock` and `Num_Lock`, and `type` while either is held emits nothing.
- **Unmappable means no events.** `resolve_text("xéy")` raises `UnknownKey` with `scalar 1 (U+00E9)` and neither the character nor the string. The dispatcher calls `resolve_text` before any sink call (`ops.py:310-311`). `é`, a C0 other than the two (and `\r`) exemptions, a dead keysym, and 4097 scalars are the same shape.
- **The 4096 cap counts scalars.** `len(str)` is what `resolve_text` compares (`keymap.py:335-338`). 4096 copies of `😀` miss the cap and fail on scalar 0; a byte cap would have said "limit".
- **Degraded mode is the reachable one.** A missing manager makes `upload_keymap` return before `create_virtual_keyboard` (`backend.py:221-226`). `has_keyboard()` stays false. `key` / `type` answer `kind: refused` (`ops.py:391-396`). `release_all` sends key-ups only when `_keys` is non-empty and `modifiers(0,…)` only when `_mask_touched` (`ops.py:347-361`). Both stay empty if no keyboard op ever succeeded, so the button half still runs. The test uses a real `us` keymap plus a sink with no keyboard (`test_ops.py:703-723`), which is how the process actually starts: the keymap is compiled before connect (`__main__.py:132-138`) even when the global is absent.
- **No keyboard `frame`, no `_aimed()` on `key` or `type`, no `touch`.** `frame` remains the pointer op. `release_all` still frames pointer outputs and does not add one for keys (`ops.py:343-344`, locked by `test_ops.py:667-683`). There is no `touch` in the driver. This commit does not add broker verbs, so it does not add any to the mutation set either.
- **The driver token exists, on the driver reply only.** A bad keysym, an unmappable scalar, a bad `state`, and a string over the cap are `{"ok": false, "kind": "invalid_argument"}` (`ops.py:112-117`, `159-160`, `413-425`). A missing keyboard is `kind: "refused"`. A bad layout is process exit 2 *before* `WaylandSink` is constructed (`__main__.py:132-141`, `keymap.py:144-153`). Upload failure is exit 10 and does not `listen` (`__main__.py:155-164`). The committed broker does not read `kind`. That is the next section, not a second copy of this one.
- **Focus.** No Stage 1 path warps to deliver `wl_keyboard.enter`, warps twice, or calls `dispatch focuswindow`. `type` with no prior warp emits keys (`test_ops.py:420-432`). `pointer acquire` is still one `_warp`. The Stage 0 misreading was not built on.
## Tests
Dispatcher tests record tuples. They cannot see Wayland `time`, the keymap fd, or `format`. That seam is fine for ops and blind for the upload. Per test, what a pass requires, and where a pass is a lie:
`tests/pointer/test_keymap.py` (real xkbcommon, not a stub):
| Test | Passes only if | False pass |
| --- | --- | --- |
| `test_a_lower_case_letter_…` | `resolve_name("a")` is `(30, 0)` | Asserting the XKB code 38 would be the lie; this one asserts 30 |
| `test_a_capital_is_the_same_code_with_shift_in_the_mask` | code 30 and mask `== 1 << mod_get_index("Shift")`, and the code is not 42 | Hardcoding mask `1` is what this test refuses. It does not run `type` |
| `test_shift_is_a_key_in_its_own_right_…` | `Shift_L` is `(42, 0)` and `modifier_mask` equals that Shift bit | |
| `test_a_named_keysym_resolves_…` | `Return` 28, `Tab` 15, `BackSpace` 14, `Left` 105 | The mask is not checked. All four are level 0 on `us`, so a resolver that always returns mask 0 passes |
| `test_the_two_allowed_control_characters_…` | `\n` and `\t` are `Return` / `Tab`, mask 0 | Does not notice that `\r` is also `Return` |
| `test_an_empty_string_…` | `resolve_text("") == []` | |
| `test_a_character_this_layout_cannot_produce_…` | `UnknownKey`, message contains `scalar 0`, and the character is not in the message | A message that quoted `é` fails this. Logging the string elsewhere would not |
| `test_the_refusal_names_the_index_…` | `"abcé"` says `scalar 3` and not `é` | |
| `test_a_dead_keysym_is_refused_by_name` | `dead_acute` raises and the message contains `dead key` | The prefix check refuses the name even when it is not on the layout. The test does not prove a layout that *has* the key still refuses it; `us` does not have it |
| `test_an_unknown_keysym_name_…` | `NoSuchKeysymAtAll` raises `UnknownKey` | |
| `test_a_comma_separated_layout_…` | `build("us,ru")` raises `KeymapError` and the message contains `group` | Compiling the two-group keymap and *then* raising still passes. The user-visible failure (nothing uploaded) is the same |
| `test_a_layout_xkbcommon_rejects_…` | `zzz-no-such-layout` raises and the name is in the message | xkbcommon does reject it (NULL, not a silent `us`). Empty string is the case this does not cover: it compiles as `us` |
| `test_the_cap_is_exactly_at_the_limit` | 4096 `a`s resolve | |
| `test_one_scalar_over_the_cap_…` | 4097 raises and the message names 4096 | No sink. The dispatcher twin covers "zero calls" |
| `test_the_cap_counts_scalars_and_not_bytes` | 4096 emoji (`len == 4096`, UTF-8 longer) raises `scalar 0` and the message does not contain `limit` | An ASCII-only cap test would not tell a byte cap from a scalar cap. This one does |
| `test_the_modifier_set_is_measured_…` | `modifier_names() == EXPECTED_MODIFIERS` | An empty set fails. It does not fail a set that matches the constant and was then hardcoded — the constant is what `us`/`pc105` measures, which is the point of the constant |
| `test_a_lock_is_not_a_modifier` | locks are exactly `{Caps_Lock, Num_Lock}`, none of them modifiers | |
| `test_control_contributes_a_mask_that_is_not_shifts` | Control's mask is neither 0 nor Shift | **Alt's bit passes.** Nothing asks `mod_get_index("Control")`. The wire tests compare against `modifier_mask(...)`, so a consistently wrong bit stays green. Measured here: index 2, mask 4. The test does not lock that |
| `test_de_swaps_y_and_z_…` | `us` y/z are 21/44, `de` is 44/21 | A table beside the keymap that always returns the `us` codes fails |
| `test_on_de_the_at_sign_…` | `us` `@` has Shift's mask; `de` `@` is neither 0 nor Shift, and equals `modifier_mask("ISO_Level3_Shift")` | The two sides use different xkbcommon calls (level lookup vs a pressed key). Both are 128. A Shift special case for letters only would still pass, which is why the `de` case exists |
| `test_a_character_us_cannot_type_is_ordinary_on_de` | `ü` raises on `us`; on `de` it is `udiaeresis`, mask 0 | |
| `test_the_keymap_text_is_an_xkb_keymap_naming_its_layout` | text starts with `xkb_keymap {`; the `xkb_symbols` line contains `us` or `de` | `"us" in "pc_us_inet(evdev)"` is true of every `us`-family map. The `de` line is what fails if the layout argument is ignored. It does not require the symbols name `pc_de_inet(evdev)`, which is what the VM grep should match. Actual lines: `xkb_symbols "pc_us_inet(evdev)"` and `xkb_symbols "pc_de_inet(evdev)"` |
| `test_an_unmappable_character_emits_nothing_through_the_dispatcher` | `type "abcé"` is `ok: false`, `kind == invalid_argument`, `sink.calls == []` | "No event carried `é`" would pass with `a` and `b` typed. This assertion would not |
| `test_a_string_over_the_cap_emits_nothing_…` | 4097 `a`s, same three checks | |
| `test_the_keymap_object_is_built_once_…` | two `type`s leave `dispatcher._keymap` as the same object | **The false pass the verification named.** Re-uploading per string never calls this object twice and stays green |
`tests/pointer/test_ops.py`, new cases. All of them talk to `RecordingSink`, which writes down whatever it was told. A pass means the dispatcher passed those tuples, not that `zwp_virtual_keyboard_v1.key` was marshalled.
| Test | Passes only if | False pass |
| --- | --- | --- |
| `test_the_contracts_ops_are_exactly_what_is_implemented` | `Dispatcher._ops` equals a set literal that includes `key` and `type` and not `release_all_keys` | The docstring says the contract. The test never opens `CONTRACT-sessions.md`. §3.4 still lists neither op, and this stays green |
| `test_key_down_sends_the_code_and_lists_the_name` | `key down Return` → `[("key", 28, 1)]` and `pressed` says `["Return"]` | |
| `test_key_needs_no_warp` | `type "Hi"` and `key a` both `ok` on a dispatcher that never warped, and some call is `key(30, down)` | The `in sink.calls` check is weak (`H` is not code 30; the explicit `key a` supplies it). `ok is True` on `type "Hi"` is the real assertion, and a call to `_aimed()` fails it. Not a false pass of the aim rule |
| `test_a_key_is_not_tagged_with_an_output_…` | after a warp, `key a` is exactly `[("key", 30, 1)]` | A sink that accepted an output argument and ignored it would still look like this, because the dispatcher never passes one. That is what the arity assertion is for |
| `test_key_up_forgets_the_key` | down then up is down, up, and `lifted == ["a"]` | |
| `test_up_of_a_key_that_was_never_down_…` | `ok`, `lifted == []`, no sink calls | |
| `test_keys_are_reported_oldest_first` | `pressed` names are `Control_L`, `Shift_L`, `a` | Does not look at the sink, so a modifier down that forgot the mask still passes |
| `test_a_modifier_down_sends_the_key_and_the_mask` | `Shift_L` down is key 42 then `modifiers(mask, 0, 0, 0)` | |
| `test_a_modifier_up_restores_the_mask_…` | releasing Shift while Control is held sends key-up 42 then Control's mask, not zero | |
| `test_an_ordinary_key_down_sends_no_mask` | `key a` is exactly one key call | This is also why `key A` has no test. The ordinary-key assertion is what a capital would satisfy, wrongly |
| `test_type_of_a_capital_is_the_mask_and_not_a_shift_keycode` | exactly `modifiers(shift), key(30,1), key(30,0), modifiers(0,0,0,0)`, and no code 42 | "Some call had code 30" would be the lie. This list is the worked example. It uses `modifier_mask("Shift_L")`, which on this keymap is 1 |
| `test_type_leaves_no_key_held` | `type "Hello"` leaves `pressed` keys empty | Does not look at the sink |
| `test_type_emits_a_down_up_pair_per_character` | the key calls for `"ab"` are 30 and 48, down/up each | **Filters to `key` calls.** Omitting every `modifiers` stays green. The capital test is what locks the mask |
| `test_type_of_an_empty_string_…` | `ok`, no calls | |
| `test_type_ors_an_explicitly_held_modifier_…` | `down Control_L` then `type c` is `modifiers(control)`, key down/up of `c`'s code, `modifiers(control)` again; `pressed` is still `["Control_L"]`; no key 29 | Full sequence. Not a false pass |
| `test_type_of_a_capital_under_a_held_control_…` | first call is `modifiers(control\|shift)`, last is `modifiers(control)` | **`modifiers(both)` then `modifiers(control)` with no key events passes.** The key, and "no second Control down", are not in the assertion |
| `test_type_while_a_non_modifier_is_held_…` | `ok: false`, `kind` invalid, no new calls, `a` still held | |
| `test_type_while_a_lock_is_held_…` | `Caps_Lock` held, `type a` is `ok: false`, no new calls | Does not check `kind`. A `refused` (exit 10) passes |
| `test_a_string_that_fails_on_its_third_character_…` | `"abé"` is `ok: false` and `calls == []` | Same strength as the keymap twin. Does not check `kind` |
| `test_a_bad_character_is_a_usage_error_and_a_missing_keyboard_is_not` | `é`, `Nope`, and `state=sideways` are `invalid_argument`; the same `type a` on `KeyboardlessSink` is `refused` | This is the token. It does not check that anything maps the token to exit 2. Nothing in `f931858` does |
| `test_without_a_keymap_at_all_…` | `Dispatcher(sink, None)` still warps and buttons; `type` is `refused` | |
| `test_release_all_lifts_keys_in_press_order_then_zeroes_the_mask` | `Control_L` then `a` lifts 29, then 30, then `modifiers(0,0,0,0)` | |
| `test_release_all_lifts_keys_after_buttons_and_adds_no_keyboard_frame` | button up, one pointer `frame`, key up 42, `modifiers(0,…)` | Locks the frame *before* the key-up. The plan's step list puts the pointer frames last. Buttons and keys are different objects; the frame does not gate the key. Not a false pass, and not worth reordering unless a client is shown to care |
| `test_release_all_lifts_keys_even_after_a_warp_to_another_output` | after a warp to another output, the only call is `key(30, up)` | A plain `a` never touched the mask, so the absent `modifiers` is correct (`_mask_touched` is false). A sink that ignored an output argument cannot fake this: the call has no output slot |
| `test_release_all_without_a_keyboard_still_lifts_buttons` | keymap present, `has_keyboard` false, a held button: `lifted == ["left"]`, `lifted_keys == []`, and the calls are button up plus frame | `KeyboardlessSink.key` raises. If the key half ran, the test errors rather than passes. It does not hold a key, which is the only degraded state the process can reach |
| `test_release_all_after_a_type_zeroes_the_mask_once_more` | after `type A`, `release_all` is exactly one `modifiers(0,0,0,0)` | `_mask_touched` stays true after `type` restores the baseline. A `type` that never sent a non-zero mask would not take this branch; `type a` is not this test |
`tests/pointer/test_driver_flags.py`:
| Test | Passes only if | False pass |
| --- | --- | --- |
| `test_the_xkb_flags_default_to_the_frozen_values` | `parse_args([])` is `us` / `pc105` / empty variant / empty options | Parsing only. `main` could ignore them; the refusal tests below are what catch that for a *bad* value |
| `test_the_defaults_are_the_ones_the_module_option_defaults_to` | the two Python constants equal `("us", "pc105")` | **Does not read `nix/module.nix`.** In `f931858` the unit's `ExecStart` is still the two-flag line (`nix/module.nix:986-992`) and there is no `sessions.keyboard` option. The docstring says the module and the binary cannot drift. They are not compared |
| `test_a_layout_is_taken_from_the_flag` | `parse_args(["--xkb-layout", "de"]).xkb_layout == "de"` | Parsing only |
| `test_the_contract_command_line_still_parses` | the §3.4 line plus the four XKB flags parses | The contract text is not read, and it does not yet contain those flags |
| `test_a_comma_separated_layout_exits_2_without_connecting` | `main(["--xkb-layout", "us,ru"])` is exit 2 and `WaylandSink` was never constructed | The injected sink raises if constructed. A connect that happened would fail the test, not pass it |
| `test_a_layout_xkbcommon_rejects_exits_2_without_connecting` | `zzz-no-such-layout` is exit 2, same injection | Ignoring the flag and always compiling `us` would reach `connect` and fail this. The flag is actually wired |
| `test_a_usable_layout_gets_as_far_as_the_compositor` | `main(["--xkb-layout", "us"])` raises `_Unreached("connect")` | Stops at connect. See finding 3 |
| `test_the_exit_codes_match_the_brokers_table` | the three constants are 0, 2, 10 | Does not import `hhstreamd.protocol`. Two copies can diverge and this still passes |
`tests/pointer/test_lease.py`, the new key cases. They call `press_key` on the lease directly. None of them opens a socket. A pass does not mean a verb updates the mirror; no verb in `f931858` does (`manager.py` never calls `press_key`).
| Test | Passes only if | False pass |
| --- | --- | --- |
| `test_press_and_lift_one_key` | `press_key` / `keys_pressed` / `unpress_key`, and a later `release` has `keys_lifted == []` | |
| `test_lifting_a_key_that_is_not_down_…` | `unpress_key` of a key not held is `[]` | |
| `test_keys_are_kept_in_press_order` | order is press order, including after one is removed; `release().keys_lifted` is what remained | |
| `test_pressing_a_key_twice_leaves_one_down` | a dict, so the second `press_key` does not duplicate | The driver does not share this dict. A double `key down` still sends two presses; this test cannot see that |
| `test_keys_and_buttons_are_tracked_separately` | `release` reports buttons and keys independently | |
| `test_a_non_holder_cannot_press_a_key` | `LeaseInvalid` for the other session | |
| `test_expire_still_returns_no_key_list_…` | read `keys_pressed()`, then `expire()`; the return has no `keys_lifted` and no `buttons_lifted`; the lease is then empty | `hasattr` fails if someone adds the field to `LeaseInfo`. Widening the return is what this is for |
| `test_expiry_does_not_leak_keys_to_the_next_holder` | after `expire`, the next `acquire` sees no keys | |
`tests/pointer/test_vendored_protocol.py`, the keyboard cases. The source-text tests pass if the generated file contains the substring, including in a comment. The two `skipif` tests import pywayland and check `hasattr` and `version == 1`, which is a real bind of the generated class, still with no display.
| Test | Passes only if | False pass |
| --- | --- | --- |
| `test_the_keyboard_protocol_is_vendored_beside_the_pointer_one` | the package exists and every `.py` starts with the scanner banner | |
| `test_the_keyboard_manager_is_version_1_with_the_seat_only_request` | the source contains the interface name, `version = 1`, `create_virtual_keyboard(self, seat: WlSeat)`, and not `WlOutput` | A comment with that signature passes |
| `test_the_keyboard_carries_keymap_key_and_modifiers` | source contains the three signatures, `ArgumentType.FileDescriptor`, and no `def frame(` | Same |
| `test_the_integers_the_xml_names_but_does_not_define_live_in_our_code` | the generated file mentions `keymap_format` and does not define the enum; `XKB_V1 == 1`; `STATES` is 0 and 1 | Does not check that `upload_keymap` passes 1. A call with format 2 stays green |
| `test_the_shim_resolves_the_keyboard_relative_import` | the manager module imports `WlSeat` from `..wayland` | |
| `test_the_keyboard_protocol_binds_against_the_installed_pywayland` | import, name, version 1, and the four requests exist on the proxy | Skipped when pywayland is absent. The package check is what runs in the build |
| `test_the_backend_binds_…_and_survives_its_absence` | `KEYBOARD_MANAGER_VERSION == 1` and an unconnected sink reports no keyboard | See finding 3. It never runs `_on_global` |
| `test_the_backend_refuses_a_version_1_manager` | `ManagerTooOld(1)` mentions version 1 and `create_virtual_pointer_with_output` | This is the *pointer* manager. It says nothing about a keyboard global at the wrong version. `_on_global` binds `KEYBOARD_MANAGER_VERSION` whenever the name matches (`backend.py:362-366`) and does not reject a compositor that advertised something else |
`tests/pointer/test_pointer_server.py` only grew `keys` / `lifted_keys` in two assertions. A pass means the JSON reply gained those fields. It does not send `key` or `type`.
## What Stage 2 must not assume
Three of these, left alone, make Stage 2 wrong. The rest are the same class of mistake at lower cost.
1. **`{"op":"key","key":"A"}` does not type `A`.** Neither does `at` on `de`, or any other keysym whose producing mask is non-zero. `type` does, and it ORs that mask with the baseline of keys that are actually modifiers. `keyboard key` / `down` / `up` must not be "send the name through unchanged" until finding 1 is fixed, and a VM check that only runs `keyboard type` will not catch it. `a` and `A` are two held names for evdev 30. `Caps_Lock` down sends the key and never a locked mask; `type` then refuses. Do not document Caps as capitalization.
2. **`kind` does not survive the broker client, and every refusal is exit 10.** `PointerDriver._exchange` raises `DriverRejected` from `reply["error"]` and drops everything else (`src/hhstreamd/driver.py:158-159` at `f931858`). `_drive` maps every `DriverRejected` to `driver_refused` (`manager.py:2047`). A Stage 2 test that asserts exit 2 for `é` fails, or it passes by reading the English. Read `kind` off the JSON *before* that conversion and map `invalid_argument` to exit 2. Leave `refused` as exit 10. The 4096 check lives only in `resolve_text`. A broker check of `len(text.encode())` disagrees with it on the emoji case the driver already got right. `Rejected` text carries an index; do not log `text`, and do not put it on `keyboard_type`.
3. **Do not design the enter subtest, the unit argv, or `kill -9` from the comments in `__main__.py`.** `pointer acquire` is still one warp (`manager.py` `_warp`, unchanged in this commit) and Stage 0's (a1) did not deliver `wl_keyboard.enter`. A second warp to the same floored pixel is not the fix. `nix/module.nix` does not pass `--xkb-layout`; the flag defaults to `us`, so the running unit types `us` until Stage 2 adds the argv. A `[keyboard]` table in the broker TOML is still not the upload — the driver never opens that file. `input:virtualkeyboard:release_pressed_on_close` is not set, whatever `__main__.py:191-193` says. `upload_keymap` is not idempotent: a second call creates a second virtual keyboard and orphans the first (`backend.py:227`). Do not call it on acquire or per string.
Also, because the mirror landed here and nothing uses it:
- `expire()` still returns `LeaseInfo` with no keys (`pointer.py:178-196`). `_expire_pointer` reads `pressed()` and not `keys_pressed()` (`manager.py:1857`). Read the keys first. The driver's one `release_all` is what lifts them; do not add `release_all_keys`.
- The committed `PointerDriver.release_all` returns the button list only (`driver.py` `release_all`), and `_release_all_buttons` does `list(lifted)` (`manager.py:2058-2061`). The new reply field is `lifted_keys` beside `lifted`. Changing the client method to return a tuple without updating that `list()` turns the button names into the two lists.
- `pressed()` on the client still returns buttons only. The reply now also has `keys`. Do not widen the return of `pressed()` in place.
- `keyboard.key` and `keyboard.type` are not in `MUTATING_VERBS`. `pointer.state` must stay out of it. No keyboard verb calls `touch`. Acquire's stderr still says "pointer" only; a `keyboard.*` verb that goes through `_refresh` moves the deadline, and the help text has to say so.
- `CONTRACT-sessions.md` §3.4 is still the two-flag command line and a `pressed` / `release_all` with no key fields (`:262`, `:283-284`). Amend it in the same change as the unit argv. `test_the_contracts_ops_…` will not notice if you forget.
## Carried objections
From the Stage 0 review, still true of `f931858`, with one correction for where the branch tip is:
- **The plan banner is not in this commit.** `git grep` of `f931858` for the supersession banner is empty, so anyone who builds Stage 1 from that commit alone still has the unedited exit-code paragraph, the `[keyboard]` TOML rows, and "if it repeats, the help text says so". `b1f2744` (after this commit, not reviewed here) adds the banner and folds the eight rows. Do not treat that as something Stage 1 did, and do not do it again.
- **Stage 0's (a) mechanism, as `f931858` inherited it.** This commit does not cite it. The parent commit's README did. `b1f2744` rewrites that README; it was not re-checked for this review. Stage 2 still must not read "one warp late" as "wait longer" or as "warp twice to the same point".
- **`mask_cleared=no` is not a held Shift.** `backend.py:246-250` cites `tests/README-keyboard-probe.md` for "destroy does not clear the modifier mask". The send of `modifiers(0,0,0,0)` after upload is right anyway — `releasePressed` never emits modifiers — but the citation is the sentence Stage 0 said the log does not support. The cleanup `state=0` for code 30 is the poison evidence, and it is why finding 2 is not theoretical.
- **The Hyprland XML, kept on purpose.** `regenerate.py` says wayland-protocols has no `virtual-keyboard` directory in this nixpkgs and vendors Hyprland's copy, which names `keymap_format` and `key_state` and defines neither. `XKB_V1 = 1` and `buttons.STATES` are the right workaround. Switching later, if a nixpkgs grows the file, does not move the integers. Do not vendor a second copy to get an enum.
- **Changes 5 and 8, the halves this stage did not take.** The driver half of 5 is done (flag, comma rejected before `xkb_keymap_new_from_names`, no `rules` flag, `evdev` hardcoded). The unit argv is not. The driver half of 8 is done (index and `U+` codepoint, and the server does not log the request line). Acquire's stderr is untouched. Change 7 (the probe's expectations, the unconditional `keyboard down` warning) is not this stage; the warning has nowhere to live until the CLI exists, and it is still unconditional when it does.
- **`xkbcommon` is a hard dependency** (`pyproject.toml`, `nix/package.nix`). Leave it that way. An optional one lets `test_keymap.py` skip, and the unmappable path is the one that rots.
+43
View File
@@ -90,7 +90,50 @@ in ''
# aimed correctly and delivered nowhere. The cursor lease already
# serialises input, so letting the pointer move keyboard focus cannot make
# two sessions fight over the keyboard.
#
# It is also what moves the KEYBOARD, which matters now that the broker
# injects keys as well: a virtual keyboard is seat-global and has no
# output, so the warp is the only thing that decides which window the
# letters land in, and the lease is what stops another session retargeting
# them mid-string.
follow_mouse = 1
# Set explicitly, at its default value, because `pointer acquire` now
# depends on it rather than merely benefiting from it.
#
# MEASURED (tests/README-keyboard-probe.md): one warp onto an idle cursor
# delivers `wl_pointer.enter` and NO `wl_keyboard.enter`. Hyprland's
# `onMouseWarp` goes through `mouseMoveUnified(refocus=false)`, which
# *sets* `m_mousePosDelta` to 0 when the previous movement was more than
# 0.5 s ago, and keyboard focus is that delta compared against this
# threshold. So acquire sends two motions a real pixel apart: the second
# carries a non-zero delta, and `> 0` is true only because this is 0.
#
# Raise it and `hhstream session pointer acquire` stops taking keyboard
# focus — the cursor would land in the session's window and the first
# keystroke would go to whatever was focused before.
follow_mouse_threshold = 0
# Release a virtual keyboard's held keys when its resource is destroyed.
#
# MEASURED, and the default is `false`: `destroy` with a key down
# delivered no key-up at all. That is worse than a stuck key, because
# `InputManager::onKeyboardKey` *drops* a press whose code is already in
# the seat's `m_pressed` — so a driver killed with `-9` leaves that code
# there and the next driver's press of it is ignored. The key is dead,
# not merely held, and nothing in the logs says so.
#
# The driver's own shutdown path lifts keys first
# (`hhstream_pointer.__main__._lift_everything`) and SIGKILL skips it;
# this is the backstop for that case.
#
# It does NOT clear the modifier mask: `releasePressed` emits key-ups and
# never a `modifiers`, and a client keeps the last mask it was sent. That
# is why `release_all` ends with `modifiers(0, 0, 0, 0)` on every path we
# control, and why this setting is a backstop rather than the mechanism.
virtualkeyboard {
release_pressed_on_close = true
}
}
# Frames cost capture bandwidth and CPU, and no one is watching the easing.
+94 -5
View File
@@ -620,6 +620,80 @@ in {
};
};
# The keyboard has no `enable` of its own: it is the same unit, the same
# process and the same lease as the pointer (`hhstream session keyboard
# …` refuses with exit 9 until `pointer acquire`). What it needs from an
# operator is a layout, because the keymap the driver uploads is the only
# thing that decides which keycode a keysym is -- Hyprland's own
# `input:kb_layout` is not read and does not affect injected keys.
keyboard = {
layout = lib.mkOption {
# `strMatching` and not `str`, and the pattern is the point: it is
# what refuses `us,ru`. A comma-separated layout compiles perfectly
# well into a two-group keymap, and v1 sends `group = 0` in every
# `modifiers` request -- so the second group would be unreachable and
# an agent asking for a Cyrillic character would silently get a Latin
# one. The driver refuses a comma too, for a binary run by hand.
type = lib.types.strMatching "[A-Za-z0-9_-]+";
default = "us";
example = "de";
description = ''
XKB layout the `hhstream-pointer` unit compiles once at start-up and
uploads as its virtual keyboard's keymap (rules `evdev`, model from
{option}`sessions.keyboard.model`).
**This is the only thing that decides what an injected key means.**
Every `hhstream session keyboard` verb names an XKB *keysym*
(`a`, `A`, `Return`, `Control_L`), and the driver resolves that name
against this keymap to get the evdev code and the modifier mask the
compositor is sent. A character this layout cannot produce is
refused with exit 2 and nothing is typed -- there is no partial
type, so `é` on `us` fails the whole string rather than the letter.
Hyprland's `input:kb_layout` is **not** read. It describes the
layout for physical keyboards, of which a headless session has none,
and reading it would mean a `hyprctl` reload could silently change
what every agent types. One group only: see the type.
'';
};
model = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9_-]*";
default = "pc105";
description = ''
XKB model for the same keymap. `pc105` unless an operator knows
otherwise; it decides little beyond which keys exist at all.
'';
};
variant = lib.mkOption {
type = lib.types.str;
default = "";
example = "intl";
description = ''
XKB variant, empty by default.
Worth knowing before setting one: a variant whose characters are
**dead keys** -- `us(intl)`'s accents, for instance -- cannot be
typed by this version. A dead key is half of a compose sequence and
v1 emits one event per character, so the driver refuses the name
rather than arming the next keystroke in the focused application.
'';
};
options = lib.mkOption {
type = lib.types.str;
default = "";
example = "ctrl:nocaps";
description = ''
XKB options, empty by default. Passed through to
`xkb_keymap_new_from_names`; a value it rejects stops the driver
with exit 2 before it connects to the compositor, so a typo here is
a failed unit rather than a session that types the wrong thing.
'';
};
};
stateDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/hhstream";
@@ -978,17 +1052,32 @@ in {
# plainly that stopping the driver stops the driver and nothing else.
KillMode = "process";
# Frozen in docs/CONTRACT-sessions.md §3.4, word for word. The driver
# defaults to both of these paths anyway; they are passed explicitly
# because the contract specifies the command line, and a unit that
# relied on the defaults would stop matching it the moment either
# default moved.
# The first two flags are frozen in docs/CONTRACT-sessions.md §3.4,
# word for word. The driver defaults to both of those paths anyway;
# they are passed explicitly because the contract specifies the command
# line, and a unit that relied on the defaults would stop matching it
# the moment either default moved.
#
# The four XKB flags are the **only** path a layout has to the uploaded
# keymap, and that is worth being blunt about: the broker's TOML has a
# `[pointer]` table that `hhstreamd` reads for its lease numbers, and
# this is a different unit that never opens that file. A `[keyboard]`
# table there would be a setting an operator could change while every
# injected key stayed on `us`.
ExecStart = lib.escapeShellArgs [
(lib.getExe' cfg.package "hhstream-pointer")
"--socket"
pointerSocket
"--compositor-runtime-dir"
runtimeDir
"--xkb-layout"
cfg.sessions.keyboard.layout
"--xkb-model"
cfg.sessions.keyboard.model
"--xkb-variant"
cfg.sessions.keyboard.variant
"--xkb-options"
cfg.sessions.keyboard.options
];
};
};
+4 -1
View File
@@ -190,7 +190,10 @@ def main(argv: list[str] | None = None) -> int:
# `m_pressed` makes the *next* driver's press of that code a no-op. So
# this is the only orderly guard there is -- and SIGKILL skips it,
# which is why nix/hyprland-conf.nix also sets
# `input:virtualkeyboard:release_pressed_on_close`.
# `input:virtualkeyboard:release_pressed_on_close = true`. That setting
# emits key-ups only and never a `modifiers`, so it is a backstop for
# the keys and not for the mask: zeroing the mask is `release_all`'s,
# on every path we control.
_lift_everything(dispatcher)
server.close()
sink.close()
+12 -1
View File
@@ -64,7 +64,11 @@ MAX_TEXT_SCALARS = 4096
#: Characters with no printable keysym that are still worth typing. Everything
#: else below U+0020 is refused: a C0 control is either one of these two or a
#: caller that pasted a terminal escape.
CONTROL_KEYSYMS = {"\n": "Return", "\t": "Tab", "\r": "Return"}
#:
#: ``\r`` is deliberately **not** here. The plan exempts ``\n`` and ``\t`` and
#: nothing else, and a carriage return silently typed as ``Return`` means a
#: caller who pasted CRLF gets two newlines per line with no way to find out.
CONTROL_KEYSYMS = {"\n": "Return", "\t": "Tab"}
#: What the detection below **measures** on ``us``/``pc105``. Not used to
#: decide anything — the keymap decides — but asserted in the tests, because a
@@ -141,6 +145,13 @@ def build(
"Do not add a `rules` option; the driver hardcodes `evdev`").
"""
if not layout:
# xkbcommon accepts an empty layout and compiles the *same keymap as
# `us`* -- `xkb_symbols "pc_us_inet(evdev)"`. So `--xkb-layout ''`
# would look configured, type `us`, and never say so. Refused for the
# same reason the comma is: a layout that silently is not the one the
# operator named.
raise KeymapError("no layout given; pass one (the default is 'us')")
if "," in layout:
# Refused here rather than by xkbcommon, which accepts `us,ru` happily
# and gives a two-group keymap. v1 sends `group = 0` in every
+46 -5
View File
@@ -142,9 +142,19 @@ class Dispatcher:
#: button name -> the output its press was sent to. Insertion-ordered,
#: so a release_all lifts in the order things went down.
self._pressed: dict[str, str] = {}
#: keysym name -> the mask it contributes while held (0 for an ordinary
#: key). Insertion-ordered for the same reason as ``_pressed``.
#: keysym name -> the mask it *contributes* while held, which is 0 for
#: an ordinary key. Insertion-ordered for the same reason as
#: ``_pressed``. Deliberately not the mask the key *needs* to produce
#: its symbol: ``type`` reads a zero contribution as "not a modifier,
#: refuse", so storing ``A``'s Shift requirement here would make a held
#: capital look like a held modifier.
self._keys: dict[str, int] = {}
#: keysym name -> the evdev code it was pressed as, so a second name
#: for a code that is already down can be refused. ``A`` and ``a`` are
#: one keycode: holding both would send two presses, the compositor
#: would drop the second, and the held set would be a lie for as long
#: as the lease lasted.
self._codes: dict[str, int] = {}
#: Whether we have ever sent a non-zero modifier mask. ``release_all``
#: zeroes the mask only if something set it: a mask we never touched is
#: not ours to clear, and on a compositor with no keyboard global
@@ -259,9 +269,31 @@ class Dispatcher:
action = _resolved(keymap.resolve_name, name)
if state == "down":
self._sink.key(action.code, buttons.STATES["down"])
held_as = {code: held for held, code in self._codes.items()}
clash = held_as.get(action.code)
if clash is not None and clash != name:
# `A` and `a` are the same keycode at two levels. Holding both
# would send `key(30, pressed)` twice; the compositor drops the
# second because the code is already in its `m_pressed`, and
# then `release_all` sends two ups of which one is also
# dropped. Nothing breaks and the held set is wrong the whole
# time, which is worse than a refusal.
raise Rejected(
f"{name!r} is the same key as {clash!r}, which is already held",
kind=KIND_INVALID,
)
contribution = keymap.modifier_mask(name) if keymap.is_modifier(name) else 0
# The mask the *symbol* needs, before the press, exactly as `type`
# does it. Without this `keyboard down A` sends a bare code 30 and
# the window receives `a` -- and on `de`, `at` loses its level-three
# mask and becomes `q`. A modifier key's own `action.mask` is 0, so
# this is a no-op for `Shift_L` and the key-then-mask order below
# is unchanged.
if action.mask:
self._set_mask(self._baseline() | action.mask)
self._sink.key(action.code, buttons.STATES["down"])
self._keys[name] = contribution
self._codes[name] = action.code
if contribution:
self._set_mask(self._baseline())
return {"ok": True, "keys": list(self._keys), "lifted": []}
@@ -272,9 +304,17 @@ class Dispatcher:
# track, and sending a key-up the compositor never had a key-down
# for is how its `m_pressed` gets out of step with ours.
return {"ok": True, "keys": list(self._keys), "lifted": []}
was_modifier = bool(self._keys.pop(name))
was_modifier = bool(self._keys[name])
self._sink.key(action.code, buttons.STATES["up"])
if was_modifier:
# Forgotten only after the send, the way `_op_button` updates
# `_pressed` only after its send: a raise from the sink between the two
# would otherwise leave us believing the key is up while the compositor
# still has it down, and `release_all` would not try again.
del self._keys[name]
self._codes.pop(name, None)
if was_modifier or action.mask:
# Back to whatever is still held -- which for a capital is the
# baseline it had before, since its Shift was never a hold.
self._set_mask(self._baseline())
return {"ok": True, "keys": list(self._keys), "lifted": [name]}
@@ -352,6 +392,7 @@ class Dispatcher:
self._sink.key(self._keymap.resolve_name(name).code, buttons.STATES["up"])
lifted_keys = list(self._keys)
self._keys.clear()
self._codes.clear()
if self._mask_touched:
# Only if something set it. With no keyboard global at all this is
# False, and the button lifting above has to keep working: one
+253 -4
View File
@@ -35,10 +35,17 @@ The verb tree, beyond the original eight:
session pointer move ID ... warp, --to X,Y or --by DX,DY (0..1, per output)
session pointer click/down/up/release ID
session pointer state who holds the cursor and what is pressed
session keyboard type ID TEXT one argument, raw UTF-8, no escapes
session keyboard key ID NAME tap: down then up
session keyboard down/up ID NAME
The pointer verbs share one precondition — the lease — and the lease id lives
in :mod:`hhstream_session.lease` between invocations, because the wire requires
it on every gesture and the CLI is one process per verb.
The pointer *and keyboard* verbs share one precondition — the pointer lease —
and the lease id lives in :mod:`hhstream_session.lease` between invocations,
because the wire requires it on every gesture and the CLI is one process per
verb. There is no ``keyboard acquire``: one ``wl_seat`` means one keyboard
focus, and the shipped ``follow_mouse = 1`` means another session's warp
retargets the keys, so a second lease would let session B move the pointer
while session A believed it was typing into its own window.
"""
from __future__ import annotations
@@ -293,6 +300,9 @@ def _build_namespace(parser: argparse.ArgumentParser) -> None:
# ---- pointer -----------------------------------------------------
_build_pointer(verbs, common)
# ---- keyboard ----------------------------------------------------
_build_keyboard(verbs, common)
#: Button names the driver knows (``hhstream_pointer.buttons.CODES``), mirrored
#: here rather than imported: this module's whole integration promise is that it
@@ -475,6 +485,148 @@ def _build_pointer(verbs: Any, common: argparse.ArgumentParser) -> None:
)
#: Printed under `keyboard --help` and under every one of its verbs. It is the
#: single fact an agent gets wrong about this group, exactly as ACTIVITY_NOTE is
#: for the namespace: the keyboard has no lease of its own.
KEYBOARD_LEASE_NOTE = (
"LEASE: every keyboard verb needs the POINTER lease and refuses with exit 9 "
"until 'hhstream session pointer acquire <id>'. There is no 'keyboard "
"acquire': the compositor has one seat and one keyboard focus, and another "
"session's pointer warp would retarget the keys mid-string. 'pointer "
"release' lifts held keys as well as held buttons, and so does a lease "
"timeout."
)
def _build_keyboard(verbs: Any, common: argparse.ArgumentParser) -> None:
"""``session keyboard <verb>`` — typing into whatever the seat focuses.
A nested namespace for the same reason ``pointer`` is one: these four verbs
share a precondition nothing else here has. It is the *pointer* lease, and
saying that once in a group description is better than four times in four
help strings -- though the note is repeated per verb anyway, because
``--help`` on a leaf is what an agent actually reads.
"""
namespace = verbs.add_parser(
"keyboard",
parents=[common],
help="type into the session the seat is focused on, under the pointer lease",
description=(
"Keys go to whichever surface the compositor's one seat has focused "
"-- a virtual keyboard is seat-global and has no output argument, so "
"unlike the pointer there is nothing to aim. What aims it is the "
"pointer: 'pointer acquire' warps into the session's own container "
"and the lease is what stops another session moving focus while you "
"type.\n\n"
"NAME is an XKB keysym name, not a number: 'a', 'A', 'Return', "
"'BackSpace', 'Left', 'Control_L', 'Shift_L'. It is resolved against "
"the layout the driver uploaded (set by the operator; 'us' by "
"default), so a name that layout does not carry is exit 2.\n\n"
"TEXT is one argument of raw UTF-8 and backslash escapes are NOT "
"interpreted: a newline is a real newline in the argument and the "
"shell does the quoting. A character the layout cannot produce "
"fails the whole string and types nothing -- there is no partial "
"type.\n\n"
"No keyboard verb counts as activity, exactly as no pointer verb "
"does. Call 'touch'."
),
epilog=f"{KEYBOARD_LEASE_NOTE}\n\n{ACTIVITY_NOTE}",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
keys = namespace.add_subparsers(dest="keyboard_verb", metavar="VERB")
# With no verb, print this group's help rather than guessing: unlike
# `pointer`, there is no read-only verb here that could be the default --
# held keys are reported by `pointer state`, which is where buttons are.
namespace.set_defaults(
func=_cmd_keyboard_usage, hhstream_session_handler=_cmd_keyboard_usage, json=False
)
namespace.set_defaults(keyboard_parser=namespace)
def add_key_verb(name: str, handler, **kwargs: Any):
sub = keys.add_parser(
name,
parents=[common],
epilog=KEYBOARD_LEASE_NOTE,
formatter_class=argparse.RawDescriptionHelpFormatter,
**kwargs,
)
sub.set_defaults(func=handler, hhstream_session_handler=handler)
sub.add_argument("--json", action="store_true", help="emit the protocol object on stdout")
sub.add_argument(
"--lease",
metavar="ID",
help="the lease id from 'pointer acquire'. Omitted, the one that "
f"acquire cached is used (${lease.ENV_LEASE} overrides that).",
)
sub.add_argument("id", help="session id")
return sub
type_ = add_key_verb(
"type",
_cmd_keyboard_type,
help="type one string into the focused window",
description=(
"Type TEXT. One argument, raw UTF-8, no backslash escapes: '\n' is "
"a backslash and an n, and a newline is a newline. Capitals and "
"symbols are sent as a modifier MASK plus the letter's key, not as "
"a synthesized Shift keypress, because this compositor does not "
"derive the mask from an injected key.\n\n"
"Validation is complete before the first event: a character the "
"uploaded layout cannot produce fails the request and types "
"nothing, so there is never a half-typed prefix to clean up. On the "
"default 'us' layout that includes 'e' with an acute accent, and "
"every C0 control except newline and tab.\n\n"
"A modifier held with 'keyboard down' is a baseline: its mask is "
"ORed into every character and it is STILL HELD when this returns, "
"which is how a chord is spelled. A non-modifier key held is a "
"refusal, because the application still believes it is being held."
),
)
type_.add_argument(
"text",
help="the string to type, as ONE argument (quote it; a newline is a newline)",
)
tap = add_key_verb(
"key",
_cmd_keyboard_key,
help="tap one keysym: down then up",
description=(
"Press and release one key. This is the verb for 'Return', 'Tab', "
"'BackSpace' and the arrows -- anything 'type' cannot express "
"because it has no character."
),
)
tap.add_argument("name", help="XKB keysym name, e.g. Return, BackSpace, Left")
for verb, state in (("down", "down"), ("up", "up")):
sub = add_key_verb(
verb,
_cmd_keyboard_hold,
help=(
"hold a key down without releasing it"
if state == "down"
else "release a key that was held down"
),
description=(
"Half a tap. The justified use is a chord: 'down Control_L', "
"then 'type c', then 'up Control_L'.\n\n"
"HOLDING A NON-MODIFIER FLOODS THE WINDOW. The compositor sends "
"one key event and publishes a repeat rate; the APPLICATION "
"repeats, so a held 'a' inserts characters for as long as it is "
"down -- up to the whole lease TTL. This is not configurable "
"here: the repeats are not ours to rate-limit. Measured on this "
"build at 25/s after 600ms.\n\n"
"The broker lifts whatever is still down on 'pointer release' "
"or on a lease timeout, so a crashed agent cannot leave a key "
"held."
),
)
sub.set_defaults(key_state=state)
sub.add_argument("name", help="XKB keysym name, e.g. Control_L, Shift_L")
def _button_help() -> str:
return f"one of: {', '.join(BUTTONS)} (default: left)"
@@ -938,7 +1090,8 @@ def _cmd_pointer_acquire(args: argparse.Namespace) -> int:
)
print(
f"expires in {_fmt_timeout(reply.get('expires_in_s'))} with no further "
f"pointer verb; release it with: hhstream session pointer release {args.id}",
f"pointer OR keyboard verb; release it with: hhstream session pointer "
f"release {args.id}",
file=sys.stderr,
)
return int(ExitCode.OK)
@@ -1057,6 +1210,102 @@ def _cmd_pointer_state(args: argparse.Namespace) -> int:
return _finish(args, reply, fmt.render_pointer_state)
# --------------------------------------------------------------------------
# the keyboard, on the same lease
# --------------------------------------------------------------------------
def _cmd_keyboard_usage(args: argparse.Namespace) -> int:
"""`session keyboard` with no verb. Prints help, exits 2.
Not a default verb: the only read-only thing to say about the keyboard is
which keys are held, and that is `pointer state`, beside the buttons.
"""
parser = getattr(args, "keyboard_parser", None)
if parser is not None:
parser.print_help(sys.stderr)
return int(ExitCode.USAGE)
@_guard
def _cmd_keyboard_type(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
# `args.text` goes through untouched. No `.encode().decode('unicode_escape')`
# and no strip: the shell quoted it, and a CLI that interpreted backslashes
# would make a literal backslash-n untypeable.
reply = _request(args, "keyboard.type", id=args.id, lease_id=lease_id, text=args.text)
def render(r: dict[str, Any]) -> str:
held = r.get("keys") or []
# The COUNT, never the text: this line goes to a terminal that is
# often being logged, and the string is a password as often as not.
bits = [f"{r.get('id')}: typed {r.get('chars')} character(s)"]
if held:
bits.append(f"still held: {', '.join(held)}")
return "; ".join(bits)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_keyboard_key(args: argparse.Namespace) -> int:
"""A tap: down then up, as two wire calls.
Two calls and not a `count`-style loop in the broker, because a tap is the
only thing anyone wants and the pair is what `down`/`up` already are. The
`up` is sent even if the `down` was refused-after-sending, for the same
reason the broker lifts on expiry: a key left down is worse than stuck.
"""
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
down = _request(
args, "keyboard.key", id=args.id, lease_id=lease_id, key=args.name, state="down"
)
if not down.get("ok"):
return _finish_gesture(args, down, lambda r: "", args.id)
reply = _request(
args, "keyboard.key", id=args.id, lease_id=lease_id, key=args.name, state="up"
)
def render(r: dict[str, Any]) -> str:
held = r.get("keys") or []
return (
f"{r.get('id')}: tapped {args.name}; "
f"held: {', '.join(held) if held else 'nothing'}"
)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_keyboard_hold(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
reply = _request(
args,
"keyboard.key",
id=args.id,
lease_id=lease_id,
key=args.name,
state=args.key_state,
)
def render(r: dict[str, Any]) -> str:
held = r.get("keys") or []
return (
f"{r.get('id')}: {args.name} {args.key_state}; "
f"held: {', '.join(held) if held else 'nothing'}"
)
return _finish_gesture(args, reply, render, args.id)
# --------------------------------------------------------------------------
# standalone use
# --------------------------------------------------------------------------
+7
View File
@@ -275,12 +275,19 @@ def render_bookmark(bookmark: dict[str, Any] | None) -> str:
def render_pointer_state(reply: dict[str, Any]) -> str:
holder = reply.get("holder")
buttons = reply.get("buttons") or []
keys = reply.get("keys") or []
lines = [
f"holder {holder if holder else 'free'}",
f"lease {_cell(reply.get('lease_id'))}",
# Loud, because a button left down is the one pointer failure that keeps
# hurting after the lease is gone.
f"buttons {', '.join(buttons) if buttons else 'none down'}",
# Keys are here and not under a `keyboard state` verb, because they are
# the same lease and the same kind of leak -- and a held key is the
# worse one: this compositor drops the *next* press of a code it still
# believes is down, so a leaked key is dead rather than merely stuck.
# Names, as everywhere else on this surface, never evdev codes.
f"keys {', '.join(keys) if keys else 'none down'}",
f"bookmark {render_bookmark(reply.get('bookmark'))}",
f"driver {_cell(reply.get('driver'))}",
]
+77 -14
View File
@@ -1,9 +1,9 @@
"""The broker's end of the private driver socket (CONTRACT-sessions.md §3.4).
The pointer driver is a separate process because a Wayland client needs its own
connection; this module is the five-verb client that talks to it. It is the
only place in the broker that knows the driver's wire format, so the driver and
the broker can be read against each other in two files.
The input driver is a separate process because a Wayland client needs its own
connection; this module is the client that talks to it. It is the only place
in the broker that knows the driver's wire format, so the driver and the broker
can be read against each other in two files.
**It holds no lease state and asks for none.** The driver is an executor: it
will warp anywhere it is told, and the only thing that stops two sessions
@@ -27,7 +27,10 @@ for EOF before each write and silently replaced — but a request that *was*
written and then went unanswered is never sent again, because a repeated
``button down`` is a click the agent did not ask for. Every failure is
:class:`DriverUnavailable` — never a guess, and never a silent no-op, because a
dropped ``release_all`` leaves a mouse button down.
dropped ``release_all`` leaves a mouse button down **and a key down**, and on
this compositor a key left in the seat's ``m_pressed`` is worse than stuck: the
*next* press of that code is dropped, so the key is dead until something sends
a matching up.
"""
from __future__ import annotations
@@ -60,7 +63,22 @@ class DriverUnavailable(Exception):
class DriverRejected(Exception):
"""The driver understood the request and refused it (``ok: false``)."""
"""The driver understood the request and refused it (``ok: false``).
``kind`` is the driver's machine-readable reason, straight off the wire
(``hhstream_pointer.ops.KIND_INVALID`` / ``KIND_REFUSED``). It exists
because two very different failures arrive through this one exception — "no
such keysym on your layout" and "this compositor has no virtual keyboard"
— and they are exit 2 and exit 10. Telling them apart by matching on the
message text would be a mapping that breaks when the wording improves.
An older driver sends no ``kind`` at all; the default then keeps today's
behaviour, which is to report everything as a compositor-side refusal.
"""
def __init__(self, message: str, *, kind: str | None = None) -> None:
super().__init__(message)
self.kind = kind
class PointerDriver:
@@ -73,7 +91,7 @@ class PointerDriver:
self._sock: socket.socket | None = None
self._stream = None
# -- the five verbs ---------------------------------------------------
# -- the verbs --------------------------------------------------------
def warp(self, output: str, x: float, y: float) -> None:
"""Aim at ``x``/``y``, each 0..1 in ``output``'s own frame."""
@@ -100,6 +118,30 @@ class PointerDriver:
self.request({"op": "frame"})
def key(self, key: str, state: str) -> list[str]:
"""Press or release one keysym by name. Returns what is still held.
A *name*, not a code: the driver owns the keymap, so it is the only
thing that can say which keycode ``z`` is on the uploaded layout. No
``frame`` follows, because ``zwp_virtual_keyboard_v1`` has none.
"""
reply = self.request({"op": "key", "key": key, "state": state})
return _string_list(reply.get("keys"), "key")
def type_text(self, text: str) -> list[str]:
"""Type a whole string. Returns the keys still explicitly held.
One request for the whole string, not one per character, and that is
load-bearing in two directions: the driver validates the string before
emitting anything, so an unmappable character types no prefix; and the
broker refreshes the lease once, which is what makes a long ``type``
a single gesture rather than a thousand.
"""
reply = self.request({"op": "type", "text": text})
return _string_list(reply.get("keys"), "type")
def pressed(self) -> list[str]:
"""What the *driver* believes is down.
@@ -110,11 +152,28 @@ class PointerDriver:
reply = self.request({"op": "pressed"})
return _string_list(reply.get("buttons"), "pressed")
def release_all(self) -> list[str]:
"""Lift everything, returning what came up. Called on expiry."""
def keys_pressed(self) -> list[str]:
"""Keysym names the *driver* believes are down. Same rule as above."""
reply = self.request({"op": "pressed"})
return _string_list(reply.get("keys"), "pressed keys")
def release_all(self) -> tuple[list[str], list[str]]:
"""Lift everything, returning ``(buttons, keys)``. Called on expiry.
One call for both, because there is one ``release_all`` op and one
expiry call site. A second op for keys would be a second thing to
forget, and the thing it would be forgotten in is the path that runs
when nobody is watching.
"""
reply = self.request({"op": "release_all"})
return _string_list(reply.get("lifted"), "release_all")
return (
_string_list(reply.get("lifted"), "release_all"),
# Absent from an older driver's reply, and `[]` is the right answer
# for one: it cannot have had a key down.
_string_list(reply.get("lifted_keys") or [], "release_all keys"),
)
# -- plumbing ---------------------------------------------------------
@@ -156,7 +215,11 @@ class PointerDriver:
if not isinstance(reply, dict):
raise ValueError(f"reply is not an object: {type(reply).__name__}")
if not reply.get("ok"):
raise DriverRejected(str(reply.get("error") or "the driver refused the request"))
kind = reply.get("kind")
raise DriverRejected(
str(reply.get("error") or "the driver refused the request"),
kind=kind if isinstance(kind, str) else None,
)
return reply
def _connect(self):
@@ -208,14 +271,14 @@ class PointerDriver:
def _string_list(value: Any, what: str) -> list[str]:
"""A list of button names, or a malformed reply — never a silent ``[]``.
"""A list of names, or a malformed reply — never a silent ``[]``.
An empty list is a real answer ("nothing was down"); anything that is not a
list of strings means the broker and the driver disagree about the
protocol, and treating that as "nothing was down" is how a button stays
pressed forever.
pressed forever and a key stays dead.
"""
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
raise DriverUnavailable(f"{what}: expected a list of button names, got {value!r}")
raise DriverUnavailable(f"{what}: expected a list of names, got {value!r}")
return list(value)
+257 -13
View File
@@ -117,6 +117,19 @@ POINTER_SWEEP_S = 1.0
DEFAULT_CONTAINER_BASE = 1000
DEFAULT_CONTAINER_SLOTS = 4
#: The driver's token for "this is the caller's mistake, not the compositor's"
#: (``hhstream_pointer.ops.KIND_INVALID``). Mirrored rather than imported: the
#: broker does not depend on the driver package -- they are separate processes
#: and separate installs -- which is the same reason ``hhstream_pointer`` keeps
#: its own copy of the exit codes.
DRIVER_KIND_INVALID = "invalid_argument"
#: The longest ``keyboard.type``, in Unicode **scalars**. Mirrors
#: ``hhstream_pointer.keymap.MAX_TEXT_SCALARS``; checked in both places because
#: only a check here produces exit 2, and only the check there protects a
#: driver run by hand.
MAX_TYPE_SCALARS = 4096
#: Clicks per ``pointer.click``. Bounded because a count comes off the wire
#: and "click 10000 times" is not a gesture.
MAX_CLICK_COUNT = 3
@@ -1591,6 +1604,12 @@ class SessionManager:
or one belonging to an output this session no longer has — the cursor
goes to the container's centre, which is the only other defensible
place.
**Acquire takes the keyboard as well as the cursor.** There is no
separate verb and no flag for it: a lease that aimed the pointer at one
window while the keys went to another would be a lease that cannot be
used to type, and finding that out costs a keystroke in someone else's
window. :meth:`_warp_taking_focus` is how, and why it is two motions.
"""
session = self._require_live(session_id)
@@ -1617,7 +1636,7 @@ class SessionManager:
bookmark = self._restore_point(session, output) if restore else None
x, y = (bookmark["x"], bookmark["y"]) if bookmark else (0.5, 0.5)
try:
await self._warp(output, x, y)
focus = await self._warp_taking_focus(session, output, x, y)
except ManagerError:
# Never hold a lease we could not aim: the next verb would move a
# cursor that is somewhere else entirely.
@@ -1631,12 +1650,17 @@ class SessionManager:
output=output,
restored=bool(bookmark),
ttl_s=self.pointer.ttl_s,
# Which mechanism took keyboard focus, so a session that ends up
# typing into the wrong window can be told apart from one that
# never tried. See `_warp_taking_focus`.
focus=focus,
)
return {
"id": session.id,
"lease_id": lease_id,
"bookmark": mark,
"expires_in_s": self.pointer.ttl_s,
"focus": focus,
}
async def pointer_move(
@@ -1782,7 +1806,7 @@ class SessionManager:
with contextlib.suppress(LeaseInvalid):
self.pointer.mark(session.id, lease_id, mark)
try:
lifted = await self._release_all_buttons()
lifted, lifted_keys = await self._release_all_buttons()
except ManagerError:
# The driver is gone, so the cursor's state is unknown — and
# holding a lease over an unknown cursor helps nobody. Drop it
@@ -1800,6 +1824,7 @@ class SessionManager:
session=session.id,
reason=outcome.reason,
buttons_lifted=lifted,
keys_lifted=lifted_keys,
)
return {
"id": session.id,
@@ -1807,6 +1832,9 @@ class SessionManager:
"released_by": "lease",
"released_at": released_at,
"buttons_lifted": lifted,
# Beside `buttons_lifted` and nowhere richer: the release body
# reports what came up, and keys are another thing that came up.
"keys_lifted": lifted_keys,
}
def pointer_state(self) -> dict[str, Any]:
@@ -1818,10 +1846,87 @@ class SessionManager:
return {
**state,
"buttons": self.pointer.pressed(),
# Names, not evdev codes: the whole surface speaks keysym names,
# and a number here would be the one place it did not.
"keys": self.pointer.keys_pressed(),
"bookmark": None if session is None else (session.pointer or {}).get("bookmark"),
"driver": None if self.config.pointer_socket is None else str(self.config.pointer_socket),
}
# ------------------------------------------------------------------
# the keyboard, on the same lease
# ------------------------------------------------------------------
#
# No `keyboard.acquire`, and that is not a simplification: there is one
# `wl_seat` and one keyboard focus, and `follow_mouse = 1` means another
# session's warp retargets the keys. Two leases would let session B move
# the pointer while session A believed it was typing into its own window.
#
# Both verbs go through `_refresh` -- live session, holder, not expired,
# container output required -- so they refresh the TTL and, like every
# `pointer.*` verb, do **not** count as activity. A session being typed
# into is still a session nobody has said they want kept.
async def keyboard_key(
self, session_id: str, lease_id: str, key: Any, state: Any
) -> dict[str, Any]:
"""Hold or release one keysym by name.
The driver first, then the lease's mirror of it -- the
``pointer_button`` order, and for the same reason: a key the driver
refused must not be recorded as down. The reverse mistake is harmless,
because ``release_all`` lifts what the *driver* recorded and that is
the set the compositor saw.
"""
session, _output = await self._refresh(session_id, lease_id)
name = _keysym_name(key)
if state not in ("down", "up"):
raise ManagerError(
"invalid_argument", f"key state must be 'down' or 'up', got {state!r}"
)
await self._drive("key", name, state)
if state == "down":
self.pointer.press_key(session.id, name)
else:
self.pointer.unpress_key(session.id, name)
# The name and the state, which is all there is: a keysym name is not
# a secret the way typed text is.
self.audit.emit("keyboard_key", session=session.id, key=name, state=state)
return {"id": session.id, "keys": self.pointer.keys_pressed()}
async def keyboard_type(
self, session_id: str, lease_id: str, text: Any
) -> dict[str, Any]:
"""Type a string. One driver request, one lease refresh.
The cap and the type check happen **here**, before the driver is
called, because the broker raising ``invalid_argument`` is the only
thing that produces exit 2: a driver refusal arrives as
``driver_refused`` unless it carries the token ``_drive`` looks for.
Nothing of the string is recorded. The audit event carries a count,
because a typed string is a password as often as not and
``events.jsonl`` is the wrong place for one.
"""
session, _output = await self._refresh(session_id, lease_id)
if not isinstance(text, str):
raise ManagerError("invalid_argument", f"text must be a string, got {text!r}")
if len(text) > MAX_TYPE_SCALARS:
# Unicode scalars, not bytes: a byte cap would refuse a string the
# caller counted as short, and the two only agree on ASCII.
raise ManagerError(
"invalid_argument",
f"text is {len(text)} scalars, over the {MAX_TYPE_SCALARS} limit",
)
await self._drive("type_text", text)
# `type` leaves no letter down; what comes back is whatever was
# explicitly held before it, so the mirror is re-read rather than
# assumed unchanged.
self.audit.emit("keyboard_type", session=session.id, chars=len(text))
return {"id": session.id, "chars": len(text), "keys": self.pointer.keys_pressed()}
# -- lease internals --------------------------------------------------
async def _sweep_pointer(self) -> None:
@@ -1855,22 +1960,31 @@ class SessionManager:
if holder is None:
return None
pressed = self.pointer.pressed()
# Read **before** `expire()`, and for the same reason `pressed()` is:
# `expire()` drops the lease and its key set with it, and the lease
# cannot lift anything itself (CONTRACT-sessions.md §3.3).
keys_held = self.pointer.keys_pressed()
info = self.pointer.expire()
if info is None:
return None
self._restore_default_ttl()
hard = self.clock.boottime() >= info.hard_deadline
lifted: list[str] = []
lifted_keys: list[str] = []
try:
lifted = await self._release_all_buttons()
lifted, lifted_keys = await self._release_all_buttons()
except ManagerError as exc:
# Loud: a button is down and we could not lift it. There is no
# Loud: something is down and we could not lift it. There is no
# caller to raise at, so the log and the audit trail are the alarm.
# A key is the worse half: 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.
log.error(
"pointer lease for %s expired with %s pressed and the driver "
"unreachable (%s): a button may still be down",
"pointer lease for %s expired with buttons %s and keys %s down and "
"the driver unreachable (%s): they may still be held",
holder,
pressed or "nothing",
pressed or "none",
keys_held or "none",
exc.reason,
)
session = self.registry.get(holder)
@@ -1882,15 +1996,23 @@ class SessionManager:
lease_id=info.lease_id,
hard_cap=hard,
pressed=pressed,
keys_pressed=keys_held,
buttons_lifted=lifted,
keys_lifted=lifted_keys,
)
log.warning(
"pointer lease for %s expired (%s); lifted %s",
"pointer lease for %s expired (%s); lifted buttons %s, keys %s",
holder,
"hard cap" if hard else "idle ttl",
lifted or "nothing",
lifted_keys or "nothing",
)
return {"session": holder, "lease_id": info.lease_id, "buttons_lifted": lifted}
return {
"session": holder,
"lease_id": info.lease_id,
"buttons_lifted": lifted,
"keys_lifted": lifted_keys,
}
async def _refresh(self, session_id: Any, lease_id: Any) -> tuple[Session, str]:
"""The gate every gesture verb goes through: live, holder, not expired."""
@@ -2044,6 +2166,14 @@ class SessionManager:
try:
return await asyncio.to_thread(getattr(driver, verb), *args)
except DriverRejected as exc:
# Two refusals arrive here and they are different exit codes. The
# driver says which with a token, because the alternative is the
# broker matching on English: `invalid_argument` is "that keysym is
# not on your layout" (exit 2, the caller's), and everything else
# is `driver_refused` (exit 10, the compositor's). An older driver
# sends no token and keeps the old behaviour.
if exc.kind == DRIVER_KIND_INVALID:
raise ManagerError("invalid_argument", str(exc)) from exc
raise ManagerError("driver_refused", f"the pointer driver refused {verb}: {exc}") from exc
except DriverUnavailable as exc:
raise ManagerError(
@@ -2055,11 +2185,92 @@ class SessionManager:
# Nothing the driver was sent reaches the compositor until a frame.
await self._drive("frame")
async def _release_all_buttons(self) -> list[str]:
"""Lift everything on the driver. The driver's set is the real one."""
async def _warp_taking_focus(
self, session: Session, output: str, x: float, y: float
) -> str:
"""Warp so this session's own window holds pointer **and** keyboard focus.
lifted = await self._drive("release_all")
return list(lifted)
**Two motions, deliberately.** One is not enough, and that is measured
rather than assumed (``tests/README-keyboard-probe.md``): Hyprland's
``onMouseWarp`` goes through ``mouseMoveUnified(refocus=false)``, which
*sets* ``m_mousePosDelta`` to 0 when the previous cursor movement was
more than 0.5 s ago, and keyboard focus is that delta compared against
``input:follow_mouse_threshold``. A single warp onto an idle cursor
therefore delivers ``wl_pointer.enter`` and no ``wl_keyboard.enter``:
the aimed window has the cursor and the *previously focused* window
still has the keys. The first key of the lease then lands there.
So: one motion to a neighbouring pixel, then one to the real target.
The second is within microseconds of the first, so the delta is the
distance between them, which is non-zero — and the threshold is 0
(set explicitly in ``nix/hyprland-conf.nix``, because this now depends
on it). The cursor finishes at the target, so the bookmark is
unchanged and nothing else here has to know this happened.
``mouseMoveUnified`` also returns *before* it touches the delta when
the floored pixel has not changed, which is why the nudge is a real
pixel away rather than a sub-pixel one, and why warping twice to the
same bookmark is not a substitute.
Returns how focus was taken, for the audit trail: ``"warp"``,
``"focuswindow"`` if the nudge could not be sent and the compositor's
own focus command stood in, or ``"none"`` if neither worked.
"""
method = "warp"
try:
await self._warp(output, x, _nudged(y))
except ManagerError as exc:
# The *target* warp below is still attempted and its failure is
# still fatal, as it was before this existed. Only the focus half
# degrades here, to the one IPC call the plan already named.
log.warning(
"could not send the focus nudge for %s (%s); falling back to "
"the compositor's own focus command",
session.id,
exc.reason,
)
method = "focuswindow" if self._focus_window(session) else "none"
await self._warp(output, x, y)
return method
def _focus_window(self, session: Session) -> bool:
"""``dispatch focuswindow`` at this session's window. Best effort.
The fallback, and not the primary, for the reason the plan gives: it is
a second mechanism for something the warp already does, it needs the
compositor's request socket to be up, and it names a window by an
address the broker only has if a read-back has happened. Failure is
logged rather than raised: an acquire that aimed the cursor correctly
is still useful, and the caller is told which mechanism ran.
"""
window = (session.container or {}).get("window") or {}
address = window.get("address")
selector = f"address:{address}" if address else None
if selector is None and session.pid:
selector = f"pid:{session.pid}"
if selector is None:
log.error("no window address or pid for %s; cannot focus it", session.id)
return False
try:
self.host.dispatch(["hyprctl", "dispatch", "focuswindow", selector])
except (CompositorUnavailable, ValueError) as exc:
log.error("could not focus %s (%s): keys may go elsewhere", session.id, exc)
return False
return True
async def _release_all_buttons(self) -> tuple[list[str], list[str]]:
"""Lift everything on the driver: ``(buttons, keys)``.
The driver's sets are the real ones -- they are what the compositor
saw -- and this is one call for both because the driver has one
``release_all`` op. A second call for keys would be a second thing to
forget in the path that runs when nobody is watching.
"""
lifted, lifted_keys = await self._drive("release_all")
return list(lifted), list(lifted_keys)
def logs(self, session_id: str, *, lines: int = 100, offset: int | None = None) -> dict[str, Any]:
"""The daemon's capture of the app's stdout/stderr.
@@ -2173,12 +2384,45 @@ def _clamp(value: float) -> float:
return min(1.0, max(0.0, value))
#: How far the focus nudge moves, as a fraction of the output. At the frozen
#: container mode of 1280x720 (CONTRACT-sessions.md §5) this is ~3 px
#: vertically, which is what makes the *floored* pixel change --
#: ``mouseMoveUnified`` returns before it touches the delta otherwise, so a
#: sub-pixel nudge would move the cursor and not the focus.
FOCUS_NUDGE = 0.004
def _nudged(value: float) -> float:
"""A coordinate one real pixel away from ``value``, still inside 0..1.
Away from whichever edge is closer, so aiming at a corner still produces a
pair of distinct positions rather than two clamped-identical ones.
"""
if value + FOCUS_NUDGE <= 1.0:
return value + FOCUS_NUDGE
return max(0.0, value - FOCUS_NUDGE)
def _button_name(value: Any) -> str:
if not isinstance(value, str) or not value:
raise ManagerError("invalid_argument", f"button must be a name, got {value!r}")
return value
def _keysym_name(value: Any) -> str:
"""A keysym name, checked only for shape.
Whether the layout *has* it is the driver's question -- it owns the keymap
-- and the driver answers an unknown one with a token that becomes exit 2.
This is the same division ``_button_name`` draws.
"""
if not isinstance(value, str) or not value:
raise ManagerError("invalid_argument", f"key must be a keysym name, got {value!r}")
return value
def _axis_name(value: Any) -> str:
if not isinstance(value, str) or not value:
raise ManagerError("invalid_argument", f"axis must be a name, got {value!r}")
+11
View File
@@ -151,6 +151,11 @@ VERBS = (
"pointer.scroll",
"pointer.release",
"pointer.state",
# Keyboard verbs are gestures on the *pointer* lease -- there is one seat
# and one keyboard focus, and `follow_mouse = 1` means another session's
# warp retargets the keys. So there is no `keyboard.acquire`.
"keyboard.key",
"keyboard.type",
)
#: Verbs whose reply is remembered by ``request_id``, so a caller that died
@@ -174,6 +179,12 @@ MUTATING_VERBS = frozenset(
"pointer.click",
"pointer.scroll",
"pointer.release",
# A retried `type` must not type twice, for exactly the reason a
# retried click must not click twice: it is the one failure an agent
# cannot undo. `pointer.state` stays out of this set -- it mutates
# nothing, and a cached one would be a stale one.
"keyboard.key",
"keyboard.type",
}
)
+29
View File
@@ -73,6 +73,8 @@ class ControlServer:
"pointer.scroll": self._op_pointer_scroll,
"pointer.release": self._op_pointer_release,
"pointer.state": self._op_pointer_state,
"keyboard.key": self._op_keyboard_key,
"keyboard.type": self._op_keyboard_type,
}
# ------------------------------------------------------------------
@@ -381,6 +383,33 @@ class ControlServer:
) -> dict[str, Any]:
return protocol.ok(**self.manager.pointer_state())
async def _op_keyboard_key(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.keyboard_key(
request.get("id"),
request.get("lease_id"),
request.get("key"),
request.get("state"),
)
)
async def _op_keyboard_type(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
# `text` is passed through untouched -- no default, no strip, no
# escape handling. A newline in the argument is a newline on the wire;
# the shell did the quoting and inventing an escape language here
# would mean `\n` could never be typed literally.
return protocol.ok(
**await self.manager.keyboard_type(
request.get("id"),
request.get("lease_id"),
request.get("text"),
)
)
async def _op_logs(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
return protocol.ok(
**self.manager.logs(
+222 -3
View File
@@ -16,6 +16,9 @@ exit 10 sends them to the wrong unit.
from __future__ import annotations
import os
from pathlib import Path
import pytest
from hhstream_pointer import __main__ as entry
@@ -139,6 +142,222 @@ def test_a_usable_layout_gets_as_far_as_the_compositor(no_compositor):
def test_the_exit_codes_match_the_brokers_table():
# Mirrored, not imported: the driver is a separate package on purpose
# (see the module docstring in __main__).
assert (entry.EXIT_OK, entry.EXIT_USAGE, entry.EXIT_COMPOSITOR) == (0, 2, 10)
"""Mirrored constants, compared against the table they mirror.
The driver keeps its own copies on purpose -- it is a separate package and
must not import the broker's internals -- so the two can drift, and
asserting the literals alone would not notice. This imports the broker's
enum to compare, which a test may do where the shipped driver may not.
"""
from hhstreamd.protocol import ExitCode
assert entry.EXIT_OK == ExitCode.OK
assert entry.EXIT_USAGE == ExitCode.USAGE
assert entry.EXIT_COMPOSITOR == ExitCode.COMPOSITOR
def test_the_module_passes_the_same_defaults_this_binary_has():
"""The drift this guards is silent: a unit and a hand-run binary that type
different characters, with nothing to compare them against but prose."""
module = Path(__file__).resolve().parents[2] / "nix/module.nix"
if not module.is_file():
pytest.skip("not running from a checkout")
text = module.read_text()
assert f'default = "{entry.DEFAULT_LAYOUT}";' in text
assert f'default = "{entry.DEFAULT_MODEL}";' in text
# And the unit really passes them, rather than relying on these defaults:
# a unit that relied on them would stop matching the contract's command
# line the moment either moved.
for flag in ("--xkb-layout", "--xkb-model", "--xkb-variant", "--xkb-options"):
assert f'"{flag}"' in text, f"{flag} is not on the unit's ExecStart"
# -- the keymap upload, which nothing else in the suite can see --------------
#
# The dispatcher tests record tuples from a sink, so they are blind to the
# Wayland `keymap` request: its format, its fd and its size never reach them.
# That is the review's finding 3 -- a `main` that connected and listened
# WITHOUT ever uploading passed every other test in this tree, and so did a
# backend that re-uploaded on every `type`.
#: One ordering log shared by the sink and the server stand-ins, because the
#: assertion is about the order of events *between* the two objects: an upload
#: after `listen` is a socket that promised a working device before it had one.
ORDER: list[str] = []
class _UploadingSink:
"""A sink whose connect succeeds, recording what it was asked to upload."""
def __init__(self, runtime_dir, display_name=None) -> None:
self.uploads: list[str] = []
self.connected = 0
_UploadingSink.last = self
def connect(self) -> None:
self.connected += 1
ORDER.append("connect")
def upload_keymap(self, text: str) -> None:
self.uploads.append(text)
ORDER.append("upload")
def has_keyboard(self) -> bool:
return True
def outputs(self) -> list[str]:
return []
def close(self) -> None:
pass
class _RecordingServer:
"""Stands in for `PointerServer`, so no socket is bound.
`serve_forever` raises, which is how the test gets control back at exactly
the point the real process would start answering requests -- and therefore
how it can assert the upload happened *before* that.
"""
class Served(Exception):
pass
def __init__(self, socket_path, handle, *, socket_mode=0o660) -> None:
self.events: list[str] = []
_RecordingServer.last = self
def listen(self) -> None:
self.events.append("listen")
ORDER.append("listen")
def serve_forever(self) -> None:
self.events.append("serve")
ORDER.append("serve")
raise _RecordingServer.Served
def close(self) -> None:
self.events.append("close")
@pytest.fixture
def uploading(monkeypatch):
ORDER.clear()
monkeypatch.setattr(entry, "WaylandSink", _UploadingSink)
monkeypatch.setattr(entry, "PointerServer", _RecordingServer)
return _UploadingSink
def test_the_keymap_is_uploaded_once_before_the_socket_listens(uploading):
"""The ordering rule, asserted rather than described.
`key` or `modifiers` before `keymap` is the protocol error `no_keymap`,
which kills the connection instead of returning something the broker could
report. So the upload has to happen between `connect` and `listen` -- a
listening socket is a promise that the device works.
"""
with pytest.raises(_RecordingServer.Served):
entry.main([])
sink = _UploadingSink.last
assert sink.connected == 1
assert len(sink.uploads) == 1, "uploaded once, not per request"
# The order across both objects, which is the whole assertion. A `main`
# that never uploaded, or uploaded after `listen`, fails here -- and before
# this test existed, both passed every other test in the tree.
assert ORDER == ["connect", "upload", "listen", "serve"]
def test_the_uploaded_text_is_the_keymap_for_the_flag(uploading):
with pytest.raises(_RecordingServer.Served):
entry.main(["--xkb-layout", "de"])
(text,) = _UploadingSink.last.uploads
assert text.lstrip().startswith("xkb_keymap {")
# The symbols name, which is what the VM check greps: a `de` layout that
# silently compiled as `us` would say `pc_us_inet(evdev)` here.
assert 'xkb_symbols "pc_de_inet(evdev)"' in text
def test_the_payload_is_nul_terminated_and_the_size_counts_the_nul():
"""The one value Hyprland reads off the end of the mapping if it is wrong.
It `mmap`s exactly `size` bytes and hands the pointer to
`xkb_keymap_new_from_string`, which wants a C string. A `size` of
`len(text)` therefore has no terminator inside the mapping. The symptom is
a keymap that will not compile, which from our side looks exactly like a
compositor that has no keyboard at all -- so this is asserted on the real
`WaylandSink.upload_keymap`, against a keyboard object that records the
request.
"""
pytest.importorskip("pywayland")
from hhstream_pointer import keymap as keymaps
from hhstream_pointer.backend import WaylandSink
class _Keyboard:
def __init__(self) -> None:
self.keymap_calls: list[tuple[int, bytes, int]] = []
self.modifier_calls: list[tuple] = []
def keymap(self, format_: int, fd: int, size: int) -> None:
# Read it back through the fd the compositor is handed, not through
# the string we started from: that is what the compositor sees.
with os.fdopen(os.dup(fd), "rb", closefd=True) as handle:
handle.seek(0)
self.keymap_calls.append((format_, handle.read(size), size))
def modifiers(self, *args) -> None:
self.modifier_calls.append(args)
class _Manager:
def __init__(self, keyboard) -> None:
self.keyboard = keyboard
def create_virtual_keyboard(self, seat):
return self.keyboard
keyboard = _Keyboard()
sink = WaylandSink(Path("/nonexistent"))
sink._keyboard_manager = _Manager(keyboard)
sink._display = _NullDisplay()
text = keymaps.build(layout="us").text()
sink.upload_keymap(text)
(format_, payload, size) = keyboard.keymap_calls[0]
assert format_ == keymaps.XKB_V1 == 1
assert payload.endswith(b"\0"), "no terminator inside the mapping"
assert payload.count(b"\0") == 1, "one terminator, not two"
assert size == len(text.encode("utf-8")) + 1
assert payload[:-1].decode("utf-8") == text
# And the mask is zeroed straight afterwards, because `destroy` of a
# previous driver's keyboard cleared no mask and a client keeps the last
# one it was sent.
assert keyboard.modifier_calls == [(0, 0, 0, 0)]
assert sink.has_keyboard() is True
def test_a_compositor_with_no_keyboard_manager_uploads_nothing_and_still_works():
pytest.importorskip("pywayland")
from hhstream_pointer.backend import WaylandSink
sink = WaylandSink(Path("/nonexistent"))
sink._display = _NullDisplay()
# No `_keyboard_manager`: the global was never advertised.
sink.upload_keymap("xkb_keymap {};")
assert sink.has_keyboard() is False
class _NullDisplay:
"""Enough of `pywayland.client.Display` for the two calls upload makes."""
def roundtrip(self) -> None:
pass
def flush(self) -> None:
pass
+44 -6
View File
@@ -95,6 +95,20 @@ def test_the_two_allowed_control_characters_are_named_keys(us, character, code):
assert action.mask == 0
def test_a_carriage_return_is_refused_rather_than_aliased_to_return(us):
"""Only `\n` and `\t` are exempt from the C0 rule.
A `\r` silently typed as Return means a caller who pasted CRLF gets two
newlines per line and no way to find out, so it is refused with the rest
of the C0 block.
"""
with pytest.raises(keymaps.UnknownKey) as caught:
us.resolve_text("\r")
assert "scalar 0" in str(caught.value)
assert "U+000D" in str(caught.value)
def test_an_empty_string_is_no_actions_and_not_an_error(us):
assert us.resolve_text("") == []
@@ -132,6 +146,18 @@ def test_an_unknown_keysym_name_is_refused(us):
us.resolve_name("NoSuchKeysymAtAll")
def test_an_empty_layout_is_refused_rather_than_compiled_as_us():
"""xkbcommon compiles `""` as the *same keymap as `us`*.
So `--xkb-layout ''` would look configured, type `us`, and never say
otherwise -- the same class of silent-wrong-layout as the comma below.
"""
with pytest.raises(keymaps.KeymapError) as caught:
keymaps.build(layout="")
assert "layout" in str(caught.value)
def test_a_comma_separated_layout_is_refused_before_anything_is_compiled():
# xkbcommon accepts `us,ru` happily and hands back a two-group keymap. v1
# always sends group 0, so the second group would be silently unreachable:
@@ -191,8 +217,18 @@ def test_a_lock_is_not_a_modifier(us):
assert us.modifier_mask(name) == 0
def test_control_contributes_a_mask_that_is_not_shifts(us):
assert us.modifier_mask("Control_L") not in (0, shift_mask(us))
def test_control_contributes_the_bit_the_keymap_gives_control(us):
"""The *right* bit, not merely a different one from Shift's.
"not 0 and not Shift" is satisfied by Alt's bit, and every wire assertion
compares against `modifier_mask(...)` -- so a consistently wrong bit would
be consistently wrong and green. This asks the keymap for the index.
"""
expected = 1 << us._keymap.mod_get_index("Control")
assert us.modifier_mask("Control_L") == expected
assert us.modifier_mask("Control_R") == expected
assert expected not in (0, shift_mask(us))
# -- a second layout, which is what stops a Shift special case ---------------
@@ -227,10 +263,12 @@ def test_a_character_us_cannot_type_is_ordinary_on_de(us, de):
def test_the_keymap_text_is_an_xkb_keymap_naming_its_layout(us, de):
assert us.text().lstrip().startswith("xkb_keymap {")
# The symbols section names the layout, which is what the VM check greps to
# prove the keymap a client decoded with is the one we uploaded.
assert "us" in _symbols_line(us)
assert "de" in _symbols_line(de)
# The exact symbols names, not `"us" in ...` -- which is true of every
# us-family map and would stay true of a `de` keymap that had silently
# compiled as `us`. These are also the strings the VM check should grep,
# so they are written down once here.
assert 'xkb_symbols "pc_us_inet(evdev)"' in _symbols_line(us)
assert 'xkb_symbols "pc_de_inet(evdev)"' in _symbols_line(de)
def _symbols_line(keymap: keymaps.Keymap) -> str:
+120 -3
View File
@@ -507,6 +507,109 @@ def test_an_ordinary_key_down_sends_no_mask(driver, sink):
assert sink.calls == [("key", KEY_A, DOWN)]
def test_key_of_a_capital_sends_the_mask_the_symbol_needs(driver, sink, us):
"""`keyboard key A` must type `A`, not `a`.
The bug this locks: `key` resolved the action and then used only its
`code`, so a keysym above level 0 went on the wire as a bare keypress and
the window received the level-0 character. `A` typed `a`; on `de`, `at`
lost its level-three mask and typed `q`. `type` was the only path that used
the mask, so every `type` test stayed green.
"""
assert driver.handle({"op": "key", "key": "A", "state": "down"})["keys"] == ["A"]
assert sink.calls == [
# Mask first, exactly as `type` does it: a client that decodes with the
# mask from the last `wl_keyboard.modifiers` emits `a` otherwise.
("modifiers", us.modifier_mask("Shift_L"), 0, 0, 0),
("key", KEY_A, DOWN),
]
# And still no Shift keycode.
assert not any(c[0] == "key" and c[1] == KEY_LEFTSHIFT for c in sink.calls)
def test_the_up_of_a_capital_restores_the_baseline(driver, sink, us):
driver.handle({"op": "key", "key": "A", "state": "down"})
sink.calls.clear()
driver.handle({"op": "key", "key": "A", "state": "up"})
assert sink.calls == [("key", KEY_A, UP), ("modifiers", 0, 0, 0, 0)]
assert driver.handle({"op": "pressed"})["keys"] == []
def test_a_capital_is_not_treated_as_a_held_modifier(driver, sink):
"""`A` held is a held *letter*, so `type` must refuse under it.
The distinction is why the held record stores what a key *contributes*
rather than what it needs: storing `A`'s Shift requirement there would make
a held capital look like a held modifier, and `type` would carry on and OR
a Shift it did not ask for into every character.
"""
driver.handle({"op": "key", "key": "A", "state": "down"})
sink.calls.clear()
reply = driver.handle({"op": "type", "text": "b"})
assert reply["ok"] is False
assert reply["kind"] == KIND_INVALID
assert sink.calls == []
def test_two_names_for_one_keycode_cannot_both_be_held(driver, sink):
"""`A` and `a` are the same keycode at two levels.
Holding both sent `key(30, pressed)` twice. Hyprland drops the second
because the code is already in its `m_pressed`, then `release_all` sends
two ups of which one is also dropped -- so nothing visibly breaks and the
held set is a lie for as long as the lease lasts. A refusal is better.
"""
driver.handle({"op": "key", "key": "A", "state": "down"})
sink.calls.clear()
reply = driver.handle({"op": "key", "key": "a", "state": "down"})
assert reply["ok"] is False
assert reply["kind"] == KIND_INVALID
assert "same key" in reply["error"]
assert sink.calls == []
assert driver.handle({"op": "pressed"})["keys"] == ["A"]
def test_the_same_name_down_twice_is_still_one_key(driver):
"""Not a clash with itself: a repeated `down` is idempotent, as for buttons."""
driver.handle({"op": "key", "key": "a", "state": "down"})
assert driver.handle({"op": "key", "key": "a", "state": "down"})["ok"] is True
assert driver.handle({"op": "pressed"})["keys"] == ["a"]
def test_a_key_is_only_forgotten_after_the_up_reaches_the_sink(us):
"""Order matters here for the same reason it does for `button`.
If the name were dropped before the send, a raise from the sink would leave
us believing the key is up while the compositor still has it down -- and
`release_all` would not try again, because the set is empty.
"""
class _Breaking(RecordingSink):
def key(self, code, state):
if state == UP:
raise RuntimeError("the keyboard went away")
super().key(code, state)
driver = Dispatcher(_Breaking(), us)
driver.handle({"op": "key", "key": "Shift_L", "state": "down"})
with pytest.raises(RuntimeError):
driver.handle({"op": "key", "key": "Shift_L", "state": "up"})
# Still held, so the next `release_all` will try the up again.
assert driver.handle({"op": "pressed"})["keys"] == ["Shift_L"]
# -- type -------------------------------------------------------------------
@@ -574,8 +677,17 @@ def test_type_of_a_capital_under_a_held_control_ors_both_masks(driver, sink, us)
driver.handle({"op": "type", "text": "A"})
both = us.modifier_mask("Control_L") | us.modifier_mask("Shift_L")
assert sink.calls[0] == ("modifiers", both, 0, 0, 0)
assert sink.calls[-1] == ("modifiers", us.modifier_mask("Control_L"), 0, 0, 0)
# The whole sequence, not just the two masks: `modifiers(both)` followed by
# `modifiers(control)` with no key events in between would satisfy a
# first-and-last assertion while typing nothing at all.
assert sink.calls == [
("modifiers", both, 0, 0, 0),
("key", KEY_A, DOWN),
("key", KEY_A, UP),
("modifiers", us.modifier_mask("Control_L"), 0, 0, 0),
]
# And no second Control down, and no Shift keycode.
assert not any(c[0] == "key" and c[1] in (KEY_LEFTCTRL, KEY_LEFTSHIFT) for c in sink.calls)
def test_type_while_a_non_modifier_is_held_emits_nothing(driver, sink):
@@ -601,13 +713,18 @@ def test_type_while_a_lock_is_held_is_refused_too(driver, sink):
driver.handle({"op": "key", "key": "Caps_Lock", "state": "down"})
sink.calls.clear()
assert driver.handle({"op": "type", "text": "a"})["ok"] is False
reply = driver.handle({"op": "type", "text": "a"})
assert reply["ok"] is False
# The caller's mistake, so exit 2 -- not `refused`, which would report a
# held Caps_Lock as a compositor failure.
assert reply["kind"] == KIND_INVALID
assert sink.calls == []
def test_a_string_that_fails_on_its_third_character_emits_nothing(driver, sink):
reply = driver.handle({"op": "type", "text": "abé"})
assert reply["ok"] is False
assert reply["kind"] == KIND_INVALID
# Not "no event carried é" -- that would also pass with a and b typed.
assert sink.calls == []
+56 -4
View File
@@ -22,6 +22,12 @@ What they prove and what they do not:
recorder. So the protocol, the framing, the driver's own button bookkeeping
and — importantly — which backend failures become ``ok: false`` and which
kill the connection are the shipped ones; only the compositor is absent.
The **keymap is real too**, a compiled ``us`` layout rather than a stub,
because what these tests assert about the keyboard is which evdev code and
which modifier mask went on the wire — and a stub would answer whatever the
test expected. ``keyboard=False`` builds a driver with no keyboard at all,
which is the compositor-has-no-global case.
"""
from __future__ import annotations
@@ -34,10 +40,36 @@ from typing import Any
import pytest
from hhstream_pointer import keymap as keymaps
from hhstream_pointer.__main__ import _handler
from hhstream_pointer.ops import Dispatcher
from hhstream_pointer.server import PointerServer
#: evdev codes the keyboard tests name. From ``linux/input-event-codes.h``,
#: and the values that cross the Wayland request -- never XKB keycodes, which
#: are 8 higher and never leave the driver.
KEY_A = 30
KEY_LEFTSHIFT = 42
KEY_LEFTCTRL = 29
_us_keymap: keymaps.Keymap | None = None
def us_keymap() -> keymaps.Keymap:
"""One compiled ``us`` keymap, shared.
Compiling is the slow part (xkbcommon reads the rules files), and the
object is immutable once built -- it is a lookup table plus the keymap text
-- so one per process is right. Shared deliberately rather than per-fixture
for the same reason the driver builds it once at start-up: a *second*
keymap in a process would be a second answer to "which code is `z`".
"""
global _us_keymap
if _us_keymap is None:
_us_keymap = keymaps.build(layout="us")
return _us_keymap
#: Linux's sun_path is 108 bytes including the NUL.
SUN_PATH_MAX = 107
@@ -390,8 +422,11 @@ class FakeCompositor:
class RecordingSink:
"""A :class:`hhstream_pointer.ops.PointerSink` that writes nothing anywhere."""
def __init__(self) -> None:
def __init__(self, *, keyboard: bool = True) -> None:
self.calls: list[tuple] = []
#: Whether a virtual keyboard was created at start-up. False is the
#: compositor-with-no-global case, which must leave the cursor working.
self.keyboard = keyboard
#: An exception to raise from the next call. The shipped driver
#: answers an ``OutputUnknown`` on the wire and lets anything else
#: take the connection down, so which one is raised here decides which
@@ -414,6 +449,23 @@ class RecordingSink:
self._check()
self.calls.append(("frame", output))
# -- the keyboard half -------------------------------------------------
#
# No output on either of these, and that is the assertion as much as the
# recording: a virtual keyboard is seat-global, so a sink that accepted an
# output would let a per-output implementation look correct.
def has_keyboard(self) -> bool:
return self.keyboard
def key(self, code: int, state: int) -> None:
self._check()
self.calls.append(("key", code, state))
def modifiers(self, depressed: int, latched: int, locked: int, group: int) -> None:
self._check()
self.calls.append(("modifiers", depressed, latched, locked, group))
def _check(self) -> None:
if self.fail is not None:
raise self.fail
@@ -433,11 +485,11 @@ class FakeDriver:
everything a test is actually asserting about still runs the real code.
"""
def __init__(self, socket_path: Path) -> None:
def __init__(self, socket_path: Path, *, keyboard: bool = True) -> None:
check_path(Path(socket_path))
self.socket_path = Path(socket_path)
self.sink = RecordingSink()
self.dispatcher = Dispatcher(self.sink)
self.sink = RecordingSink(keyboard=keyboard)
self.dispatcher = Dispatcher(self.sink, us_keymap() if keyboard else None)
self.server = PointerServer(self.socket_path, _handler(self.dispatcher))
self.server.listen()
self.connections: list[socket.socket] = []
@@ -172,6 +172,30 @@ def test_every_pointer_verb_that_moves_something_is_cached():
assert "container.list" not in protocol.MUTATING_VERBS
def test_every_keyboard_verb_is_cached_for_the_same_reason():
"""A retried `type` that typed twice is also unrecoverable.
And `pointer.state`, which now reports held keys, stays out of the set: it
mutates nothing, and a cached one would be a stale one.
"""
assert {"keyboard.key", "keyboard.type"} <= protocol.MUTATING_VERBS
assert {"keyboard.key", "keyboard.type"} <= set(protocol.VERBS)
assert "pointer.state" not in protocol.MUTATING_VERBS
def test_there_is_no_keyboard_acquire_verb():
"""One seat, one keyboard focus, one lease.
A `keyboard.acquire` would let session B warp the pointer while session A
believed it was typing into its own window, because `follow_mouse = 1`
means a warp retargets the keys.
"""
assert not any(verb.startswith("keyboard.acquire") for verb in protocol.VERBS)
assert "keyboard.release" not in protocol.VERBS
def test_every_verb_the_protocol_names_is_one_the_daemon_answers():
"""One list, so a verb cannot be added to the dispatcher alone.
+70
View File
@@ -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"])
+6 -3
View File
@@ -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)
+663
View File
@@ -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"
+29 -2
View File
@@ -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