From 6b395305e0657e1c7bc1101e7ff7d7c17e4cf531 Mon Sep 17 00:00:00 2001 From: Hermenix Date: Sat, 3 Oct 2026 19:05:39 +0000 Subject: [PATCH] scroll: one verb, two axes, and the sign carries the direction A session could move a cursor and press it, but not scroll. The protocol already had the request -- zwlr_virtual_pointer_v1.axis(time, axis, value) -- it had simply never been implemented, in the driver or the broker. hhstream session pointer scroll --axis vertical --amount 3 Positive is down (vertical) or right (horizontal): the protocol's direction, not a choice of ours, which is why direction travels in the sign and there is deliberately no up/down vocabulary layered over it. The output is whatever the last warp aimed at, exactly like a button, so scrolling somewhere else is a warp first -- and the lease is what keeps the whole gesture atomic. Bounded at 100 wheel clicks per request on both sides, because a decimal-point slip should be a refusal rather than a session scrolled somewhere unrecoverable. The resume point is re-stamped, not moved: the cursor did not go anywhere, so the coordinates are re-affirmed and only the stamp advances. Recorded in the contract as an amendment to the frozen op set, because adding an op to a frozen interface should be visible rather than implied. Co-authored-by: Claude Opus 5 --- docs/CONTRACT-sessions.md | 13 +++ docs/TODO/README.md | 24 ++++ docs/TODO/containers-do-not-bind.md | 54 +++++++++ docs/TODO/cursor-visibility-in-captures.md | 53 +++++++++ .../reconcile-while-containers-are-off.md | 48 ++++++++ docs/TODO/scroll-has-no-compositor-proof.md | 50 +++++++++ src/hhstream_pointer/backend.py | 4 + src/hhstream_pointer/buttons.py | 23 ++++ src/hhstream_pointer/ops.py | 39 +++++++ src/hhstream_session/__init__.py | 54 +++++++++ src/hhstreamd/driver.py | 11 ++ src/hhstreamd/manager.py | 73 ++++++++++++ src/hhstreamd/protocol.py | 2 + src/hhstreamd/server.py | 13 +++ tests/pointer/test_ops.py | 75 ++++++++++++- tests/sessions/fakes.py | 4 + tests/sessions/unit/test_pointer_verbs.py | 104 ++++++++++++++++++ 17 files changed, 642 insertions(+), 2 deletions(-) create mode 100644 docs/TODO/README.md create mode 100644 docs/TODO/containers-do-not-bind.md create mode 100644 docs/TODO/cursor-visibility-in-captures.md create mode 100644 docs/TODO/reconcile-while-containers-are-off.md create mode 100644 docs/TODO/scroll-has-no-compositor-proof.md diff --git a/docs/CONTRACT-sessions.md b/docs/CONTRACT-sessions.md index ff7e2e8..e470260 100644 --- a/docs/CONTRACT-sessions.md +++ b/docs/CONTRACT-sessions.md @@ -278,11 +278,24 @@ blocked driver must not stall the broker. ```json {"op": "warp", "output": "hh-x", "x": 0.42, "y": 0.61} -> {"ok": true} {"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"]} ``` +**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, +and the reason there is no `up`/`down` vocabulary layered over it. The output is +whatever the last `warp` aimed at, exactly like `button`, so scrolling somewhere +else is a warp first — which is what keeps the whole gesture atomic under the +lease. The magnitude is bounded at 100 wheel clicks per request, in both the +driver and the broker, because a decimal-point slip should be a refusal rather +than a session scrolled somewhere unrecoverable. Unit tests cover validation and +the lease; a real-compositor case is still missing — see +`docs/TODO/scroll-has-no-compositor-proof.md`. + `{"ok": false, "error": ""}` for anything rejected. The driver holds **no lease state** — the broker owns the lease; the driver is an executor that must never be trusted to serialise anything. diff --git a/docs/TODO/README.md b/docs/TODO/README.md new file mode 100644 index 0000000..233a7c4 --- /dev/null +++ b/docs/TODO/README.md @@ -0,0 +1,24 @@ +# TODO + +Known, unfixed problems — each one real, none of them guessed at. + +Each file answers three questions and stops: + +- **The issue** — what is actually wrong, with the evidence for it. +- **Ideas** — more than one, and which one is the recommended route. +- **Why it matters** — the impact, not the principle. + +| item | severity | state | +| --- | --- | --- | +| [containers-do-not-bind](containers-do-not-bind.md) | high | containers built, tested, **switched off** in production | +| [scroll-has-no-compositor-proof](scroll-has-no-compositor-proof.md) | medium | implemented; unit-tested; unproven against a real compositor | +| [cursor-visibility-in-captures](cursor-visibility-in-captures.md) | medium | unverified — the acceptance video shows no cursor | +| [reconcile-while-containers-are-off](reconcile-while-containers-are-off.md) | medium | worked around by restarting the compositor | + +Severity here means "how much of the feature is actually delivered", not +"how loud the failure is". The high one is high because a working feature is +turned off; the others are medium because they are gaps in proof, where the +symptom of a real fault and the symptom of a working thing look identical. + +When one of these is fixed, delete its file and the row — this folder is a list +of what is still true, not a history of what was thought. diff --git a/docs/TODO/containers-do-not-bind.md b/docs/TODO/containers-do-not-bind.md new file mode 100644 index 0000000..45e81f5 --- /dev/null +++ b/docs/TODO/containers-do-not-bind.md @@ -0,0 +1,54 @@ +# Containers are built, tested, and switched off + +## The issue + +A session can be given its own container — its own headless output and a +numbered workspace — but **no window can be assigned to it**. + +The broker stamps an identity on each session's app and matches a windowrule on +`match:initial_class`, on the assumption that an allowlisted app will carry that +stamp. None of them does: chromium reaches the compositor through a wrapper +script whose flags do not set a per-session class, and `foot` has no such +option. Every allowlisted app therefore lands in the *base* class set, the +broker judges it foreign to every container, and quarantines it. + +The consequence is that enabling containers makes sessions unusable — which is +how this was found: not in tests, but live, immediately after the first switch +that enabled them. Containers are now off +(`containers_enabled = false`), and every session reports +`container: {state: "degraded", output: null}`, deliberately, so a disabled +machine cannot be mistaken for one whose compositor is down. + +## Ideas + +1. **Adopt windows by the pid the compositor already reports.** *(recommended)* + `hyprctl clients -j` gives each client's pid, and the broker already knows each + session's pid — so the join is a lookup, and **no app has to take part**. No + stamp, no per-app flags, and it works for programs that will never co-operate. + It must use `(pid, starttime)` rather than pid alone, because the wrapper + replaces its own argv and that is exactly the pid-reuse confusion already + fixed once in `procmon`. +2. **Per-app identity argument, where one exists.** chromium accepts + `--class=hh-`, so the wrapper could pass the session's value. Cheap for + chromium, and dead weight for every other app: it makes the allowlist a list of + apps that cooperate. +3. **Keep the stamp, set it in each wrapper.** Same shape as (2), more moving + parts, same ceiling. +4. **Hybrid: pid first, stamp as a fallback.** Only worth it if some app reports + no pid at all; the compositor's `-1` sentinel for "absent pid" already covers + the reporting side. + +## Why it matters + +The isolation milestone does not deliver while this is open. Sessions still +share one output and tile over each other on the same screen — two concurrent +sessions are both `ready` and both visible at once. Per-session ownership today +is bookkeeping only: a runtime directory, an idle clock, captured output, an +audit trail. + +So the difference between what the design claims ("a session owns a workspace") +and what the machine does ("a session is an app on a shared screen") is entirely +this one join. And note which failure mode to expect on the way: the *first* +half of the feature — creating outputs and workspaces — worked on the first +attempt and looked fine right up until an app was put in one. A green container +test proves the compositor accepted the commands, not that anything arrived. diff --git a/docs/TODO/cursor-visibility-in-captures.md b/docs/TODO/cursor-visibility-in-captures.md new file mode 100644 index 0000000..675167a --- /dev/null +++ b/docs/TODO/cursor-visibility-in-captures.md @@ -0,0 +1,53 @@ +# The cursor may not appear in captures at all + +## The issue + +The acceptance video shows the browser searching, opening listings in separate +tabs, and a terminal running cowsay — and **no cursor anywhere**. Two candidate +causes, and they are not exclusive: + +1. **The demo never moved it.** The browser beats were driven over Chromium's + CDP HTTP endpoints (`/json/new`, `/json/activate`, navigation), which inject + no pointer input at all. Nothing moved the cursor because nothing was asked + to. This part is a gap in the demo, not in the machine, and it is now + fixable: `pointer.move` warps the real cursor. +2. **A headless capture may not include the cursor image.** The compositor + normally draws the cursor as its own plane, on top of the scene, so a buffer + read back from the output can legitimately contain everything except the + pointer. Whether that is what happens here has **not been checked**. + +Which one it is decides the fix, so the first step is to find out rather than +pick. + +## Ideas + +1. **Check before changing anything.** *(recommended)* Start a session, warp the + pointer to a known point with `pointer.move`, take a `shot`, and look — + once with the pointer parked in a corner and once beside it. One comparison + separates the two causes. +2. **If the cursor is missing from the buffer, force software cursors** in the + compositor configuration (`cursor { no_hardware_cursors = true }`). That draws + the cursor into the scene, so it lands in the capture, at the cost of a redraw + per frame — the same cost this box already pays, since there is no GPU and + rendering is software anyway. Worth measuring rather than assuming. +3. **Verify motion without pixels, for tests.** `hyprctl cursorpos` answers on + this build, so a test can assert *where* the cursor is without any image at + all. That belongs in the gates; (2) is only for the human eye. +4. **Last resort: a synthetic marker** drawn by the driver. Honest only if it is + labelled as an overlay — it proves the driver thinks the cursor is at (x, y), + which is not the same claim as the compositor putting it there. + +## Why it matters + +The point of moving a pointer is to act somewhere visible. If the cursor cannot +be seen in the artifact the operator is shown, then the acceptance proof for all +input work is missing, and the failure it hides is specifically the one that +matters: **a click on the wrong element looks exactly like a click on the right +one.** Both produce a screen that changed; neither shows where it happened. + +There is a second-order cost too. Everything learned about the cursor — that the +compositor remembers no position per-device, that `motion_absolute` speaks +output-normalised coordinates, that a bookmark has to live in the session +record — was hard-won and is all invisible in a video with no cursor in it. The +operator cannot check any of it. That is a documentation problem the video was +supposed to solve. diff --git a/docs/TODO/reconcile-while-containers-are-off.md b/docs/TODO/reconcile-while-containers-are-off.md new file mode 100644 index 0000000..43fe67e --- /dev/null +++ b/docs/TODO/reconcile-while-containers-are-off.md @@ -0,0 +1,48 @@ +# Cleanup depends on the feature it is cleaning up after + +## The issue + +Start-up reconciliation for stray `hh-*` outputs lives inside the container +host, so it runs **only when containers are enabled**. Turning containers off +therefore also turned off the broker's ability to see what it had already left +on the compositor. + +That is not theoretical: an output created while the feature was on survived the +rollback switch. With containers off, nothing reconciled it, and the frame +capture stayed **2560×720 instead of 1280×720** — the extra width being the +orphan sitting beside the real one. The symptom is a *capture* problem, which is +where it would be looked for, and it was fixed by restarting the compositor, +which drops every session. + +## Ideas + +1. **Reconcile always, not conditionally.** *(recommended)* On start-up, list the + compositor's outputs, find `hh-*` ones that no live session owns, and remove + them — regardless of whether containers are enabled. "Disabled" should mean + *create none*, not *leave the machine as it was found*. +2. **Never start a session onto an unowned output.** If a leftover is found that + cannot be removed, refuse to place a session on it rather than silently + sharing it — the ambiguity is what makes the capture width unexplainable. +3. **Record removals in the audit trail.** The `hyprctl output remove` calls are + already logged individually; a reconcile pass that removes three outputs + should say so once, with the names, so a later "why is my screen narrower" + has an answer. +4. **Make it a check.** A VM case that creates a container, disables the feature, + and asserts the output is gone — the rollback path deserves the same gate as + the forward path, because it is the one that runs when something is already + wrong. + +## Why it matters + +A feature that cannot be turned off safely is worse than one that was never +turned on, and this one fails asymmetrically: the *forward* path is tested +(containers are created and torn down in `vm-sessions` and `vm-containers`), +while the *rollback* path was never exercised before it was needed. That is +precisely when it is used. + +It also cost a compositor restart — the bluntest tool available, and one that +kills every session — to clean up a state the broker itself had created and +could no longer see. The general rule worth keeping: **teardown code belongs +outside the thing being torn down**, or there will be exactly one configuration +where it does not run, and it will be the configuration you are in when you +need it. diff --git a/docs/TODO/scroll-has-no-compositor-proof.md b/docs/TODO/scroll-has-no-compositor-proof.md new file mode 100644 index 0000000..2b7d75c --- /dev/null +++ b/docs/TODO/scroll-has-no-compositor-proof.md @@ -0,0 +1,50 @@ +# Scrolling works, but nothing proves it against a real compositor + +## The issue + +`hhstream session pointer scroll --amount N` now exists end to end: CLI → +`pointer.scroll` → the lease check → driver `axis` op → +`zwlr_virtual_pointer_v1.axis(time, axis, value)` → `frame`. Validation is +covered by unit tests, and the lease behaviour matches the other gestures. + +What is **not** covered is the half that matters: no test scrolls a real +application on a real compositor. The `vm-pointer` gate has no axis case, and +the fake compositor can only prove the wiring — that the broker said the right +thing to the driver, not that a window moved. + +Also unproven, and worth knowing before trusting it: whether an app on a +**headless** output honours a bare `axis` event at all. GTK and Chromium +smooth-scrolling both look at `axis_source` and `axis_discrete`, which the +driver does not send today. If they are required, the symptom will be a scroll +that silently does nothing — indistinguishable from a page that would not move. + +## Ideas + +1. **An axis case in `vm-pointer` that reads the app's own state.** *(recommended)* + Scroll a real app and assert *its* state changed, not the pixels — the + contract already sets this bar for clicks ("verified by reading the app's own + state"). A `foot` running a script that appends a line on scroll, or a page + whose scroll offset the app can report, keeps the assertion honest. +2. **Send `axis_source` and `axis_discrete` alongside `axis`** if (1) shows the + event arriving and the app ignoring it. Small, confined to the driver's + `axis` op. +3. **Keep the direction convention in one place.** Positive vertical is down and + positive horizontal is right, per the protocol. It is documented in + `hhstream_pointer/buttons.py` and mirrored in the CLI's `AXES` — if a third + copy ever appears, that is the point to notice, because two vocabularies over + one sign is how a scroll ends up backwards. +4. **A live check on this machine, not only in a VM.** The video that prompted + this work is a real scroll on a real app; making that reproducible as a + command (like `examples/proof-video.py`) is worth as much as the VM case. + +## Why it matters + +An unimplemented feature is honest; a **plausible** one is not. A scroll that +does nothing, a scroll that goes the wrong way, and a scroll the app ignores all +present as "the page would not move", and all three would be found by a human +watching a video — which is not a test. + +This is the same shape as the bug that made `foot` exit 230 with every test +green: the tests exercised what was built, and the built thing was fine, and the +app exited anyway. Anything whose acceptance proof runs through a real window +needs a real window in the test. diff --git a/src/hhstream_pointer/backend.py b/src/hhstream_pointer/backend.py index c1fce8b..c82807d 100644 --- a/src/hhstream_pointer/backend.py +++ b/src/hhstream_pointer/backend.py @@ -193,6 +193,10 @@ class WaylandSink: self._pointer(output).button(_now_ms(), code, state) self._flush() + def axis(self, output: str, axis: int, value: float) -> None: + self._pointer(output).axis(_now_ms(), axis, value) + self._flush() + def frame(self, output: str) -> None: self._pointer(output).frame() self._flush() diff --git a/src/hhstream_pointer/buttons.py b/src/hhstream_pointer/buttons.py index 6dd5f99..d3f40c4 100644 --- a/src/hhstream_pointer/buttons.py +++ b/src/hhstream_pointer/buttons.py @@ -27,7 +27,30 @@ CODES: dict[str, int] = { #: ``wl_pointer.button_state``. Named on the wire so a log line reads. STATES: dict[str, int] = {"up": 0, "down": 1} +#: ``wl_pointer_axis`` values. Named "vertical"/"horizontal" rather than +#: up/down/left/right, because the sign is what carries the direction: the +#: protocol's positive vertical scroll is *down*, and a caller asking for +#: "down" while a negative value means down is how a scroll ends up backwards. +AXES: dict[str, int] = {"vertical": 0, "horizontal": 1} + +#: The largest scroll a single request may carry, in wheel clicks. Bounded so a +#: decimal-point slip (3 -> 30000) is a refusal rather than a session scrolled +#: into next week, where the only clue is that the page will not move back. +MAX_AXIS_VALUE = 100.0 + NAMES = tuple(CODES) +AXIS_NAMES = tuple(AXES) + + +def axis_for(name: str) -> int: + """The protocol axis for a name, or :class:`ValueError` naming the set.""" + + try: + return AXES[name] + except KeyError: + raise ValueError( + f"unknown axis {name!r} (known: {', '.join(AXIS_NAMES)})" + ) from None def code_for(name: str) -> int: diff --git a/src/hhstream_pointer/ops.py b/src/hhstream_pointer/ops.py index 03c6c6b..594a4c0 100644 --- a/src/hhstream_pointer/ops.py +++ b/src/hhstream_pointer/ops.py @@ -39,6 +39,13 @@ class PointerSink(Protocol): def button(self, output: str, code: int, state: int) -> None: """An evdev button code and a ``wl_pointer.button_state``.""" + def axis(self, output: str, axis: int, value: float) -> None: + """Scroll by ``value`` wheel clicks along ``axis`` (a ``wl_pointer_axis``). + + Positive vertical is *down* and positive horizontal is *right*, which is + the protocol's direction and not a choice of ours. + """ + def frame(self, output: str) -> None: """Commit the queued events. Nothing is delivered until this.""" @@ -107,6 +114,37 @@ class Dispatcher: self._pressed.pop(name, None) return {"ok": True} + def _op_axis(self, request: dict) -> dict[str, Any]: + """Scroll the aimed output. + + The output is implicit, like ``button``: there is one cursor, and a + scroll belongs to whatever it is currently over. A caller that wants to + scroll somewhere else warps first, which is also what makes the gesture + serialisable by the lease. + """ + + name = request.get("axis", "vertical") + if not isinstance(name, str): + raise Rejected("'axis' must be a string") + try: + code = buttons.axis_for(name) + except ValueError as exc: + raise Rejected(str(exc)) from None + + value = request.get("value", 1.0) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise Rejected("'value' must be a number of wheel clicks") + value = float(value) + if value != value or value in (float("inf"), float("-inf")): + raise Rejected("'value' must be finite") + if abs(value) > buttons.MAX_AXIS_VALUE: + raise Rejected( + f"'value' {value} exceeds the {buttons.MAX_AXIS_VALUE:g} wheel-click limit" + ) + + self._sink.axis(self._aimed(), code, value) + return {"ok": True} + def _op_frame(self, request: dict) -> dict[str, Any]: self._sink.frame(self._aimed()) return {"ok": True} @@ -131,6 +169,7 @@ class Dispatcher: _ops = { "warp": _op_warp, "button": _op_button, + "axis": _op_axis, "frame": _op_frame, "pressed": _op_pressed, "release_all": _op_release_all, diff --git a/src/hhstream_session/__init__.py b/src/hhstream_session/__init__.py index c6d3452..d4ae4c6 100644 --- a/src/hhstream_session/__init__.py +++ b/src/hhstream_session/__init__.py @@ -302,6 +302,14 @@ def _build_namespace(parser: argparse.ArgumentParser) -> None: #: and this list only buys a typo an exit 2 instead of an exit 10. BUTTONS = ("left", "right", "middle", "side", "extra", "forward", "back", "task") +#: Axis names the driver knows (``hhstream_pointer.buttons.AXES``), mirrored for +#: the same reason and with the same caveat: the driver remains the authority. +#: Direction is the sign of the amount, so there is deliberately no "down" or +#: "up" here -- the protocol fixes positive as down (vertical) and right +#: (horizontal), and a second vocabulary over it is how a scroll ends up +#: backwards. +AXES = ("vertical", "horizontal") + def _build_pointer(verbs: Any, common: argparse.ArgumentParser) -> None: """``session pointer `` — the one cursor, under a lease (PLAN §6). @@ -409,6 +417,29 @@ def _build_pointer(verbs: Any, common: argparse.ArgumentParser) -> None: "--button", default="left", choices=BUTTONS, metavar="B", help=_button_help() ) + scroll = with_lease(add_gesture( + "scroll", + _cmd_pointer_scroll, + help="scroll the session's screen where the cursor is", + description=( + "Scroll the session's screen. --amount is signed wheel clicks: " + "positive scrolls down (vertical) or right (horizontal), which is " + "the protocol's direction rather than a choice of ours. The cursor " + "does not move, so the resume point keeps its coordinates -- but it " + "is re-stamped, because a scroll is the session acting and a later " + "resume should know when it last did." + ), + )) + scroll.add_argument("id", help="session id") + scroll.add_argument( + "--axis", default="vertical", choices=AXES, metavar="A", + help="vertical (default) or horizontal", + ) + scroll.add_argument( + "--amount", type=float, default=3.0, metavar="N", + help="wheel clicks, signed; positive is down/right (default: 3)", + ) + for name, state in (("down", "down"), ("up", "up")): sub = with_lease(add_gesture( name, @@ -951,6 +982,29 @@ def _cmd_pointer_click(args: argparse.Namespace) -> int: return _finish_gesture(args, reply, render, args.id) +@_guard +def _cmd_pointer_scroll(args: argparse.Namespace) -> int: + lease_id = _lease_of(args, args.id) + if not lease_id: + return _no_lease(args, args.id) + reply = _request( + args, + "pointer.scroll", + id=args.id, + lease_id=lease_id, + axis=args.axis, + amount=args.amount, + ) + + def render(r: dict[str, Any]) -> str: + return ( + f"{r.get('id')}: scrolled {r.get('axis')} by {r.get('amount')} " + f"at {fmt.render_bookmark(r.get('bookmark'))}" + ) + + return _finish_gesture(args, reply, render, args.id) + + @_guard def _cmd_pointer_button(args: argparse.Namespace) -> int: lease_id = _lease_of(args, args.id) diff --git a/src/hhstreamd/driver.py b/src/hhstreamd/driver.py index d478af0..7ad09d6 100644 --- a/src/hhstreamd/driver.py +++ b/src/hhstreamd/driver.py @@ -83,6 +83,17 @@ class PointerDriver: def button(self, button: str, state: str) -> None: self.request({"op": "button", "button": button, "state": state}) + def axis(self, axis_name: str, value: float) -> None: + """Scroll the aimed output by ``value`` wheel clicks along ``axis_name``. + + Positive vertical is down, positive horizontal is right (the protocol's + direction). The output is whatever the last ``warp`` aimed at, so a + scroll into another session is a warp first -- which is also what the + lease serialises. + """ + + self.request({"op": "axis", "axis": axis_name, "value": float(value)}) + def frame(self) -> None: """Commit what was queued. Nothing the driver was sent is delivered to the compositor until this, so every gesture ends with one.""" diff --git a/src/hhstreamd/manager.py b/src/hhstreamd/manager.py index 441a2c2..134a906 100644 --- a/src/hhstreamd/manager.py +++ b/src/hhstreamd/manager.py @@ -116,6 +116,12 @@ DEFAULT_CONTAINER_SLOTS = 4 #: and "click 10000 times" is not a gesture. MAX_CLICK_COUNT = 3 +#: The largest scroll one request may carry, in wheel clicks. The driver +#: enforces the same ceiling with its own copy (they are separate processes and +#: neither imports the other); this one exists so the broker refuses early with a +#: message naming the caller's value rather than relaying the driver's. +MAX_SCROLL_AMOUNT = 100.0 + SIGNALS_BY_NAME = { "TERM": signal.SIGTERM, "SIGTERM": signal.SIGTERM, @@ -1658,6 +1664,44 @@ class SessionManager: "bookmark": self._restore_point(session, output), } + async def pointer_scroll( + self, session_id: str, lease_id: str, axis: Any = "vertical", amount: Any = 3 + ) -> dict[str, Any]: + """Scroll the session's screen. + + Same shape as a click -- the lease is checked first, then the driver is + told, then the resume point is re-stamped -- with one difference that is + worth being precise about: **the cursor does not move**. The + coordinates are therefore re-affirmed rather than changed. The stamp + advances, because a scroll is the session acting and a later resume + should know when it last did -- but not one pixel of the position + changes, and a bookmark that claimed otherwise would be fiction. + """ + + session, output = await self._refresh(session_id, lease_id) + name = _axis_name(axis if axis is not None else "vertical") + clicks = _checked_amount(amount) + await self._drive("axis", name, clicks) + await self._drive("frame") + # A bookmark from a container this session no longer has is not a + # position in this one, so a missing or stale one falls back to the + # centre that the acquire would have aimed at. + known = self._restore_point(session, output) or {} + mark = self._mark( + session, + lease_id, + output, + float(known.get("x", 0.5)), + float(known.get("y", 0.5)), + ) + self.audit.emit("pointer_scroll", session=session.id, axis=name, amount=clicks) + return { + "id": session.id, + "axis": name, + "amount": clicks, + "bookmark": mark, + } + async def pointer_release(self, session_id: str, lease_id: str) -> dict[str, Any]: """Give the cursor back, leaving nothing pressed and a bookmark behind.""" @@ -2079,6 +2123,35 @@ def _button_name(value: Any) -> str: 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}") + return value + + +def _checked_amount(value: Any) -> float: + """A scroll amount in wheel clicks, signed. + + Signed rather than split into `--up`/`--down`: the protocol carries direction + in the sign (positive vertical is down), and a second vocabulary on top of it + is how a scroll ends up backwards. Zero is refused because it is never + intended -- it is a caller that forgot to pass an amount. + """ + + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ManagerError( + "invalid_argument", f"amount must be a number of wheel clicks, got {value!r}" + ) + amount = float(value) + if amount == 0 or abs(amount) > MAX_SCROLL_AMOUNT: + raise ManagerError( + "invalid_argument", + f"amount must be non-zero and at most {MAX_SCROLL_AMOUNT:g} wheel clicks, " + f"got {amount}", + ) + return amount + + def _checked_count(value: Any) -> int: if isinstance(value, bool) or not isinstance(value, int): raise ManagerError("invalid_argument", f"count must be an integer, got {value!r}") diff --git a/src/hhstreamd/protocol.py b/src/hhstreamd/protocol.py index 9f0f05f..94b6afc 100644 --- a/src/hhstreamd/protocol.py +++ b/src/hhstreamd/protocol.py @@ -148,6 +148,7 @@ VERBS = ( "pointer.move", "pointer.button", "pointer.click", + "pointer.scroll", "pointer.release", "pointer.state", ) @@ -171,6 +172,7 @@ MUTATING_VERBS = frozenset( "pointer.move", "pointer.button", "pointer.click", + "pointer.scroll", "pointer.release", } ) diff --git a/src/hhstreamd/server.py b/src/hhstreamd/server.py index 755c583..f981298 100644 --- a/src/hhstreamd/server.py +++ b/src/hhstreamd/server.py @@ -70,6 +70,7 @@ class ControlServer: "pointer.move": self._op_pointer_move, "pointer.button": self._op_pointer_button, "pointer.click": self._op_pointer_click, + "pointer.scroll": self._op_pointer_scroll, "pointer.release": self._op_pointer_release, "pointer.state": self._op_pointer_state, } @@ -356,6 +357,18 @@ class ControlServer: ) ) + async def _op_pointer_scroll( + self, request: dict[str, Any], caller: dict[str, Any] + ) -> dict[str, Any]: + return protocol.ok( + **await self.manager.pointer_scroll( + request.get("id"), + request.get("lease_id"), + request.get("axis", "vertical"), + request.get("amount", 3), + ) + ) + async def _op_pointer_release( self, request: dict[str, Any], caller: dict[str, Any] ) -> dict[str, Any]: diff --git a/tests/pointer/test_ops.py b/tests/pointer/test_ops.py index ecbe3f0..041609c 100644 --- a/tests/pointer/test_ops.py +++ b/tests/pointer/test_ops.py @@ -34,6 +34,9 @@ class RecordingSink: def button(self, output, code, state): self.calls.append(("button", output, code, state)) + def axis(self, output, axis, value): + self.calls.append(("axis", output, axis, value)) + def frame(self, output): self.calls.append(("frame", output)) @@ -105,6 +108,51 @@ def test_buttons_follow_the_last_warp_not_the_first(driver, sink): assert sink.calls[-1] == ("button", "hh-beta", LEFT, DOWN) +# -- axis (scrolling) ------------------------------------------------------- + + +def test_axis_scrolls_the_aimed_output_and_sends_no_implicit_frame(driver, sink): + warp(driver) + sink.calls.clear() + + assert driver.handle({"op": "axis", "axis": "vertical", "value": 3}) == {"ok": True} + assert sink.calls == [("axis", "hh-alpha", buttons.AXES["vertical"], 3.0)] + + +def test_axis_defaults_to_one_vertical_click(driver, sink): + warp(driver) + sink.calls.clear() + + assert driver.handle({"op": "axis"}) == {"ok": True} + assert sink.calls == [("axis", "hh-alpha", buttons.AXES["vertical"], 1.0)] + + +def test_a_horizontal_scroll_is_the_other_axis_and_keeps_the_sign(driver, sink): + warp(driver) + sink.calls.clear() + + assert driver.handle({"op": "axis", "axis": "horizontal", "value": -2}) == {"ok": True} + assert sink.calls == [("axis", "hh-alpha", buttons.AXES["horizontal"], -2.0)] + # Two names, two axes -- and positive is down/right, per the protocol rather + # than per us, which is why direction travels in the sign and not the name. + assert buttons.AXES["vertical"] != buttons.AXES["horizontal"] + + +def test_a_scroll_goes_to_the_pointer_the_last_warp_aimed(driver, sink): + warp(driver, output="hh-alpha") + warp(driver, output="hh-beta") + sink.calls.clear() + + driver.handle({"op": "axis", "value": 5}) + + assert sink.calls == [("axis", "hh-beta", buttons.AXES["vertical"], 5.0)] + + +def test_scroll_before_any_warp_is_refused(driver, sink): + assert driver.handle({"op": "axis", "value": 3})["ok"] is False + assert sink.calls == [], "a scroll with nothing aimed must emit nothing" + + # -- pressed / release_all -------------------------------------------------- @@ -220,6 +268,13 @@ def test_a_failed_warp_does_not_change_the_aim(): ({"op": "button", "button": "left"}, "'state' must be"), ({"op": "button", "button": "pinky", "state": "down"}, "unknown button 'pinky'"), ({"op": "button", "button": "left", "state": "sideways"}, "unknown button state"), + ({"op": "axis", "axis": "diagonal"}, "unknown axis 'diagonal'"), + ({"op": "axis", "axis": 0}, "'axis' must be a string"), + ({"op": "axis", "value": "a lot"}, "'value' must be a number"), + ({"op": "axis", "value": True}, "'value' must be a number"), + ({"op": "axis", "value": float("nan")}, "'value' must be finite"), + ({"op": "axis", "value": 101}, "wheel-click limit"), + ({"op": "axis", "value": -1e9}, "wheel-click limit"), ], ) def test_malformed_requests_are_answered_not_fatal(sink, request_, fragment): @@ -240,5 +295,21 @@ def test_a_non_object_request_is_refused(driver, request_): assert "must be a JSON object" in driver.handle(request_)["error"] -def test_the_contracts_five_ops_are_exactly_what_is_implemented(): - assert set(Dispatcher._ops) == {"warp", "button", "frame", "pressed", "release_all"} +def test_the_contracts_ops_are_exactly_what_is_implemented() -> None: + """The op set cannot drift quietly. + + An op that exists here and nowhere in the contract -- or the reverse -- + fails this test rather than surprising whoever reads the contract next. + ``axis`` is the one addition since the freeze, made deliberately so that a + session can scroll; the set is edited by hand, which is the reminder to + write it down. + """ + + assert set(Dispatcher._ops) == { + "warp", + "button", + "axis", + "frame", + "pressed", + "release_all", + } diff --git a/tests/sessions/fakes.py b/tests/sessions/fakes.py index 04f21ae..cdf2b0d 100644 --- a/tests/sessions/fakes.py +++ b/tests/sessions/fakes.py @@ -353,6 +353,10 @@ class RecordingSink: self._check() self.calls.append(("button", output, code, state)) + def axis(self, output: str, axis: int, value: float) -> None: + self._check() + self.calls.append(("axis", output, axis, value)) + def frame(self, output: str) -> None: self._check() self.calls.append(("frame", output)) diff --git a/tests/sessions/unit/test_pointer_verbs.py b/tests/sessions/unit/test_pointer_verbs.py index e834e8d..007e553 100644 --- a/tests/sessions/unit/test_pointer_verbs.py +++ b/tests/sessions/unit/test_pointer_verbs.py @@ -24,6 +24,10 @@ from hhstreamd.registry import ContainerState, Session, State, container_record LEFT = 0x110 DOWN, UP = 1, 0 +#: ``wl_pointer_axis``, mirrored from the driver for the same reason the button +#: codes above are: these tests assert the events, so they name the wire values. +VERTICAL, HORIZONTAL = 0, 1 + def make_session(session_id: str = "foot-aaaaaa", *, container: bool = True) -> Session: return Session( @@ -590,3 +594,103 @@ def test_the_sweeper_expires_a_lease_nobody_came_back_for(short_tmpdir: Path): if manager.driver is not None: manager.driver.close() fake.stop() + + +# --------------------------------------------------------------------------- +# scrolling +# --------------------------------------------------------------------------- + + +def test_scroll_drives_axis_then_frame_on_the_sessions_own_output(harness): + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.fake.sink.calls.clear() + + reply = harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "vertical", 3)) + + assert (reply["axis"], reply["amount"]) == ("vertical", 3.0) + assert harness.fake.sink.calls == [ + ("axis", "hh-foot-aaaaaa", VERTICAL, 3.0), + ("frame", "hh-foot-aaaaaa"), + ] + + +def test_scrolling_up_is_the_sign_and_not_a_different_verb(harness): + """One verb, one axis name, and the protocol's sign carries the direction.""" + + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.fake.sink.calls.clear() + + harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "vertical", -3)) + + assert harness.fake.sink.calls == [ + ("axis", "hh-foot-aaaaaa", VERTICAL, -3.0), + ("frame", "hh-foot-aaaaaa"), + ] + + +def test_a_horizontal_scroll_uses_the_other_axis(harness): + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.fake.sink.calls.clear() + + harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "horizontal", 2)) + + assert harness.fake.sink.calls == [ + ("axis", "hh-foot-aaaaaa", HORIZONTAL, 2.0), + ("frame", "hh-foot-aaaaaa"), + ] + + +def test_a_scroll_restamps_the_resume_point_without_moving_it(harness): + """The cursor stays put -- and the record must not pretend otherwise.""" + + session = harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + before = dict(session.pointer["bookmark"]) + + harness.clock.advance(7.0) + reply = harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "vertical", 3)) + + assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (before["x"], before["y"]) + assert reply["bookmark"]["output"] == before["output"] + assert reply["bookmark"]["at"] != before["at"], "the session acted, so the stamp moved" + assert harness.manager.pointer.state()["holder"] == "foot-aaaaaa" + + +@pytest.mark.parametrize("bad", [0, 0.0, 101, -101, "three", True, None]) +def test_a_scroll_amount_off_the_wire_is_bounded(harness, bad): + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "vertical", bad)) + + assert exc.value.error == "invalid_argument" + + +def test_an_unknown_axis_is_refused_by_the_driver_not_invented(harness): + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.fake.sink.calls.clear() + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "diagonal", 3)) + + assert exc.value.error == "driver_refused" + assert harness.fake.sink.calls == [], "a refused scroll must emit nothing" + + +def test_a_scroll_without_the_lease_is_refused(harness): + session = harness.add() + harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) + harness.fake.sink.calls.clear() + + with pytest.raises(ManagerError): + harness.run( + harness.manager.pointer_scroll("foot-aaaaaa", "not-this-lease", "vertical", 3) + ) + + assert harness.fake.sink.calls == [] + assert session.pointer.get("bookmark") is not None, "a refused scroll changes nothing"