Files
hyprland-headless-stream-pl…/tests/pointer/test_pointer_server.py
T
HermenixandClaude Opus 5 f931858f30 Stage 1: the driver learns to type
`zwp_virtual_keyboard_v1`, spoken by the process that already speaks
`zwlr_virtual_pointer_v1`. One device for the seat, one keymap uploaded
once, keysym names on our socket and evdev codes only on the Wayland
request -- the division buttons.py already draws.

keymap.py is the new seam, and it holds the three decisions that have a
wrong version which looks right:

  * A capital is the MASK, not a synthetic Shift keycode. Hyprland's
    virtual keyboard never runs updateXkbStateWithKey, so a virtual
    KEY_LEFTSHIFT changes no modifier state at all -- and sending both
    is how a toolkit applies Shift twice.
  * A modifier is whatever the keymap says is one, measured by pressing
    each key in a throwaway xkb state. Not a name list: `@` on `de` is a
    level-three symbol, and a Shift-only special case types the wrong
    character. (The measured set is also smaller than the canonical one,
    because no keycode on us/pc105 carries Meta or Hyper.)
  * A lock is not a modifier. Caps_Lock reports a *locked* mask, so
    `type` refuses while it is held rather than guessing the case.

The whole string resolves before anything is emitted, and every refusal
names the scalar INDEX, never the character: these messages reach the
driver's log and the string is a password as often as not.

Folding in the review's changes 1, 2, 3 and 6:

  1 a Rejected now carries a `kind`. A bad keysym or an unmappable
    character is `invalid_argument`; a missing keyboard global is
    `refused`. Without the token the broker would have to tell exit 2
    from exit 10 by reading English, and _drive maps every `ok: false`
    to driver_refused today.
  2 the keymap `size` on the wire includes the trailing NUL, and the fd
    outlives a roundtrip rather than a flush. Hyprland mmaps exactly
    that many bytes and hands the pointer to xkb_keymap_new_from_string.
  3 release_all lifts buttons, then keys in press order, then zeroes the
    mask -- and the mask only if something set it, so a compositor with
    no keyboard global still gets its buttons lifted. One release_all is
    the whole of expiry; an exception in the key half would abandon it.
  6 `key` and `type` never call _aimed(). A keyboard has no output, and
    one test deliberately never warps so that stays true.

Also: `--xkb-layout/-model/-variant/-options`, compiled BEFORE any
Wayland call so a bad layout is exit 2 rather than exit 10; a comma in
the layout refused outright, because v1 always sends group 0 and
xkbcommon would hand back a second group nothing could reach; the
keymap uploaded after connect and before listen, with one
modifiers(0,0,0,0) after it; and xkbcommon as a hard, non-optional
dependency -- an optional one would let test_keymap.py skip, and the
unmappable-character path is the one that must not rot.

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GhNPM6rGcuzxocM1nATnuM
2026-10-04 03:39:00 +00:00

145 lines
4.6 KiB
Python

"""The driver's socket: framing, not logic.
The dispatcher is tested next door; what is proved here is that a real
``AF_UNIX`` connection carrying newline-delimited JSON gets one response object
per request line, that a garbled line is answered rather than fatal, and that
the connection stays open for the next request — which matters because the
broker holds one connection for the life of a lease.
"""
from __future__ import annotations
import json
import shutil
import socket
import tempfile
import threading
from pathlib import Path
import pytest
from hhstream_pointer.ops import Dispatcher
from hhstream_pointer.server import PointerServer
from test_ops import RecordingSink
#: Linux's sun_path is 108 bytes including the NUL, and pytest's tmp_path can
#: exceed it, so the socket lives in a shallow directory of its own.
SUN_PATH_MAX = 107
@pytest.fixture
def connection():
"""A listening driver and a connected client, torn down together."""
directory = Path(tempfile.mkdtemp(prefix="hhp"))
path = directory / "p.sock"
if len(str(path).encode()) > SUN_PATH_MAX:
pytest.skip(f"socket path too long for AF_UNIX: {path}")
sink = RecordingSink()
server = PointerServer(path, Dispatcher(sink).handle)
server.listen()
thread = threading.Thread(target=_serve_once, args=(server,), daemon=True)
thread.start()
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.settimeout(5.0)
client.connect(str(path))
try:
yield _Client(client), sink
finally:
client.close()
thread.join(timeout=5.0)
server.close()
shutil.rmtree(directory, ignore_errors=True)
def _serve_once(server: PointerServer) -> None:
conn, _ = server._sock.accept()
with conn:
server._serve_connection(conn)
class _Client:
def __init__(self, sock: socket.socket) -> None:
self._stream = sock.makefile("rwb")
def call(self, request: dict) -> dict:
self._stream.write(json.dumps(request).encode() + b"\n")
self._stream.flush()
return json.loads(self._stream.readline())
def send_raw(self, line: bytes) -> dict:
self._stream.write(line)
self._stream.flush()
return json.loads(self._stream.readline())
def test_one_request_gets_one_response(connection):
client, _ = connection
assert client.call({"op": "pressed"}) == {"ok": True, "buttons": [], "keys": []}
def test_many_requests_share_one_connection(connection):
client, sink = connection
assert client.call({"op": "warp", "output": "hh-a", "x": 0.5, "y": 0.5}) == {"ok": True}
assert client.call({"op": "button", "button": "left", "state": "down"}) == {"ok": True}
assert client.call({"op": "frame"}) == {"ok": True}
assert client.call({"op": "pressed"}) == {
"ok": True,
"buttons": ["left"],
"keys": [],
}
assert client.call({"op": "release_all"}) == {
"ok": True,
"lifted": ["left"],
"lifted_keys": [],
}
assert [c[0] for c in sink.calls] == ["motion", "button", "frame", "button", "frame"]
def test_a_rejected_request_leaves_the_connection_usable(connection):
client, _ = connection
assert client.call({"op": "nonsense"})["ok"] is False
assert client.call({"op": "pressed"})["ok"] is True
def test_malformed_json_is_answered_not_fatal(connection):
client, _ = connection
response = client.send_raw(b"{not json\n")
assert response["ok"] is False
assert "malformed JSON" in response["error"]
# Still talking.
assert client.call({"op": "pressed"})["ok"] is True
def test_an_oversized_line_is_refused(connection):
from hhstream_pointer.server import MAX_LINE_BYTES
client, _ = connection
response = client.send_raw(b'{"op":"' + b"x" * MAX_LINE_BYTES + b'"}\n')
assert response == {"ok": False, "error": "request line too long"}
def test_listen_replaces_a_stale_socket_file():
"""A crashed driver leaves the file behind; the unit must still start."""
directory = Path(tempfile.mkdtemp(prefix="hhp"))
path = directory / "p.sock"
if len(str(path).encode()) > SUN_PATH_MAX:
pytest.skip("socket path too long for AF_UNIX")
try:
first = PointerServer(path, Dispatcher(RecordingSink()).handle)
first.listen()
first._sock.close() # the file survives; the listener does not
second = PointerServer(path, Dispatcher(RecordingSink()).handle)
second.listen()
assert path.is_socket()
assert path.stat().st_mode & 0o777 == 0o660
second.close()
assert not path.exists()
finally:
shutil.rmtree(directory, ignore_errors=True)