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

+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(