diff --git a/flake.nix b/flake.nix index 17138a9..5a30480 100644 --- a/flake.nix +++ b/flake.nix @@ -40,7 +40,10 @@ grim ffmpeg # The client side of the contract (hhstream-client), so a shell can - # read the stream without a `nix build` first. + # read the stream without a `nix build` first. It also brings + # pywayland and xkbcommon, which `tests/pointer` imports directly -- + # `test_keymap.py` compiles a real `us` keymap rather than stubbing + # one, because a stub cannot tell you that `é` is unmappable. (callPackage ./nix/package.nix { }) # `websocket-client` drives Chromium over the DevTools protocol, which # is how the demo types into the page and reads the result back. diff --git a/nix/package.nix b/nix/package.nix index fb402ca..b63567b 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -12,22 +12,29 @@ python3.pkgs.buildPythonApplication { build-system = [ python3.pkgs.setuptools ]; - # `hhstream-pointer` is a Wayland client, so it needs libwayland's marshalling. - # The wlr virtual-pointer protocol itself is *not* a build input: the generated - # module is vendored under src/hhstream_pointer/_protocol, so a checkout builds - # without a code generator. See that package's docstring for why, and - # hhstream_pointer._protocol.regenerate for how to refresh it. - dependencies = [ python3.pkgs.pywayland ]; + # `hhstream-pointer` is a Wayland client, so it needs libwayland's + # marshalling; and it resolves keysym names against the XKB layout it + # uploads, so it needs xkbcommon. + # + # Neither protocol XML is a build input: both generated modules are vendored + # under src/hhstream_pointer/_protocol, so a checkout builds without a code + # generator. See that package's docstring for why, and + # hhstream_pointer._protocol.regenerate for how to refresh them -- including + # the note that virtual-keyboard-unstable-v1.xml is not in wayland-protocols + # or wlr-protocols in this nixpkgs and comes from pkgs.hyprland.src. + dependencies = [ python3.pkgs.pywayland python3.pkgs.xkbcommon ]; # Unit tests are wired up in the flake's `checks` so they can run without # installing the package; see docs/CONTRACT.md. doCheck = false; - # Cheap proof that the vendored protocol still binds against this pywayland: - # importing it runs the scanner-generated `_gen_c()` for both interfaces. + # Cheap proof that the vendored protocols still bind against this pywayland: + # importing each runs the scanner-generated `_gen_c()` for its interfaces. pythonImportsCheck = [ "hhstream_pointer.ops" + "hhstream_pointer.keymap" "hhstream_pointer._protocol.wlr_virtual_pointer_unstable_v1" + "hhstream_pointer._protocol.virtual_keyboard_unstable_v1" ]; meta = { diff --git a/pyproject.toml b/pyproject.toml index 0e8c0f9..0645b84 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,11 +8,14 @@ version = "0.1.0" description = "Publish a headless Hyprland session's frames on a Unix socket" requires-python = ">=3.11" # The frame socket, the CLI and the broker are stdlib-only by policy -# (docs/CONTRACT-sessions.md §6, rule 3). The pointer driver is the one -# exception: talking Wayland means speaking the wire protocol, and -# re-implementing libwayland's marshalling here would be a worse idea than -# a dependency. -dependencies = ["pywayland>=0.4"] +# (docs/CONTRACT-sessions.md §6, rule 3). The input driver is the one +# exception, twice over: talking Wayland means speaking the wire protocol, and +# turning a keysym name into the keycode-plus-modifier-mask that *this* layout +# needs means compiling an XKB keymap. Re-implementing either here would be a +# worse idea than a dependency, and `xkbcommon` is deliberately NOT optional -- +# an optional one would let `tests/pointer/test_keymap.py` skip, and the +# unmappable-character path is exactly the one that must not rot. +dependencies = ["pywayland>=0.4", "xkbcommon>=1.0"] [project.scripts] hhstream-server = "hhstream.server:main" diff --git a/src/hhstream_pointer/__main__.py b/src/hhstream_pointer/__main__.py index fd99c32..d025f04 100644 --- a/src/hhstream_pointer/__main__.py +++ b/src/hhstream_pointer/__main__.py @@ -3,15 +3,33 @@ The broker starts it with exactly: hhstream-pointer --socket /run/hhstream/pointer.sock \\ - --compositor-runtime-dir /run/hypr-stream + --compositor-runtime-dir /run/hypr-stream \\ + --xkb-layout us --xkb-model pc105 \\ + --xkb-variant '' --xkb-options '' -Both flags default to those frozen paths (§5) so the binary is also runnable by -hand when diagnosing a stuck cursor. +Every flag defaults to the value above, so the binary is also runnable by hand +when diagnosing a stuck cursor or a layout that will not type. -It connects to the compositor *before* it listens. A socket that exists is a -promise that warps will work, and a driver that accepted requests while still -looking for a version-2 manager would answer the first few with errors the -broker cannot tell apart from a bad output name. +**The XKB flags are the only way a layout reaches the uploaded keymap.** Not +the broker's TOML: `[pointer]` in that file is read by `hhstreamd` for its +lease numbers, and this is a different unit that never opens it. A `[keyboard]` +table there would be a setting an operator could change with no effect at all +— which is why `nix/module.nix` puts the layout on this command line instead. + +Order of start-up, and none of it is interchangeable: + +1. **Compile the keymap.** Before any Wayland call, because a layout + xkbcommon will not compile is a configuration error (exit 2) and has + nothing to do with the compositor. +2. **Connect.** A version-1 pointer manager or an unreachable display is + exit 10. +3. **Upload the keymap**, if the compositor has a keyboard manager at all. + ``key`` before ``keymap`` is the protocol error ``no_keymap``, which kills + the connection rather than returning something reportable. +4. **Then listen.** A socket that exists is a promise that warps and keys + work; a driver that accepted requests while still looking for a manager + would answer the first few with errors the broker cannot tell apart from a + bad output name. """ from __future__ import annotations @@ -23,7 +41,14 @@ import sys from pathlib import Path from typing import Any -from .backend import CompositorUnavailable, ManagerTooOld, OutputUnknown, WaylandSink +from . import keymap as keymaps +from .backend import ( + CompositorUnavailable, + KeyboardUnavailable, + ManagerTooOld, + OutputUnknown, + WaylandSink, +) from .ops import Dispatcher from .server import PointerServer @@ -39,6 +64,13 @@ EXIT_COMPOSITOR = 10 DEFAULT_SOCKET = Path("/run/hhstream/pointer.sock") DEFAULT_RUNTIME_DIR = Path("/run/hypr-stream") +#: Frozen defaults for the keymap, matching §5's style for the paths above. +#: ``us``/``pc105`` and empty variant/options is what the NixOS module's +#: ``sessions.keyboard.*`` defaults to as well, so a hand-run driver and the +#: unit type the same characters. +DEFAULT_LAYOUT = "us" +DEFAULT_MODEL = "pc105" + class _Terminated(Exception): """SIGTERM/SIGINT arrived; unwind through the normal shutdown path.""" @@ -69,6 +101,20 @@ def build_parser() -> argparse.ArgumentParser: default=0o660, help="octal mode for the driver socket (default 660)", ) + parser.add_argument( + "--xkb-layout", + default=DEFAULT_LAYOUT, + metavar="LAYOUT", + help="XKB layout uploaded as the virtual keyboard's keymap (default: " + f"{DEFAULT_LAYOUT}). One group only: a comma-separated list is refused, " + "because every `modifiers` request sends group 0 and the rest would be " + "unreachable.", + ) + parser.add_argument( + "--xkb-model", default=DEFAULT_MODEL, metavar="MODEL", help="XKB model" + ) + parser.add_argument("--xkb-variant", default="", metavar="VARIANT", help="XKB variant") + parser.add_argument("--xkb-options", default="", metavar="OPTIONS", help="XKB options") parser.add_argument("--log-level", default="info", help="debug, info, warning, error") return parser @@ -80,6 +126,20 @@ def main(argv: list[str] | None = None) -> int: format="%(levelname)s %(name)s: %(message)s", ) + # Step 1: the layout, before anything touches Wayland. A layout that will + # not compile is the operator's typo, not the compositor's fault, and + # reporting it as exit 10 would send them looking at the wrong unit. + try: + keymap = keymaps.build( + layout=args.xkb_layout, + model=args.xkb_model, + variant=args.xkb_variant, + options=args.xkb_options, + ) + except keymaps.KeymapError as exc: + log.error("%s", exc) + return EXIT_USAGE + sink = WaylandSink(args.compositor_runtime_dir, args.wayland_display) try: sink.connect() @@ -92,7 +152,18 @@ def main(argv: list[str] | None = None) -> int: log.error("%s", exc) return EXIT_COMPOSITOR - dispatcher = Dispatcher(sink) + try: + sink.upload_keymap(keymap.text()) + except CompositorUnavailable as exc: + # A keymap the compositor refuses leaves the resource dead, so there is + # nothing to listen for requests with. Exit 10 and let the unit restart + # us; exit 2 would claim the operator's layout was wrong when + # xkbcommon already accepted it. + log.error("the keymap upload failed: %s", exc) + sink.close() + return EXIT_COMPOSITOR + + dispatcher = Dispatcher(sink, keymap) server = PointerServer(args.socket, _handler(dispatcher), socket_mode=args.socket_mode) for sig in (signal.SIGTERM, signal.SIGINT): @@ -112,8 +183,14 @@ def main(argv: list[str] | None = None) -> int: log.error("socket %s: %s", args.socket, exc) return EXIT_USAGE finally: - # Never exit with a button held: the compositor would keep it down and - # the next session would inherit a drag it never started. + # Never exit with a button or a key held, and never with a modifier + # mask set. The compositor keeps all three: `destroy` of a virtual + # keyboard releases nothing and clears no mask on this build (measured, + # tests/README-keyboard-probe.md), and a code left in the seat's + # `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`. _lift_everything(dispatcher) server.close() sink.close() @@ -131,20 +208,28 @@ def _handler(dispatcher: Dispatcher): def handle(request: Any) -> dict[str, Any]: try: return dispatcher.handle(request) - except OutputUnknown as exc: - return {"ok": False, "error": str(exc)} + except (OutputUnknown, KeyboardUnavailable) as exc: + # Both are "the compositor does not have that", not "this + # connection is finished": the broker is told and keeps its lease. + return {"ok": False, "error": str(exc), "kind": "refused"} return handle def _lift_everything(dispatcher: Dispatcher) -> None: try: - lifted = dispatcher.handle({"op": "release_all"}).get("lifted") or [] + reply = dispatcher.handle({"op": "release_all"}) except Exception as exc: # shutdown is not a place to raise - log.warning("could not lift buttons on the way out: %s", exc) + log.warning("could not lift buttons and keys on the way out: %s", exc) return - if lifted: - log.info("lifted on shutdown: %s", ", ".join(lifted)) + lifted = reply.get("lifted") or [] + lifted_keys = reply.get("lifted_keys") or [] + if lifted or lifted_keys: + log.info( + "lifted on shutdown: buttons %s, keys %s", + ", ".join(lifted) or "none", + ", ".join(lifted_keys) or "none", + ) def _raise_terminated(signum: int, frame) -> None: diff --git a/src/hhstream_pointer/_protocol/__init__.py b/src/hhstream_pointer/_protocol/__init__.py index 0a07ab7..9bcf8d3 100644 --- a/src/hhstream_pointer/_protocol/__init__.py +++ b/src/hhstream_pointer/_protocol/__init__.py @@ -1,8 +1,18 @@ -"""The wlr virtual-pointer protocol, generated and vendored. +"""The two input protocols, generated and vendored. -``wlr_virtual_pointer_unstable_v1/`` is byte-for-byte pywayland scanner output -for ``wlr-virtual-pointer-unstable-v1.xml``; do not hand-edit it. Regenerate -with :mod:`hhstream_pointer._protocol.regenerate`, which prints the command. +``wlr_virtual_pointer_unstable_v1/`` and ``virtual_keyboard_unstable_v1/`` are +byte-for-byte pywayland scanner output for +``wlr-virtual-pointer-unstable-v1.xml`` and +``virtual-keyboard-unstable-v1.xml``; do not hand-edit either. Regenerate with +:mod:`hhstream_pointer._protocol.regenerate`, which prints the command and +records where each XML actually lives — the keyboard one is not where either +plan says it is, and its docstring says so at length. + +One thing the keyboard XML does *not* give us, and it matters: it names +``keymap_format`` and ``key_state`` in its request descriptions and defines +neither enum, so there is nothing generated to read ``xkb_v1 == 1`` or +``pressed == 1`` off. Those live in :data:`hhstream_pointer.keymap.XKB_V1` and +:data:`hhstream_pointer.buttons.STATES` instead, with the citation. Vendored rather than generated at build time for one reason: the scanner needs ``wlr-protocols`` and a working pywayland on the *build* host, so generating diff --git a/src/hhstream_pointer/_protocol/regenerate.py b/src/hhstream_pointer/_protocol/regenerate.py index dbcd99d..22dde98 100644 --- a/src/hhstream_pointer/_protocol/regenerate.py +++ b/src/hhstream_pointer/_protocol/regenerate.py @@ -1,17 +1,44 @@ -"""Regenerate the vendored protocol package. Run by hand after a bump. +"""Regenerate the vendored protocol packages. Run by hand after a bump. nix shell --impure --expr 'with (builtins.getFlake "nixpkgs").legacyPackages.${builtins.currentSystem}; [ (python3.withPackages (p: [ p.pywayland ])) wlr-protocols ]' \\ - --command python3 -m hhstream_pointer._protocol.regenerate + --command env HHSTREAM_PROTOCOL_DIR="$(nix eval --raw nixpkgs#hyprland.src)/protocols" \\ + python3 -m hhstream_pointer._protocol.regenerate -The XML lives at ``share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml`` +Two protocols, two XMLs, and they are in two different places. + +**The virtual pointer** is ``share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml`` in ``pkgs.wlr-protocols`` — note that this is *not* the path -``docs/CONTRACT-sessions.md`` §3.4 gives; see the slice report. +``docs/CONTRACT-sessions.md`` §3.4 originally gave; see the slice report and +the §3.4 amendment. -pywayland's own ``python -m pywayland.scanner`` is not usable here: it builds -its import map only from the files it was handed, so scanning the wlr XML alone -raises ``KeyError: 'wl_seat'``. We seed the map with the core interfaces -pywayland already ships, then let the scanner emit ``from ..wayland import ...`` -against the shim next door. +**The virtual keyboard** is ``protocols/virtual-keyboard-unstable-v1.xml`` in +``pkgs.hyprland.src``, and that needs saying because two plans name a different +path. ``docs/plans/2026-10-03-keyboard-input.md`` §2 and the review's +objection 4 both call for wayland-protocols' +``unstable/virtual-keyboard/virtual-keyboard-unstable-v1.xml``. **No such file +exists in this flake's nixpkgs.** Checked: wayland-protocols 1.49 has no +``virtual-keyboard`` directory under ``unstable``, ``staging`` or ``stable``; +``pkgs.wlr-protocols`` (nixpkgs' 2022-09-05 snapshot) ships ten XMLs and this +is not one of them, in its output or its source; ``pkgs.wlroots.src`` does not +have it either. Hyprland's own copy is the only one on the machine, so it is +the one vendored, and ``$HHSTREAM_PROTOCOL_DIR`` is how this script is told +where that is. + +One consequence of using that copy, and the reason the review wanted to avoid +it: it *names* ``keymap_format`` and ``key_state`` in its request descriptions +and defines neither enum. So the generated module has no enum to read those +integers off, and they are written down instead — :data:`hhstream_pointer.keymap.XKB_V1` +for the format, and the existing :data:`hhstream_pointer.buttons.STATES` for +``pressed``/``released``, which already holds the same two values because +``wl_pointer.button_state`` and ``wl_keyboard.key_state`` agree. If a future +nixpkgs grows the wayland-protocols copy, switching to it is a one-line change +here and those constants become redundant rather than wrong. + +pywayland's own ``python -m pywayland.scanner`` is not usable for either: it +builds its import map only from the files it was handed, so scanning one of +these alone raises ``KeyError: 'wl_seat'``. We seed the map with the core +interfaces pywayland already ships, then let the scanner emit +``from ..wayland import ...`` against the shim next door. """ from __future__ import annotations @@ -21,36 +48,55 @@ import os import sys from pathlib import Path -#: Where ``pkgs.wlr-protocols`` puts it, relative to the package root. -XML_SUFFIX = "share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml" +#: Where ``pkgs.wlr-protocols`` puts the pointer XML, relative to a package root. +POINTER_XML_SUFFIX = "share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml" + +#: Where wayland-protocols *would* put the keyboard XML if it had it. Searched +#: first anyway, so a nixpkgs that grows it is picked up without an edit. +KEYBOARD_XML_SUFFIX = ( + "share/wayland-protocols/unstable/virtual-keyboard/virtual-keyboard-unstable-v1.xml" +) + +#: The filename to look for in ``$HHSTREAM_PROTOCOL_DIR``, which is where +#: Hyprland's source keeps the only copy that exists here. +KEYBOARD_XML_NAME = "virtual-keyboard-unstable-v1.xml" + +#: Where to look for a package root that might contain either suffix. +ENV_PROTOCOL_DIR = "HHSTREAM_PROTOCOL_DIR" -def find_xml() -> Path | None: - """Look for the protocol XML on ``XDG_DATA_DIRS`` and in the nix profile.""" +def _roots() -> list[Path]: + """Package roots to search: ``XDG_DATA_DIRS``, then the usual profiles.""" roots = [Path(p).parent for p in os.environ.get("XDG_DATA_DIRS", "").split(":") if p] - roots += [Path("/run/current-system/sw"), Path.home() / ".nix-profile"] - for root in roots: - candidate = root / XML_SUFFIX + return roots + [Path("/run/current-system/sw"), Path.home() / ".nix-profile"] + + +def find_pointer_xml() -> Path | None: + for root in _roots(): + candidate = root / POINTER_XML_SUFFIX if candidate.is_file(): return candidate return None -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--xml", type=Path, default=None, help=f"path to .../{XML_SUFFIX}") - parser.add_argument( - "--output-dir", - type=Path, - default=Path(__file__).resolve().parent, - help="where the protocol package is written (default: next to this file)", - ) - args = parser.parse_args(argv) +def find_keyboard_xml() -> Path | None: + """wayland-protocols if it ever has it, else ``$HHSTREAM_PROTOCOL_DIR``.""" - xml = args.xml or find_xml() - if xml is None: - parser.error(f"could not find {XML_SUFFIX}; pass --xml (is wlr-protocols in the shell?)") + for root in _roots(): + candidate = root / KEYBOARD_XML_SUFFIX + if candidate.is_file(): + return candidate + directory = os.environ.get(ENV_PROTOCOL_DIR) + if directory: + candidate = Path(directory) / KEYBOARD_XML_NAME + if candidate.is_file(): + return candidate + return None + + +def generate(xml: Path, output_dir: Path) -> str: + """Scanner output for one XML into ``output_dir``. Returns the module name.""" from pywayland.protocol import wayland as core from pywayland.scanner.protocol import Protocol @@ -58,13 +104,56 @@ def main(argv: list[str] | None = None) -> int: protocol = Protocol.parse_file(str(xml)) module = protocol.name.replace("-", "_") # Interface -> protocol module. The core interfaces resolve to the shim in - # this directory; ours resolve to themselves. + # this directory; this protocol's own resolve to themselves. core_dir = Path(core.__file__).parent imports = {p.stem: "wayland" for p in core_dir.glob("wl_*.py")} imports.update({iface.name: module for iface in protocol.interface}) - protocol.output(str(args.output_dir), imports) - print(f"generated {module} from {xml} into {args.output_dir}") + protocol.output(str(output_dir), imports) + print(f"generated {module} from {xml} into {output_dir}") + return module + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--pointer-xml", type=Path, default=None, help=f"path to .../{POINTER_XML_SUFFIX}" + ) + parser.add_argument( + "--keyboard-xml", type=Path, default=None, help=f"path to .../{KEYBOARD_XML_NAME}" + ) + parser.add_argument( + "--only", + choices=("pointer", "keyboard"), + default=None, + help="regenerate one of the two; the default is both", + ) + parser.add_argument( + "--output-dir", + type=Path, + default=Path(__file__).resolve().parent, + help="where the protocol packages are written (default: next to this file)", + ) + args = parser.parse_args(argv) + + wanted = ("pointer", "keyboard") if args.only is None else (args.only,) + if "pointer" in wanted: + xml = args.pointer_xml or find_pointer_xml() + if xml is None: + parser.error( + f"could not find {POINTER_XML_SUFFIX}; pass --pointer-xml " + "(is wlr-protocols in the shell?)" + ) + generate(xml, args.output_dir) + if "keyboard" in wanted: + xml = args.keyboard_xml or find_keyboard_xml() + if xml is None: + parser.error( + f"could not find {KEYBOARD_XML_NAME}; pass --keyboard-xml, or set " + f"${ENV_PROTOCOL_DIR} to \"$(nix eval --raw nixpkgs#hyprland.src)/protocols\" " + "(it is not in wayland-protocols or wlr-protocols -- see the module docstring)" + ) + generate(xml, args.output_dir) return 0 diff --git a/src/hhstream_pointer/_protocol/virtual_keyboard_unstable_v1/__init__.py b/src/hhstream_pointer/_protocol/virtual_keyboard_unstable_v1/__init__.py new file mode 100644 index 0000000..34b8c79 --- /dev/null +++ b/src/hhstream_pointer/_protocol/virtual_keyboard_unstable_v1/__init__.py @@ -0,0 +1,28 @@ +# This file has been autogenerated by the pywayland scanner + +# Copyright © 2008-2011 Kristian Høgsberg +# Copyright © 2010-2013 Intel Corporation +# Copyright © 2012-2013 Collabora, Ltd. +# Copyright © 2018 Purism SPC +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice (including the next +# paragraph) shall be included in all copies or substantial portions of the +# Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. + +from .zwp_virtual_keyboard_manager_v1 import ZwpVirtualKeyboardManagerV1 # noqa: F401 +from .zwp_virtual_keyboard_v1 import ZwpVirtualKeyboardV1 # noqa: F401 diff --git a/src/hhstream_pointer/_protocol/virtual_keyboard_unstable_v1/zwp_virtual_keyboard_manager_v1.py b/src/hhstream_pointer/_protocol/virtual_keyboard_unstable_v1/zwp_virtual_keyboard_manager_v1.py new file mode 100644 index 0000000..2d692e1 --- /dev/null +++ b/src/hhstream_pointer/_protocol/virtual_keyboard_unstable_v1/zwp_virtual_keyboard_manager_v1.py @@ -0,0 +1,95 @@ +# This file has been autogenerated by the pywayland scanner + +# Copyright © 2008-2011 Kristian Høgsberg +# Copyright © 2010-2013 Intel Corporation +# Copyright © 2012-2013 Collabora, Ltd. +# Copyright © 2018 Purism SPC +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice (including the next +# paragraph) shall be included in all copies or substantial portions of the +# Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. + +from __future__ import annotations + +import enum + +from pywayland.protocol_core import ( + Argument, + ArgumentType, + Global, + Interface, + Proxy, + Resource, +) + +from ..wayland import WlSeat +from .zwp_virtual_keyboard_v1 import ZwpVirtualKeyboardV1 + + +class ZwpVirtualKeyboardManagerV1(Interface): + """Virtual keyboard manager + + A virtual keyboard manager allows an application to provide keyboard input + events as if they came from a physical keyboard. + """ + + name = "zwp_virtual_keyboard_manager_v1" + version = 1 + + class error(enum.IntEnum): + unauthorized = 0 + + +class ZwpVirtualKeyboardManagerV1Proxy(Proxy[ZwpVirtualKeyboardManagerV1]): + interface = ZwpVirtualKeyboardManagerV1 + + @ZwpVirtualKeyboardManagerV1.request( + Argument(ArgumentType.Object, interface=WlSeat), + Argument(ArgumentType.NewId, interface=ZwpVirtualKeyboardV1), + ) + def create_virtual_keyboard(self, seat: WlSeat) -> Proxy[ZwpVirtualKeyboardV1]: + """Create a new virtual keyboard + + Creates a new virtual keyboard associated to a seat. + + If the compositor enables a keyboard to perform arbitrary actions, it + should present an error when an untrusted client requests a new + keyboard. + + :param seat: + :type seat: + :class:`~pywayland.protocol.wayland.WlSeat` + :returns: + :class:`~pywayland.protocol.virtual_keyboard_unstable_v1.ZwpVirtualKeyboardV1` + """ + id = self._marshal_constructor(0, ZwpVirtualKeyboardV1, seat) + return id + + +class ZwpVirtualKeyboardManagerV1Resource(Resource): + interface = ZwpVirtualKeyboardManagerV1 + + +class ZwpVirtualKeyboardManagerV1Global(Global): + interface = ZwpVirtualKeyboardManagerV1 + + +ZwpVirtualKeyboardManagerV1._gen_c() +ZwpVirtualKeyboardManagerV1.proxy_class = ZwpVirtualKeyboardManagerV1Proxy +ZwpVirtualKeyboardManagerV1.resource_class = ZwpVirtualKeyboardManagerV1Resource +ZwpVirtualKeyboardManagerV1.global_class = ZwpVirtualKeyboardManagerV1Global diff --git a/src/hhstream_pointer/_protocol/virtual_keyboard_unstable_v1/zwp_virtual_keyboard_v1.py b/src/hhstream_pointer/_protocol/virtual_keyboard_unstable_v1/zwp_virtual_keyboard_v1.py new file mode 100644 index 0000000..cf84ac9 --- /dev/null +++ b/src/hhstream_pointer/_protocol/virtual_keyboard_unstable_v1/zwp_virtual_keyboard_v1.py @@ -0,0 +1,176 @@ +# This file has been autogenerated by the pywayland scanner + +# Copyright © 2008-2011 Kristian Høgsberg +# Copyright © 2010-2013 Intel Corporation +# Copyright © 2012-2013 Collabora, Ltd. +# Copyright © 2018 Purism SPC +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice (including the next +# paragraph) shall be included in all copies or substantial portions of the +# Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. + +from __future__ import annotations + +import enum + +from pywayland.protocol_core import ( + Argument, + ArgumentType, + Global, + Interface, + Proxy, + Resource, +) + + +class ZwpVirtualKeyboardV1(Interface): + """Virtual keyboard + + The virtual keyboard provides an application with requests which emulate + the behaviour of a physical keyboard. + + This interface can be used by clients on its own to provide raw input + events, or it can accompany the input method protocol. + """ + + name = "zwp_virtual_keyboard_v1" + version = 1 + + class error(enum.IntEnum): + no_keymap = 0 + + +class ZwpVirtualKeyboardV1Proxy(Proxy[ZwpVirtualKeyboardV1]): + interface = ZwpVirtualKeyboardV1 + + @ZwpVirtualKeyboardV1.request( + Argument(ArgumentType.Uint), + Argument(ArgumentType.FileDescriptor), + Argument(ArgumentType.Uint), + ) + def keymap(self, format: int, fd: int, size: int) -> None: + """Keyboard mapping + + Provide a file descriptor to the compositor which can be memory-mapped + to provide a keyboard mapping description. + + Format carries a value from the keymap_format enumeration. + + :param format: + keymap format + :type format: + `ArgumentType.Uint` + :param fd: + keymap file descriptor + :type fd: + `ArgumentType.FileDescriptor` + :param size: + keymap size, in bytes + :type size: + `ArgumentType.Uint` + """ + self._marshal(0, format, fd, size) + + @ZwpVirtualKeyboardV1.request( + Argument(ArgumentType.Uint), + Argument(ArgumentType.Uint), + Argument(ArgumentType.Uint), + ) + def key(self, time: int, key: int, state: int) -> None: + """Key event + + A key was pressed or released. The time argument is a timestamp with + millisecond granularity, with an undefined base. All requests regarding + a single object must share the same clock. + + Keymap must be set before issuing this request. + + State carries a value from the key_state enumeration. + + :param time: + timestamp with millisecond granularity + :type time: + `ArgumentType.Uint` + :param key: + key that produced the event + :type key: + `ArgumentType.Uint` + :param state: + physical state of the key + :type state: + `ArgumentType.Uint` + """ + self._marshal(1, time, key, state) + + @ZwpVirtualKeyboardV1.request( + Argument(ArgumentType.Uint), + Argument(ArgumentType.Uint), + Argument(ArgumentType.Uint), + Argument(ArgumentType.Uint), + ) + def modifiers(self, mods_depressed: int, mods_latched: int, mods_locked: int, group: int) -> None: + """Modifier and group state + + Notifies the compositor that the modifier and/or group state has + changed, and it should update state. + + The client should use :func:`WlKeyboard.modifiers() + ` event to synchronize + its internal state with seat state. + + Keymap must be set before issuing this request. + + :param mods_depressed: + depressed modifiers + :type mods_depressed: + `ArgumentType.Uint` + :param mods_latched: + latched modifiers + :type mods_latched: + `ArgumentType.Uint` + :param mods_locked: + locked modifiers + :type mods_locked: + `ArgumentType.Uint` + :param group: + keyboard layout + :type group: + `ArgumentType.Uint` + """ + self._marshal(2, mods_depressed, mods_latched, mods_locked, group) + + @ZwpVirtualKeyboardV1.request(version=1) + def destroy(self) -> None: + """Destroy the virtual keyboard keyboard object + """ + self._marshal(3) + self._destroy() + + +class ZwpVirtualKeyboardV1Resource(Resource): + interface = ZwpVirtualKeyboardV1 + + +class ZwpVirtualKeyboardV1Global(Global): + interface = ZwpVirtualKeyboardV1 + + +ZwpVirtualKeyboardV1._gen_c() +ZwpVirtualKeyboardV1.proxy_class = ZwpVirtualKeyboardV1Proxy +ZwpVirtualKeyboardV1.resource_class = ZwpVirtualKeyboardV1Resource +ZwpVirtualKeyboardV1.global_class = ZwpVirtualKeyboardV1Global diff --git a/src/hhstream_pointer/backend.py b/src/hhstream_pointer/backend.py index c82807d..c7d5a4d 100644 --- a/src/hhstream_pointer/backend.py +++ b/src/hhstream_pointer/backend.py @@ -1,10 +1,27 @@ -"""The pywayland half: one virtual pointer per output, created on demand. +"""The pywayland half: one virtual pointer per output, plus one virtual keyboard. This is the only module that imports pywayland, so everything above it can be tested without a compositor. It implements :class:`hhstream_pointer.ops.PointerSink` and nothing else; the decisions are all next door. -Three things here are load-bearing: +The keyboard half is deliberately unlike the pointer half in three ways, each +forced by the protocol rather than chosen: + +* **One device, not one per output.** ``create_virtual_keyboard(seat)`` takes + no output — a virtual keyboard is seat-global and keys go to whatever has + keyboard focus. There is nothing to aim and nothing to create on demand. +* **The keymap is uploaded once**, after connect and before the socket is + listening, because ``key`` or ``modifiers`` before ``keymap`` is the protocol + error ``no_keymap`` and kills the connection. A *second* upload is not a + refresh either: Hyprland replaces its XKB state without walking the keys it + thinks are down, so re-uploading under a held modifier strands it. +* **A missing global is survivable.** ``ManagerTooOld`` aborts start-up for + the *pointer* manager because a version-1 pointer aims at the whole desktop + and every click would land somewhere wrong. A compositor with no + ``zwp_virtual_keyboard_manager_v1`` still gets a working cursor, so the + keyboard is simply absent and the keyboard ops refuse. + +Three things on the pointer side are load-bearing: * ``zwlr_virtual_pointer_manager_v1`` is bound at **version 2** and pointers are created with :func:`create_virtual_pointer_with_output`. Version 1's @@ -32,7 +49,9 @@ from pathlib import Path from pywayland.client import Display from pywayland.protocol.wayland import WlOutput, WlSeat +from ._protocol.virtual_keyboard_unstable_v1 import ZwpVirtualKeyboardManagerV1 from ._protocol.wlr_virtual_pointer_unstable_v1 import ZwlrVirtualPointerManagerV1 +from .keymap import XKB_V1 log = logging.getLogger("hhstream_pointer.backend") @@ -46,6 +65,11 @@ OUTPUT_VERSION = 4 #: The manager version that first carried ``create_virtual_pointer_with_output``. MANAGER_VERSION = 2 +#: ``zwp_virtual_keyboard_manager_v1`` is version 1 and only version 1. +#: Measured on the running compositor by ``tests/keyboard_probe.py``, not +#: assumed: the plan's gate was that the global exists under this name. +KEYBOARD_MANAGER_VERSION = 1 + class CompositorUnavailable(Exception): """No display to connect to, or the connection died. Fatal; do not guess.""" @@ -71,6 +95,16 @@ class OutputUnknown(Exception): """The compositor advertises no output by that name.""" +class KeyboardUnavailable(Exception): + """No virtual keyboard: the global is absent, or the keymap never went up. + + Not fatal, and not :class:`CompositorUnavailable`: the display is fine and + the cursor still works. :mod:`hhstream_pointer.ops` asks + :meth:`WaylandSink.has_keyboard` instead of catching this, so the question + can be answered without provoking it — which is what ``release_all`` needs. + """ + + def find_wayland_display(runtime_dir: Path) -> str: """The name of the compositor's socket inside its runtime directory. @@ -118,6 +152,9 @@ class WaylandSink: self._manager = None self._manager_version = 0 self._output_version = 0 + self._keyboard_manager = None + self._keyboard_manager_version = 0 + self._keyboard = None #: registry global id -> output self._outputs: dict[int, _Output] = {} #: output name -> virtual pointer proxy @@ -162,16 +199,64 @@ class WaylandSink: "to learn output names" ) log.info( - "connected to %s: manager v%d, %d output(s)", + "connected to %s: manager v%d, %d output(s), keyboard manager %s", name, self._manager_version, len(self._outputs), + f"v{self._keyboard_manager_version}" if self._keyboard_manager else "absent", ) + def upload_keymap(self, text: str) -> None: + """Create the one virtual keyboard and give it ``text``, once. + + Called between :meth:`connect` and the socket being listened on, which + is where the ordering rule lives: a listening socket is a promise that + the device works, and ``key`` before ``keymap`` is a protocol error + that kills the connection rather than returning an error we could + report. + + No-op when the compositor advertises no keyboard manager. + """ + + if self._keyboard_manager is None: + log.warning( + "no zwp_virtual_keyboard_manager_v1: the cursor will work and every " + "keyboard op will be refused" + ) + return + self._keyboard = self._keyboard_manager.create_virtual_keyboard(self._seat) + payload = text.encode("utf-8") + b"\0" + fd = os.memfd_create("hhstream-keymap", 0) + try: + os.ftruncate(fd, len(payload)) + with os.fdopen(os.dup(fd), "wb", closefd=True) as handle: + handle.write(payload) + # The size on the wire **includes the NUL**. Hyprland maps exactly + # this many bytes and hands the pointer to + # `xkb_keymap_new_from_string`, which wants a C string, so a size + # of `len(text)` reads off the end of the mapping -- and the + # symptom is a keymap that silently will not compile, which looks + # from here exactly like a compositor that has no keyboard at all. + self._keyboard.keymap(XKB_V1, fd, len(payload)) + # A round trip, not a flush: the compositor has to have received + # and mapped the fd before we close our end of it. + self._sync() + finally: + os.close(fd) + # Once, here, and the reason is Hyprland-specific: `destroy` of a + # virtual keyboard does not clear the modifier mask (measured, see + # tests/README-keyboard-probe.md), and a client keeps the last + # `wl_keyboard.modifiers` it was sent. Starting from a known zero means + # a previous driver's stuck Shift is not inherited. + self._keyboard.modifiers(0, 0, 0, 0) + self._flush() + log.info("uploaded a %d-byte keymap to the virtual keyboard", len(payload)) + def close(self) -> None: if self._display is None: return self._pointers.clear() + self._keyboard = None try: self._display.disconnect() finally: @@ -201,8 +286,35 @@ class WaylandSink: self._pointer(output).frame() self._flush() + def has_keyboard(self) -> bool: + return self._keyboard is not None + + def key(self, code: int, state: int) -> None: + """An evdev code and a key state. Flushed, because there is no frame. + + ``zwp_virtual_keyboard_v1`` has no end-of-gesture request, so a key + that waited for one would never be delivered. The flush is the same + one every pointer method above does. + """ + + self._require_keyboard().key(_now_ms(), code, state) + self._flush() + + def modifiers(self, depressed: int, latched: int, locked: int, group: int) -> None: + self._require_keyboard().modifiers(depressed, latched, locked, group) + self._flush() + # -- internals -------------------------------------------------------- + def _require_keyboard(self): + keyboard = self._keyboard + if keyboard is None: + raise KeyboardUnavailable( + "no virtual keyboard: the compositor advertises no " + "zwp_virtual_keyboard_manager_v1" + ) + return keyboard + def _pointer(self, output: str): existing = self._pointers.get(output) if existing is not None: @@ -247,6 +359,11 @@ class WaylandSink: self._manager_version = version if version >= MANAGER_VERSION: self._manager = registry.bind(global_id, ZwlrVirtualPointerManagerV1, MANAGER_VERSION) + elif interface == ZwpVirtualKeyboardManagerV1.name: + self._keyboard_manager_version = version + self._keyboard_manager = registry.bind( + global_id, ZwpVirtualKeyboardManagerV1, KEYBOARD_MANAGER_VERSION + ) elif interface == WlSeat.name and self._seat is None: self._seat = registry.bind(global_id, WlSeat, min(version, WlSeat.version)) elif interface == WlOutput.name: diff --git a/src/hhstream_pointer/keymap.py b/src/hhstream_pointer/keymap.py new file mode 100644 index 0000000..1b07f52 --- /dev/null +++ b/src/hhstream_pointer/keymap.py @@ -0,0 +1,383 @@ +"""Keysym names and text to ``(evdev code, modifier mask)``, via one XKB keymap. + +This is the only module that imports xkbcommon, the way :mod:`.backend` is the +only one that imports pywayland. Everything above it — :mod:`.ops`, the broker, +the CLI — speaks keysym *names*, which is the same division +:mod:`.buttons` draws for the pointer: names on our sockets, evdev integers only +on the Wayland request. + +``buttons.py`` can be a hand-written table because +``zwlr_virtual_pointer_v1.button`` takes those codes directly and there are +eight of them. Keysyms cannot: which code produces ``z`` and which modifiers +have to be held to get it are properties of *the layout we uploaded*, and a +second table beside the keymap would be a table that can disagree with it. So +every answer here is read out of the compiled keymap. + +Three decisions worth stating, because each one has a wrong version that looks +right: + +* **The mask, not a Shift keycode, is what makes a capital.** Hyprland's + virtual-keyboard device does not run ``updateXkbStateWithKey`` + (``devices/VirtualKeyboard.cpp`` vs ``devices/Keyboard.cpp`` at v0.56.2), so a + virtual ``key(KEY_LEFTSHIFT)`` changes no modifier state and produces no + ``wl_keyboard.modifiers``. The mask has to be sent explicitly, and sending + *both* a mask and a synthetic Shift key is how a toolkit applies Shift twice. + :meth:`Keymap.resolve_text` therefore returns a mask per character and never + a Shift action. +* **A modifier is whatever this keymap says is one.** Not a name list: a + layout where ``@`` is a level-3 symbol needs ``ISO_Level3_Shift``'s mask, and + a Shift-only special case would quietly produce the wrong character. The set + is computed by pressing each key in a throwaway XKB state and reading the + depressed mask back, which on ``us``/``pc105`` yields exactly the expected + names (see :data:`EXPECTED_MODIFIERS`). +* **A lock is not a modifier.** ``Caps_Lock`` and ``Num_Lock`` report a + *locked* mask, and a ``type`` performed while one of them is held would + produce a case we did not ask for, so ``type`` refuses rather than guessing. + +The whole string is resolved before anything is emitted, so an unmappable +character fails the request instead of typing a prefix. Errors carry the +scalar *index*, never the character and never the string: the typed text is a +password as often as not, and :class:`Rejected` messages reach the driver's log. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +#: ``wl_keyboard.keymap_format.xkb_v1``. Written down rather than read off the +#: generated protocol module because the only copy of +#: ``virtual-keyboard-unstable-v1.xml`` available here (Hyprland's) *names* +#: ``keymap_format`` in the ``keymap`` request's description and never defines +#: the enum. See ``_protocol/regenerate.py``. +XKB_V1 = 1 + +#: A Wayland/evdev keycode is the XKB keycode minus 8. ``wl_keyboard.key`` and +#: ``zwp_virtual_keyboard_v1.key`` both carry the evdev value; xkbcommon's +#: tables are indexed by the XKB one. +EVDEV_OFFSET = 8 + +#: The largest ``type`` we accept, in Unicode scalars — not bytes. Scalars +#: because that is what the caller counts and what the resolver walks; a byte +#: cap would let 4096 emoji through on one side of the wire and not the other. +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"} + +#: What the detection below **measures** on ``us``/``pc105``. Not used to +#: decide anything — the keymap decides — but asserted in the tests, because a +#: detection that silently returned an empty set would make every ``type`` look +#: modifier-free and every chord a no-op, and nothing else would notice. +#: +#: Shorter than the canonical list of modifier keysyms, and deliberately: the +#: review's set also names ``Meta_L/R`` and ``Hyper_L/R``, and **no keycode on +#: this layout carries them**, so a resolver that claimed them would be +#: claiming keys it cannot press. That is the whole argument for measuring +#: rather than listing. +EXPECTED_MODIFIERS = frozenset( + { + "Shift_L", + "Shift_R", + "Control_L", + "Control_R", + "Alt_L", + "Alt_R", + "Super_L", + "Super_R", + "ISO_Level3_Shift", + "ISO_Level5_Shift", + } +) + +#: Keysyms this layout treats as locks rather than modifiers. ``type`` refuses +#: while one of these is held; see :meth:`Keymap.is_modifier`. +EXPECTED_LOCKS = frozenset({"Caps_Lock", "Num_Lock"}) + + +class KeymapError(Exception): + """The layout itself is unusable. Fatal at start-up, exit 2.""" + + +class UnknownKey(Exception): + """A keysym name, or a character, that this layout cannot produce. + + A caller error, not a compositor failure: it carries no compositor state + and the same request will fail the same way forever. The driver answers it + with ``kind: invalid_argument`` so the broker can report exit 2 rather than + exit 10. + """ + + +@dataclass(frozen=True) +class Action: + """One keystroke: an evdev code and the modifier mask it needs. + + ``mask`` is what must be *depressed* for this keycode to produce the wanted + keysym — 0 for ``a``, Shift's bit for ``A``, LevelThree's for a ``de`` + ``@``. It is not a key to press; see the module docstring. + """ + + code: int + mask: int + #: The keysym name, for the held-key record and for log lines. A name and + #: not the character: `keys` on `pointer.state` reads as names everywhere. + name: str + + +def build( + *, + layout: str = "us", + model: str = "pc105", + variant: str = "", + options: str = "", + rules: str = "evdev", +) -> "Keymap": + """Compile one keymap, or raise :class:`KeymapError`. + + ``rules`` is an argument rather than a constant only so a test can prove + the failure path; there is deliberately no flag for it (the review: + "Do not add a `rules` option; the driver hardcodes `evdev`"). + """ + + 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 + # `modifiers` request and has no group-switch keysym, so the second + # group would be unreachable and every caller asking for a Cyrillic + # character would get a silent Latin one. + raise KeymapError( + f"layout {layout!r} names more than one group; v1 uploads a single " + "group and always sends group 0, so the others would be unreachable" + ) + try: + from xkbcommon import xkb + except ImportError as exc: # pragma: no cover - the dependency is not optional + raise KeymapError(f"xkbcommon is unavailable: {exc}") from None + + try: + compiled = xkb.Context().keymap_new_from_names( + rules=rules, model=model, layout=layout, variant=variant, options=options + ) + except Exception as exc: + # xkbcommon logs its own multi-line complaint to stderr and then hands + # back a bare failure, so the layout is named again here: the operator + # set one string and that is what they need to see. + raise KeymapError( + f"xkbcommon will not compile rules={rules!r} model={model!r} " + f"layout={layout!r} variant={variant!r} options={options!r}: {exc}" + ) from None + return Keymap(compiled, xkb) + + +class Keymap: + """A compiled layout, plus the two lookups the driver needs from it. + + Built once, at start-up, and uploaded once. Not rebuilt per request: a + second ``keymap`` upload replaces the compositor's XKB state without + walking its set of held keys, so re-uploading under a held modifier is how + a chord gets stuck. + """ + + def __init__(self, compiled, xkb) -> None: + self._keymap = compiled + self._xkb = xkb + #: keysym name -> Action. Built eagerly: the whole point is that a + #: lookup cannot disagree with the uploaded keymap, and a lazy table + #: would be a second source of truth with a cache in front of it. + self._by_name: dict[str, Action] = {} + #: keysym number -> Action, which is what a character resolves through. + self._by_keysym: dict[int, Action] = {} + #: keysym name -> the mask this key *contributes* when held down. + self._modifier_masks: dict[str, int] = {} + #: keysym names that lock rather than modify (``Caps_Lock``). + self._locks: set[str] = set() + self._index() + + # -- the table -------------------------------------------------------- + + def _index(self) -> None: + keymap, xkb = self._keymap, self._xkb + #: (popcount, mask, keycode) -> the best candidate for a keysym, so a + #: keysym reachable both unshifted and shifted resolves unshifted, and + #: a tie between two keycodes resolves to the lower one. Deterministic + #: on purpose: "which keycode is `1`" must not depend on dict order. + best: dict[int, tuple[tuple[int, int, int], Action]] = {} + for keycode in range(keymap.min_keycode(), keymap.max_keycode() + 1): + evdev = keycode - EVDEV_OFFSET + if evdev < 0: + continue + self._index_modifier(keycode, evdev) + # Group 0 only: v1 is a single group (plan §4), so a level table + # read from another group would describe keys we can never reach. + for level in range(keymap.num_levels_for_key(keycode, 0)): + masks = keymap.key_get_mods_for_level(keycode, 0, level) or [0] + mask = min(masks, key=lambda m: (bin(m).count("1"), m)) + for keysym in keymap.key_get_syms_by_level(keycode, 0, level): + name = xkb.keysym_get_name(keysym) + if not name: + continue + rank = (bin(mask).count("1"), mask, keycode) + current = best.get(keysym) + if current is not None and current[0] <= rank: + continue + best[keysym] = (rank, Action(code=evdev, mask=mask, name=name)) + + for keysym, (_rank, action) in best.items(): + self._by_keysym[keysym] = action + # First name wins, and the names are unique per keysym because + # `keysym_get_name` is a function of the keysym alone. + self._by_name.setdefault(action.name, action) + + def _index_modifier(self, keycode: int, evdev: int) -> None: + """Record what holding this key does to the modifier masks. + + Measured rather than listed: press the key in a throwaway state and + read the serialised masks back. A key with a depressed mask and no + locked mask is a modifier; one with a locked mask is a lock, and the + two are not interchangeable for ``type``. + """ + + xkb = self._xkb + state = self._keymap.state_new() + state.update_key(keycode, xkb.XKB_KEY_DOWN) + depressed = state.serialize_mods(xkb.XKB_STATE_MODS_DEPRESSED) + locked = state.serialize_mods(xkb.XKB_STATE_MODS_LOCKED) + if not depressed and not locked: + return + for level in range(self._keymap.num_levels_for_key(keycode, 0)): + for keysym in self._keymap.key_get_syms_by_level(keycode, 0, level): + name = xkb.keysym_get_name(keysym) + if not name: + continue + if locked: + self._locks.add(name) + else: + self._modifier_masks.setdefault(name, depressed) + + # -- what the driver asks --------------------------------------------- + + def text(self) -> str: + """The keymap as the XKB text the ``keymap`` request wants uploaded.""" + + return self._keymap.get_as_bytes().decode("utf-8") + + def resolve_name(self, name: str) -> Action: + """One keysym name to an :class:`Action`, or :class:`UnknownKey`. + + The same resolver named keys and characters both go through, so + ``keyboard key z`` and ``keyboard type z`` cannot disagree about which + keycode ``z`` is on a ``de`` layout. + """ + + if not isinstance(name, str) or not name: + raise UnknownKey("a key name is required") + if name.startswith("dead_"): + # Named by many layouts and typeable by none of them in one event: + # a dead key is half of a compose sequence, and v1 does not emit + # the other half. Refused rather than sent, because sending it + # arms the next keystroke in the focused application. + raise UnknownKey( + f"{name!r} is a dead key; v1 does not emit compose sequences" + ) + action = self._by_name.get(name) + if action is not None: + return action + # Fall back through the keysym number so an alias (`Return` vs + # `KP_Enter` is not one, but `XF86...` spellings and `0x…` forms are) + # resolves to the same action rather than looking unknown. + keysym = self._xkb.keysym_from_name(name) + action = self._by_keysym.get(keysym) if keysym else None + if action is None: + raise UnknownKey( + f"{name!r} is not on the uploaded keymap; it has no keycode under " + "this layout" + ) + return action + + def is_modifier(self, name: str) -> bool: + """True for a key that contributes to the depressed mask. + + ``Caps_Lock`` is **not** one of these: it locks, and a ``type`` while a + lock is held would produce a case nobody asked for. + """ + + return name in self._modifier_masks + + def modifier_mask(self, name: str) -> int: + """The mask this key contributes while held, or 0 if it contributes none.""" + + return self._modifier_masks.get(name, 0) + + def modifier_names(self) -> frozenset[str]: + """Every keysym name this layout treats as a modifier. For tests and help.""" + + return frozenset(self._modifier_masks) + + def lock_names(self) -> frozenset[str]: + """Keysym names that lock (``Caps_Lock``, ``Num_Lock``).""" + + return frozenset(self._locks) + + def resolve_text(self, text: str) -> list[Action]: + """A whole string to actions, or :class:`UnknownKey` naming the index. + + Resolved completely before returning, which is the property the caller + depends on: a string whose fifth character is unmappable emits nothing + at all rather than four characters and an error. An empty string is + an empty list and not an error — it is a no-op the caller may well have + computed. + """ + + if not isinstance(text, str): + raise UnknownKey("text must be a string") + if len(text) > MAX_TEXT_SCALARS: + raise UnknownKey( + f"text is {len(text)} scalars, over the {MAX_TEXT_SCALARS} limit" + ) + actions: list[Action] = [] + for index, character in enumerate(text): + actions.append(self._resolve_character(character, index)) + return actions + + def _resolve_character(self, character: str, index: int) -> Action: + named = CONTROL_KEYSYMS.get(character) + if named is not None: + try: + return self.resolve_name(named) + except UnknownKey: + raise UnknownKey( + f"scalar {index} needs keysym {named!r}, which this layout " + "does not carry" + ) from None + keysym = _keysym_for(character) + action = self._by_keysym.get(keysym) + if action is None: + # The index and the codepoint, never the character: this message + # is logged, and the string it came from is often a password. + raise UnknownKey( + f"scalar {index} (U+{ord(character):04X}) is not typeable on the " + "uploaded layout" + ) + if action.name.startswith("dead_"): + raise UnknownKey( + f"scalar {index} (U+{ord(character):04X}) resolves to the dead key " + f"{action.name!r}; v1 does not emit compose sequences" + ) + return action + + +def _keysym_for(character: str) -> int: + """The X keysym for one Unicode scalar. + + The two-range rule from ``xproto``: Latin-1 is its own keysym value, and + everything else is ``0x01000000 + codepoint``. Not ``xkb.keysym_from_name`` + with a one-character string, which resolves ``"a"`` by *name* and would + make the digit ``1`` and the keysym ``1`` the same lookup by accident. + """ + + codepoint = ord(character) + if 0x20 <= codepoint <= 0x7E or 0xA0 <= codepoint <= 0xFF: + return codepoint + return 0x01000000 + codepoint diff --git a/src/hhstream_pointer/ops.py b/src/hhstream_pointer/ops.py index 594a4c0..f2e4cff 100644 --- a/src/hhstream_pointer/ops.py +++ b/src/hhstream_pointer/ops.py @@ -6,18 +6,33 @@ a rejected request is answered, never fatal, because the broker is a long-lived peer and dropping its connection would cost it a cursor it still holds a lease on. -This module is the whole of the driver's logic and it touches no Wayland. It -speaks to a :class:`PointerSink` — "send this to the virtual pointer bound to -*this* output" — which is the one thing pywayland is needed for. That seam is -why the dispatcher can be tested without a compositor, and the test suite does -exactly that. +This module is the whole of the driver's logic and it touches no Wayland and no +xkbcommon. It speaks to a :class:`PointerSink` — "send this to the virtual +pointer bound to *this* output", plus "send this to the one virtual keyboard" — +and to a :class:`Keymap`, which turns a keysym name or a string into evdev +codes and modifier masks. Those two seams are why the dispatcher can be tested +without a compositor and without a layout, and the test suite does exactly +that. -The dispatcher keeps two pieces of *device* state, which is not lease state: +The dispatcher keeps three pieces of *device* state, which is not lease state: * the output of the last ``warp``, because ``button`` and ``frame`` carry no output of their own and there is only one cursor to aim; * which buttons are down and on which pointer, because ``release_all`` has to - report what it lifted and must lift it through the pointer it went down on. + report what it lifted and must lift it through the pointer it went down on; +* which keys are down, in press order, because ``release_all`` has to lift + those too — and, unlike buttons, has to put the modifier mask back to zero + afterwards. A virtual key-up does not clear the mask: Hyprland's virtual + keyboard never runs ``updateXkbStateWithKey``, so the mask is only ever what + we last said it was. + +**There is no keyboard output and no keyboard frame.** ``key`` and ``type`` +deliberately do not call :meth:`Dispatcher._aimed`: a virtual keyboard is +seat-global, there is nothing to aim, and a ``type`` that first demanded a warp +would fail for a caller that only ever wanted to type. Nor is there an +end-of-gesture ``frame`` — ``zwp_virtual_keyboard_v1`` has none, and a key +queued until one would never arrive. The sink flushes each request the way it +already flushes each pointer request. It keeps no notion of who is allowed to ask. That is the lease, and the lease lives in the broker. @@ -28,6 +43,12 @@ from __future__ import annotations from typing import Any, Protocol from . import buttons +# A pure exception class, and the one import that crosses the keymap seam. It +# costs nothing: `keymap.py` imports xkbcommon inside `build()`, never at module +# level, so this file still pulls in neither xkbcommon nor pywayland. The +# alternative -- catching `Exception` around a resolver call -- would report a +# genuine bug in this process as the caller's bad keysym. +from .keymap import UnknownKey class PointerSink(Protocol): @@ -49,18 +70,86 @@ class PointerSink(Protocol): def frame(self, output: str) -> None: """Commit the queued events. Nothing is delivered until this.""" + def has_keyboard(self) -> bool: + """Whether a virtual keyboard was created at start-up. + + False is a normal state, not a failure: a compositor that does not + advertise ``zwp_virtual_keyboard_manager_v1`` still gets a working + cursor, and the keyboard ops answer ``ok: false`` instead. It exists + as a question rather than an exception because ``release_all`` has to + know not to try. + """ + + def key(self, code: int, state: int) -> None: + """An evdev key code and a ``wl_keyboard.key_state``. No output.""" + + def modifiers(self, depressed: int, latched: int, locked: int, group: int) -> None: + """Set the seat's modifier masks. Not derived from :meth:`key`.""" + + +class Keymap(Protocol): + """Keysym names and text to ``(evdev code, mask)``. Implemented by :mod:`.keymap`. + + The same shape as :class:`PointerSink`: a seam, so this module holds no + layout knowledge. Everything it raises is a caller error — see + :class:`Rejected` and the ``kind`` it carries. + """ + + def resolve_name(self, name: str): ... + + def resolve_text(self, text: str) -> list: ... + + def is_modifier(self, name: str) -> bool: ... + + def modifier_mask(self, name: str) -> int: ... + + +#: ``kind`` for a rejection the *caller* caused: a keysym this layout does not +#: have, an unmappable character, a bad state word, a string over the cap. The +#: broker maps it to ``invalid_argument`` (exit 2). Without it every refusal +#: would arrive as ``driver_refused`` (exit 10), which says "the compositor +#: failed" about a typo — see the review's change 1. +KIND_INVALID = "invalid_argument" + +#: ``kind`` for everything else: an unknown op, no aimed output, no keyboard +#: global. The broker maps it to ``driver_refused`` (exit 10), which is what +#: the button and axis paths already do and what their tests already assert. +KIND_REFUSED = "refused" + class Rejected(Exception): - """The request was understood and refused; the text goes to the broker.""" + """The request was understood and refused; the text goes to the broker. + + ``kind`` is the machine-readable half. The text is for a human and is + never trusted by the broker to carry meaning, which is why a token exists + at all: "unmappable character" and "the compositor has no keyboard" are + different exit codes and must not be told apart by reading English. + """ + + def __init__(self, message: str, *, kind: str = KIND_REFUSED) -> None: + super().__init__(message) + self.kind = kind class Dispatcher: - def __init__(self, sink: PointerSink) -> None: + def __init__(self, sink: PointerSink, keymap: Keymap | None = None) -> None: self._sink = sink + #: ``None`` when the process started without a usable layout. Keyboard + #: ops then refuse; pointer ops are untouched, which is the whole point + #: of the argument being optional. + self._keymap = keymap self._output: str | None = None #: 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``. + self._keys: 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 + #: sending one at all would raise and stop the buttons being lifted. + self._mask_touched = False def handle(self, request: Any) -> dict[str, Any]: """One request object to one response object. Never raises.""" @@ -68,7 +157,7 @@ class Dispatcher: try: return self._handle(request) except Rejected as exc: - return {"ok": False, "error": str(exc)} + return {"ok": False, "error": str(exc), "kind": exc.kind} def _handle(self, request: Any) -> dict[str, Any]: if not isinstance(request, dict): @@ -149,13 +238,102 @@ class Dispatcher: self._sink.frame(self._aimed()) return {"ok": True} + def _op_key(self, request: dict) -> dict[str, Any]: + """One keysym down or up. + + No output and no ``frame``: see the module docstring. A ``down`` of a + key the layout calls a modifier also sends the mask, because a virtual + ``key`` does not change Hyprland's modifier state — and the mask is + remembered so ``release_all`` can undo both halves. + """ + + name = request.get("key") + if not isinstance(name, str) or not name: + raise Rejected("'key' must be a keysym name", kind=KIND_INVALID) + state = request.get("state") + if state not in ("down", "up"): + raise Rejected( + f"'state' must be 'down' or 'up', got {state!r}", kind=KIND_INVALID + ) + keymap = self._require_keymap() + action = _resolved(keymap.resolve_name, name) + + if state == "down": + self._sink.key(action.code, buttons.STATES["down"]) + contribution = keymap.modifier_mask(name) if keymap.is_modifier(name) else 0 + self._keys[name] = contribution + if contribution: + self._set_mask(self._baseline()) + return {"ok": True, "keys": list(self._keys), "lifted": []} + + if name not in self._keys: + # Reported rather than invented, the way `unpress` reports a button + # that was never down: a duplicate `up` is a caller that lost + # 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)) + self._sink.key(action.code, buttons.STATES["up"]) + if was_modifier: + self._set_mask(self._baseline()) + return {"ok": True, "keys": list(self._keys), "lifted": [name]} + + def _op_type(self, request: dict) -> dict[str, Any]: + """A whole string, as key pairs with the mask each character needs. + + Resolved completely before the first sink call, so an unmappable + character emits nothing at all. Explicit modifier holds are the + *baseline*: each character's mask is ORed onto them, and the baseline + is restored afterwards, so ``down Control_L`` then ``type c`` is Ctrl+C + and Control is still down when this returns. + + ``modifiers`` is sent before every character and once more at the end, + rather than only when the mask changes. Three requests per character + is nothing on a local socket, and the alternative keeps a running + "what did we last send" that is wrong exactly once — after which every + capital in the string is a lower-case letter. + """ + + text = request.get("text") + if not isinstance(text, str): + raise Rejected("'text' must be a string", kind=KIND_INVALID) + held = [name for name, mask in self._keys.items() if not mask] + if held: + # Refused rather than typed around: a character sent while `a` is + # down arrives in an application that believes `a` is still being + # held, and the auto-repeat it has already started does not stop. + raise Rejected( + f"a non-modifier key is held ({', '.join(held)}); release it before " + "typing", + kind=KIND_INVALID, + ) + keymap = self._require_keymap() + actions = _resolved(keymap.resolve_text, text) + + baseline = self._baseline() + for action in actions: + self._set_mask(baseline | action.mask) + self._sink.key(action.code, buttons.STATES["down"]) + self._sink.key(action.code, buttons.STATES["up"]) + if actions: + # Back to the baseline, so a held Control survives and a Shift we + # synthesised for one capital does not. + self._set_mask(baseline) + return {"ok": True, "keys": list(self._keys)} + def _op_pressed(self, request: dict) -> dict[str, Any]: - return {"ok": True, "buttons": list(self._pressed)} + return {"ok": True, "buttons": list(self._pressed), "keys": list(self._keys)} def _op_release_all(self, request: dict) -> dict[str, Any]: """Lift everything. The broker calls this when a lease expires, so it must not depend on an aim: each button is lifted through the pointer it - was pressed on, even if the cursor has since been warped elsewhere.""" + was pressed on, even if the cursor has since been warped elsewhere. + + Buttons first, then keys in press order, then one zeroed ``modifiers`` + — and the mask is the part that is easy to leave out. A virtual + key-up does not clear it, so a lease that ended with Shift down would + hand the next holder a keyboard where every letter is a capital. + """ lifted = list(self._pressed) outputs = list(dict.fromkeys(self._pressed.values())) @@ -164,13 +342,32 @@ class Dispatcher: self._pressed.clear() for output in outputs: self._sink.frame(output) - return {"ok": True, "lifted": lifted} + + lifted_keys: list[str] = [] + if self._keys and self._keymap is not None: + # `_require_keymap` deliberately not used: it raises, and this op is + # the whole of expiry (`SessionManager._expire_pointer` calls it + # once). A refusal here would abandon the lift it has already done. + for name in list(self._keys): + self._sink.key(self._keymap.resolve_name(name).code, buttons.STATES["up"]) + lifted_keys = list(self._keys) + self._keys.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 + # `release_all` is the whole of expiry (`_expire_pointer`), so an + # exception here would leave a mouse button down. + self._sink.modifiers(0, 0, 0, 0) + self._mask_touched = False + return {"ok": True, "lifted": lifted, "lifted_keys": lifted_keys} _ops = { "warp": _op_warp, "button": _op_button, "axis": _op_axis, "frame": _op_frame, + "key": _op_key, + "type": _op_type, "pressed": _op_pressed, "release_all": _op_release_all, } @@ -182,6 +379,51 @@ class Dispatcher: raise Rejected("no output is aimed; warp before button or frame") return self._output + def _require_keymap(self) -> Keymap: + """The layout, or a refusal that is *not* a usage error. + + No keymap means the process started without a keyboard: either the + compositor advertises no ``zwp_virtual_keyboard_manager_v1`` or the + upload failed. Either way the caller's request was fine, so this + carries :data:`KIND_REFUSED` and the broker reports exit 10. + """ + + if self._keymap is None or not self._sink.has_keyboard(): + raise Rejected( + "this driver has no virtual keyboard; the compositor advertises no " + "zwp_virtual_keyboard_manager_v1, or no keymap was uploaded", + kind=KIND_REFUSED, + ) + return self._keymap + + def _baseline(self) -> int: + """The mask the explicitly held modifier keys add up to.""" + + mask = 0 + for contribution in self._keys.values(): + mask |= contribution + return mask + + def _set_mask(self, depressed: int) -> None: + self._sink.modifiers(depressed, 0, 0, 0) + if depressed: + self._mask_touched = True + + +def _resolved(resolve, argument): + """Call a keymap resolver, turning its refusal into a usage-level one. + + One place, so the ``kind`` is the same for a bad keysym and a bad + character, and so the resolver's own message survives — it is the one that + names the scalar *index* rather than the character, which is what keeps a + typed password out of the driver's log. + """ + + try: + return resolve(argument) + except UnknownKey as exc: + raise Rejected(str(exc), kind=KIND_INVALID) from None + def _require_output(request: dict) -> str: output = request.get("output") diff --git a/src/hhstreamd/pointer.py b/src/hhstreamd/pointer.py index e293587..b075920 100644 --- a/src/hhstreamd/pointer.py +++ b/src/hhstreamd/pointer.py @@ -70,6 +70,10 @@ class LeaseOutcome: bookmark: Bookmark | None reason: str buttons_lifted: list[str] + #: Keysym names this lease believed were down. Beside ``buttons_lifted`` + #: and for the same reason: both are the *lease's* mirror, and the driver's + #: own answer is what the broker actually reports. + keys_lifted: list[str] = field(default_factory=list) @dataclass @@ -85,6 +89,11 @@ class _Held: #: Insertion-ordered set: a dict with ignored values. Order is kept so a #: forced release lifts buttons in the order they went down. buttons: dict[str, None] = field(default_factory=dict) + #: The same pattern for keysym names. A dict and not a ``keyboard`` + #: boolean, which is what PLAN §6.7 proposed: a flag cannot say to lift + #: ``Control_L`` and not ``a``, and order matters for the same reason it + #: does for buttons. + keys: dict[str, None] = field(default_factory=dict) def info(self) -> LeaseInfo: return LeaseInfo( @@ -163,15 +172,23 @@ class PointerLease: bookmark=held.bookmark, reason=reason, buttons_lifted=list(held.buttons), + keys_lifted=list(held.keys), ) def expire(self) -> LeaseInfo | None: """Force-release a lease past its TTL or its hard cap. Returns what was released, or ``None`` if nothing was due. The caller - lifts the buttons on the driver: this object's button set is a mirror - of the driver's, never the authority, so it is simply dropped here and - ``release_all`` on the driver is what actually ungrabs the mouse. + lifts the buttons *and the keys* on the driver: this object's sets are + a mirror of the driver's, never the authority, so they are simply + dropped here and ``release_all`` on the driver is what actually ungrabs + the mouse and lets the keys up. + + Deliberately still :class:`LeaseInfo` and not a richer return + (CONTRACT-sessions.md §3.3): callers that want to know what was held + read :meth:`pressed` and :meth:`keys_pressed` *first*. Widening it + would make the ordering rule optional, and the ordering rule is the + only thing stopping a key from being forgotten before it is lifted. """ held = self._held @@ -213,6 +230,33 @@ class PointerLease: return [] if self._held is None else list(self._held.buttons) + # -- keys ------------------------------------------------------------- + # + # Mirrors the three above exactly, and shares their rule: the lease's set + # is a mirror of the driver's and never the authority. The driver's is the + # one the compositor saw, and on this compositor a key the driver forgot is + # worse than a button it forgot -- `InputManager::onKeyboardKey` drops the + # *next* press of a code still in its `m_pressed`, so a leaked key makes + # that key dead rather than merely stuck. + + def press_key(self, session_id: str, key: str) -> None: + self._holder(session_id).keys[key] = None + + def unpress_key(self, session_id: str, key: str) -> list[str]: + """Lift one key. Returns what actually came up — ``[]`` if it was + never down, so a duplicate release is reported rather than invented.""" + + keys = self._holder(session_id).keys + if key not in keys: + return [] + del keys[key] + return [key] + + def keys_pressed(self) -> list[str]: + """Keysym names currently down, oldest first. Empty when unheld.""" + + return [] if self._held is None else list(self._held.keys) + # -- bookmark --------------------------------------------------------- def mark(self, session_id: str, lease_id: str, bookmark: Bookmark) -> None: diff --git a/tests/pointer/test_driver_flags.py b/tests/pointer/test_driver_flags.py new file mode 100644 index 0000000..ec05f96 --- /dev/null +++ b/tests/pointer/test_driver_flags.py @@ -0,0 +1,144 @@ +"""The driver's XKB flags — the only path a layout has to the uploaded keymap. + +This file exists where a `tests/sessions/unit/test_settings.py` case would have +gone, and that is the point. The broker's TOML is read by `hhstreamd` for its +lease numbers; `hhstream-pointer` is a different unit and never opens that +file. So a `[keyboard]` table there would be a setting an operator could change +with no effect at all, and a test asserting its default would be green while +every injected key stayed on `us`. + +The layout therefore arrives as `--xkb-layout`, and these are the assertions +about that flag: what it defaults to, that a bad value is exit **2**, and that +a bad value is exit 2 **without the compositor being touched** — because a +layout xkbcommon will not compile is the operator's typo, and reporting it as +exit 10 sends them to the wrong unit. +""" + +from __future__ import annotations + +import pytest + +from hhstream_pointer import __main__ as entry + + +class _Unreached(Exception): + """Raised if the Wayland side is reached when it should not have been.""" + + +class _RefusingSink: + """A sink that fails the test if anything asks it to talk to a compositor. + + The review asked for an injected connect that can be asserted *not* to have + been called; this is that, as a type rather than a flag, so a future code + path that connects earlier fails loudly instead of silently reordering + start-up. + """ + + instances = 0 + + def __init__(self, runtime_dir, display_name=None) -> None: + type(self).instances += 1 + + def connect(self) -> None: + raise _Unreached("connect") + + def upload_keymap(self, text: str) -> None: + raise _Unreached("upload_keymap") + + def close(self) -> None: + pass + + +@pytest.fixture +def no_compositor(monkeypatch): + _RefusingSink.instances = 0 + monkeypatch.setattr(entry, "WaylandSink", _RefusingSink) + return _RefusingSink + + +# -- defaults --------------------------------------------------------------- + + +def test_the_xkb_flags_default_to_the_frozen_values(): + args = entry.build_parser().parse_args([]) + assert args.xkb_layout == "us" + assert args.xkb_model == "pc105" + assert (args.xkb_variant, args.xkb_options) == ("", "") + + +def test_the_defaults_are_the_ones_the_module_option_defaults_to(): + # Stated as constants so the NixOS option and the hand-run binary cannot + # drift into typing different characters. + assert (entry.DEFAULT_LAYOUT, entry.DEFAULT_MODEL) == ("us", "pc105") + + +def test_a_layout_is_taken_from_the_flag(): + assert entry.build_parser().parse_args(["--xkb-layout", "de"]).xkb_layout == "de" + + +def test_the_contract_command_line_still_parses(): + """CONTRACT-sessions.md §3.4's exact line, plus the keymap flags.""" + + args = entry.build_parser().parse_args( + [ + "--socket", + "/run/hhstream/pointer.sock", + "--compositor-runtime-dir", + "/run/hypr-stream", + "--xkb-layout", + "us", + "--xkb-model", + "pc105", + "--xkb-variant", + "", + "--xkb-options", + "", + ] + ) + assert str(args.socket) == "/run/hhstream/pointer.sock" + assert str(args.compositor_runtime_dir) == "/run/hypr-stream" + assert args.xkb_layout == "us" + + +# -- refusals, before any Wayland call -------------------------------------- + + +def test_a_comma_separated_layout_exits_2_without_connecting(no_compositor, caplog): + """v1 sends group 0 in every `modifiers`, so a second group is unreachable. + + xkbcommon accepts `us,ru` and hands back a two-group keymap, so nothing + downstream would notice: a caller asking for Cyrillic would get Latin and + no error. Refused here, and the NixOS option's type refuses it too — this + one is for the binary run by hand, which that type cannot reach. + """ + + code = entry.main(["--xkb-layout", "us,ru"]) + + assert code == entry.EXIT_USAGE + assert no_compositor.instances == 0, "the compositor must not be touched" + + +def test_a_layout_xkbcommon_rejects_exits_2_without_connecting(no_compositor): + code = entry.main(["--xkb-layout", "zzz-no-such-layout"]) + + assert code == entry.EXIT_USAGE + assert no_compositor.instances == 0 + + +def test_a_usable_layout_gets_as_far_as_the_compositor(no_compositor): + """The other half: exit 2 must not be how a *good* layout fails. + + A test that only asserted the refusals would pass against a `main` that + returned 2 for everything, so this one proves the good path reaches the + Wayland side and fails there instead. + """ + + with pytest.raises(_Unreached, match="connect"): + entry.main(["--xkb-layout", "us"]) + assert no_compositor.instances == 1 + + +def test_the_exit_codes_match_the_brokers_table(): + # Mirrored, not imported: the driver is a separate package on purpose + # (see the module docstring in __main__). + assert (entry.EXIT_OK, entry.EXIT_USAGE, entry.EXIT_COMPOSITOR) == (0, 2, 10) diff --git a/tests/pointer/test_keymap.py b/tests/pointer/test_keymap.py new file mode 100644 index 0000000..03a5cae --- /dev/null +++ b/tests/pointer/test_keymap.py @@ -0,0 +1,293 @@ +"""Keysym names and text to ``(evdev code, modifier mask)``, against real xkbcommon. + +A real keymap, not a stub, and that is the whole design of this file. A stub +can be made to agree with any resolver; only xkbcommon can tell you that ``é`` +is unmappable on ``us``, that ``@`` on ``de`` is a *level-three* symbol rather +than a shifted one, and that ``y`` and ``z`` swap keycodes between the two. +Those three facts are what the resolver exists for, so ``xkbcommon`` is a hard +dependency (``pyproject.toml`` says why) and these tests do not skip. + +Codes here are **evdev**, never XKB. ``a`` is 30 and not 38: 30 is what +``zwp_virtual_keyboard_v1.key`` carries and what the client reads back off +``wl_keyboard.key``, and asserting 38 would be asserting an internal index that +never reaches the wire. + +Masks are read out of the keymap, never written down. ``A`` needs +``1 << mod_get_index("Shift")``, which happens to be 1 on every layout here — +so the test computes it, because a hard-coded 1 passes today and is wrong the +first time a resolver is asked for a level-three character. +""" + +from __future__ import annotations + +import pytest + +from hhstream_pointer import keymap as keymaps +from hhstream_pointer.ops import KIND_INVALID, Dispatcher + +#: evdev codes from ``linux/input-event-codes.h``, spelled out so a failure +#: reads against the header rather than against another part of this suite. +KEY_A = 30 +KEY_ENTER = 28 +KEY_TAB = 15 +KEY_LEFTSHIFT = 42 +KEY_Y = 21 # the physical key that is `y` on us and `z` on de +KEY_Z = 44 # ...and `z` on us, `y` on de + + +@pytest.fixture(scope="module") +def us() -> keymaps.Keymap: + return keymaps.build(layout="us") + + +@pytest.fixture(scope="module") +def de() -> keymaps.Keymap: + return keymaps.build(layout="de") + + +def shift_mask(keymap: keymaps.Keymap) -> int: + """Shift's bit, asked of the keymap rather than assumed to be 1.""" + + return 1 << keymap._keymap.mod_get_index("Shift") + + +# -- the letter path -------------------------------------------------------- + + +def test_a_lower_case_letter_is_its_evdev_code_and_no_modifier(us): + action = us.resolve_name("a") + assert (action.code, action.mask) == (KEY_A, 0) + + +def test_a_capital_is_the_same_code_with_shift_in_the_mask(us): + action = us.resolve_name("A") + assert action.code == KEY_A + assert action.mask == shift_mask(us) + # The point of the mask: a capital is NOT a Shift keycode. Hyprland's + # virtual keyboard never runs updateXkbStateWithKey, so a synthetic + # KEY_LEFTSHIFT would change no modifier state at all. + assert action.code != KEY_LEFTSHIFT + + +def test_shift_is_a_key_in_its_own_right_with_no_mask_of_its_own(us): + action = us.resolve_name("Shift_L") + # Pressing Shift needs no modifier held; what it *contributes* is separate. + assert (action.code, action.mask) == (KEY_LEFTSHIFT, 0) + assert us.is_modifier("Shift_L") + assert us.modifier_mask("Shift_L") == shift_mask(us) + + +# -- the named keys --------------------------------------------------------- + + +@pytest.mark.parametrize( + "name, code", + [("Return", KEY_ENTER), ("Tab", KEY_TAB), ("BackSpace", 14), ("Left", 105)], +) +def test_a_named_keysym_resolves_to_its_evdev_code(us, name, code): + assert us.resolve_name(name).code == code + + +@pytest.mark.parametrize("character, code", [("\n", KEY_ENTER), ("\t", KEY_TAB)]) +def test_the_two_allowed_control_characters_are_named_keys(us, character, code): + (action,) = us.resolve_text(character) + assert action.code == code + assert action.mask == 0 + + +def test_an_empty_string_is_no_actions_and_not_an_error(us): + assert us.resolve_text("") == [] + + +# -- refusals --------------------------------------------------------------- + + +@pytest.mark.parametrize("character", ["é", "ü", "😀", "\x01", "\x1b", "\x7f"]) +def test_a_character_this_layout_cannot_produce_is_refused(us, character): + with pytest.raises(keymaps.UnknownKey) as caught: + us.resolve_text(character) + message = str(caught.value) + # The index and the codepoint, and NOT the character: this message reaches + # the driver's log, and the string it came from is a password as often as + # not. + assert "scalar 0" in message + assert character not in message + + +def test_the_refusal_names_the_index_of_the_offending_scalar(us): + with pytest.raises(keymaps.UnknownKey) as caught: + us.resolve_text("abcé") + assert "scalar 3" in str(caught.value) + assert "é" not in str(caught.value) + + +def test_a_dead_keysym_is_refused_by_name(us): + with pytest.raises(keymaps.UnknownKey) as caught: + us.resolve_name("dead_acute") + assert "dead key" in str(caught.value) + + +def test_an_unknown_keysym_name_is_refused(us): + with pytest.raises(keymaps.UnknownKey): + us.resolve_name("NoSuchKeysymAtAll") + + +def test_a_comma_separated_layout_is_refused_before_anything_is_compiled(): + # xkbcommon accepts `us,ru` happily and hands back a two-group keymap. v1 + # always sends group 0, so the second group would be silently unreachable: + # a caller asking for Cyrillic would get Latin and no error. + with pytest.raises(keymaps.KeymapError) as caught: + keymaps.build(layout="us,ru") + assert "group" in str(caught.value) + + +def test_a_layout_xkbcommon_rejects_is_a_keymap_error_naming_it(): + with pytest.raises(keymaps.KeymapError) as caught: + keymaps.build(layout="zzz-no-such-layout") + assert "zzz-no-such-layout" in str(caught.value) + + +# -- the cap ---------------------------------------------------------------- + + +def test_the_cap_is_exactly_at_the_limit(us): + assert len(us.resolve_text("a" * keymaps.MAX_TEXT_SCALARS)) == keymaps.MAX_TEXT_SCALARS + + +def test_one_scalar_over_the_cap_is_refused(us): + with pytest.raises(keymaps.UnknownKey) as caught: + us.resolve_text("a" * (keymaps.MAX_TEXT_SCALARS + 1)) + assert str(keymaps.MAX_TEXT_SCALARS) in str(caught.value) + + +def test_the_cap_counts_scalars_and_not_bytes(us): + # 4096 astral-plane scalars are 16384 UTF-8 bytes. A byte cap would refuse + # this for being too long; the scalar cap lets it through to the character + # check, which refuses it for being unmappable instead. The distinction is + # the whole test: a byte cap and a scalar cap agree on ASCII, so only a + # non-ASCII case can tell them apart. + text = "😀" * keymaps.MAX_TEXT_SCALARS + assert len(text) == keymaps.MAX_TEXT_SCALARS + assert len(text.encode("utf-8")) > keymaps.MAX_TEXT_SCALARS + with pytest.raises(keymaps.UnknownKey) as caught: + us.resolve_text(text) + assert "scalar 0" in str(caught.value) + assert "limit" not in str(caught.value) + + +# -- the modifier set ------------------------------------------------------- + + +def test_the_modifier_set_is_measured_and_not_empty(us): + assert us.modifier_names() == keymaps.EXPECTED_MODIFIERS + + +def test_a_lock_is_not_a_modifier(us): + # Caps_Lock reports a *locked* mask, so `type` refuses while it is held + # rather than producing a case nobody asked for. + assert us.lock_names() == keymaps.EXPECTED_LOCKS + for name in keymaps.EXPECTED_LOCKS: + assert not us.is_modifier(name) + assert us.modifier_mask(name) == 0 + + +def test_control_contributes_a_mask_that_is_not_shifts(us): + assert us.modifier_mask("Control_L") not in (0, shift_mask(us)) + + +# -- a second layout, which is what stops a Shift special case --------------- + + +def test_de_swaps_y_and_z_against_us(us, de): + assert (us.resolve_name("y").code, us.resolve_name("z").code) == (KEY_Y, KEY_Z) + # Same keysyms, other codes: a resolver with a table beside the keymap + # rather than inside it would return the us answer here. + assert (de.resolve_name("y").code, de.resolve_name("z").code) == (KEY_Z, KEY_Y) + + +def test_on_de_the_at_sign_needs_a_level_three_mask_not_shift(us, de): + at_us = us.resolve_text("@")[0] + at_de = de.resolve_text("@")[0] + assert at_us.mask == shift_mask(us) + # The case a Shift-only special case gets wrong: `@` is AltGr+q on de. + assert at_de.mask not in (0, shift_mask(de)) + assert at_de.mask == de.modifier_mask("ISO_Level3_Shift") + + +def test_a_character_us_cannot_type_is_ordinary_on_de(us, de): + with pytest.raises(keymaps.UnknownKey): + us.resolve_text("ü") + (action,) = de.resolve_text("ü") + assert action.name == "udiaeresis" + assert action.mask == 0 + + +# -- the keymap text we upload ---------------------------------------------- + + +def test_the_keymap_text_is_an_xkb_keymap_naming_its_layout(us, de): + assert us.text().lstrip().startswith("xkb_keymap {") + # The symbols section names the layout, which is what the VM check greps to + # prove the keymap a client decoded with is the one we uploaded. + assert "us" in _symbols_line(us) + assert "de" in _symbols_line(de) + + +def _symbols_line(keymap: keymaps.Keymap) -> str: + return next(line for line in keymap.text().splitlines() if "xkb_symbols" in line) + + +# -- through the dispatcher: nothing is emitted for a bad string ------------- + + +class _Sink: + """Just enough of :class:`hhstream_pointer.ops.PointerSink` to count calls.""" + + def __init__(self) -> None: + self.calls: list[tuple] = [] + + def has_keyboard(self) -> bool: + return True + + def key(self, code, state): + self.calls.append(("key", code, state)) + + def modifiers(self, depressed, latched, locked, group): + self.calls.append(("modifiers", depressed, latched, locked, group)) + + +def test_an_unmappable_character_emits_nothing_through_the_dispatcher(us): + sink = _Sink() + reply = Dispatcher(sink, us).handle({"op": "type", "text": "abcé"}) + assert reply["ok"] is False + # The assertion that matters: not "no event carried é" -- which would also + # pass if a, b and c had been typed -- but that the sink was never called. + assert sink.calls == [] + assert reply["kind"] == KIND_INVALID + + +def test_a_string_over_the_cap_emits_nothing_through_the_dispatcher(us): + sink = _Sink() + reply = Dispatcher(sink, us).handle( + {"op": "type", "text": "a" * (keymaps.MAX_TEXT_SCALARS + 1)} + ) + assert reply["ok"] is False + assert reply["kind"] == KIND_INVALID + assert sink.calls == [] + + +def test_the_keymap_object_is_built_once_and_reused_across_types(us): + """Two ``type``s, one keymap. + + The false pass this guards is a backend that recompiles and re-*uploads* + per string: a second ``keymap`` request replaces Hyprland's XKB state + without walking the keys it believes are down, so re-uploading under a held + modifier strands it. The dispatcher is handed one object and never asks for + another, which is what makes the single upload in ``__main__`` sufficient. + """ + + sink = _Sink() + dispatcher = Dispatcher(sink, us) + assert dispatcher.handle({"op": "type", "text": "a"})["ok"] is True + assert dispatcher.handle({"op": "type", "text": "b"})["ok"] is True + assert dispatcher._keymap is us diff --git a/tests/pointer/test_lease.py b/tests/pointer/test_lease.py index ccda2fe..8bc23ee 100644 --- a/tests/pointer/test_lease.py +++ b/tests/pointer/test_lease.py @@ -243,3 +243,102 @@ def test_a_new_lease_starts_without_the_previous_bookmark(lease): def test_defaults_match_the_contract(): lease = PointerLease() assert (lease.ttl_s, lease.max_s) == (30.0, 300.0) + + +# -- keys: the same mirror, and the same ordering rule ---------------------- +# +# PLAN §6.7 proposed a `keyboard` flag on the lease. These tests are the +# argument against it: a boolean cannot say to lift `Control_L` and not `a`, +# and it cannot say which went down first. + + +def test_press_and_lift_one_key(lease): + lease_id = lease.acquire("alpha") + lease.press_key("alpha", "Shift_L") + assert lease.keys_pressed() == ["Shift_L"] + assert lease.unpress_key("alpha", "Shift_L") == ["Shift_L"] + assert lease.keys_pressed() == [] + assert lease.release("alpha", lease_id, "done").keys_lifted == [] + + +def test_lifting_a_key_that_is_not_down_reports_nothing(lease): + lease.acquire("alpha") + assert lease.unpress_key("alpha", "Shift_L") == [] + lease.press_key("alpha", "Shift_L") + lease.unpress_key("alpha", "Shift_L") + assert lease.unpress_key("alpha", "Shift_L") == [] + + +def test_keys_are_kept_in_press_order(lease): + lease_id = lease.acquire("alpha") + for name in ("Control_L", "Shift_L", "a"): + lease.press_key("alpha", name) + assert lease.keys_pressed() == ["Control_L", "Shift_L", "a"] + + assert lease.unpress_key("alpha", "Shift_L") == ["Shift_L"] + assert lease.keys_pressed() == ["Control_L", "a"] + + outcome = lease.release("alpha", lease_id, "timeout") + assert outcome.keys_lifted == ["Control_L", "a"] + assert lease.keys_pressed() == [] + + +def test_pressing_a_key_twice_leaves_one_down(lease): + lease.acquire("alpha") + lease.press_key("alpha", "a") + lease.press_key("alpha", "a") + assert lease.keys_pressed() == ["a"] + + +def test_keys_and_buttons_are_tracked_separately(lease): + lease_id = lease.acquire("alpha") + lease.press("alpha", "left") + lease.press_key("alpha", "Shift_L") + assert (lease.pressed(), lease.keys_pressed()) == (["left"], ["Shift_L"]) + + outcome = lease.release("alpha", lease_id, "done") + assert (outcome.buttons_lifted, outcome.keys_lifted) == (["left"], ["Shift_L"]) + + +def test_a_non_holder_cannot_press_a_key(lease): + lease.acquire("alpha") + with pytest.raises(LeaseInvalid): + lease.press_key("beta", "a") + with pytest.raises(LeaseInvalid): + lease.unpress_key("beta", "a") + + +def test_expire_still_returns_no_key_list_so_the_broker_must_read_first(lease, clock): + """CONTRACT-sessions.md §3.3, unchanged by the keyboard. + + `expire()` is still `LeaseInfo` and carries neither buttons nor keys. The + ordering it forces -- read, *then* expire -- is the only thing stopping a + key from being forgotten before the driver has been told to lift it, and + widening the return would make that ordering optional. + """ + + lease.acquire("alpha") + lease.press_key("alpha", "Shift_L") + clock.advance(31.0) + + # The broker's order, and it is not interchangeable. + held = lease.keys_pressed() + info = lease.expire() + + assert held == ["Shift_L"] + assert info is not None + assert not hasattr(info, "keys_lifted") + assert not hasattr(info, "buttons_lifted") + assert lease.keys_pressed() == [] + + +def test_expiry_does_not_leak_keys_to_the_next_holder(lease, clock): + """A held Shift must not become the next session's Shift.""" + + lease.acquire("alpha") + lease.press_key("alpha", "Shift_L") + clock.advance(31.0) + assert lease.expire() is not None + + lease.acquire("beta") + assert lease.keys_pressed() == [] diff --git a/tests/pointer/test_ops.py b/tests/pointer/test_ops.py index 041609c..5db11e8 100644 --- a/tests/pointer/test_ops.py +++ b/tests/pointer/test_ops.py @@ -13,17 +13,34 @@ from __future__ import annotations import pytest -from hhstream_pointer import buttons -from hhstream_pointer.ops import Dispatcher +from hhstream_pointer import buttons, keymap as keymaps +from hhstream_pointer.ops import KIND_INVALID, KIND_REFUSED, Dispatcher LEFT = buttons.CODES["left"] RIGHT = buttons.CODES["right"] DOWN = buttons.STATES["down"] UP = buttons.STATES["up"] +#: evdev codes, from ``linux/input-event-codes.h``. Asserted as the integers +#: the wire carries, never as XKB codes: ``a`` is 30 there and 38 in xkbcommon's +#: tables, and only one of the two ever leaves this process. +KEY_A = 30 +KEY_B = 48 +KEY_ENTER = 28 +KEY_LEFTSHIFT = 42 +KEY_LEFTCTRL = 29 + class RecordingSink: - """Every call, in order, as a tuple. Nothing else.""" + """Every call, in order, as a tuple. Nothing else. + + ``has_keyboard`` answers True by default because most tests want one. The + keyboard calls carry **no output**: a virtual keyboard is seat-global, and + a sink that tagged them with one would be hiding the fact that a key after + a warp to another output still goes to whatever has focus. + """ + + keyboard = True def __init__(self) -> None: self.calls: list[tuple] = [] @@ -40,6 +57,31 @@ class RecordingSink: def frame(self, output): self.calls.append(("frame", output)) + def has_keyboard(self): + return self.keyboard + + def key(self, code, state): + self.calls.append(("key", code, state)) + + def modifiers(self, depressed, latched, locked, group): + self.calls.append(("modifiers", depressed, latched, locked, group)) + + +class KeyboardlessSink(RecordingSink): + """A compositor with no ``zwp_virtual_keyboard_manager_v1``. + + Not a failing sink: the methods are simply never meant to be reached, and + a call that got through would be the bug. + """ + + keyboard = False + + def key(self, code, state): + raise AssertionError("no virtual keyboard exists; key must not be sent") + + def modifiers(self, depressed, latched, locked, group): + raise AssertionError("no virtual keyboard exists; modifiers must not be sent") + class FailingSink(RecordingSink): """A sink whose motion raises, standing in for an output that vanished.""" @@ -56,9 +98,21 @@ def sink() -> RecordingSink: return RecordingSink() +@pytest.fixture(scope="module") +def us() -> keymaps.Keymap: + """A real ``us`` keymap. + + Real, not a fake, for the reason ``test_keymap.py`` gives at length: the + mask for ``A`` and the refusal of ``é`` are properties of the layout, and a + fake that agreed with the dispatcher would prove only that they agree. + """ + + return keymaps.build(layout="us") + + @pytest.fixture -def driver(sink) -> Dispatcher: - return Dispatcher(sink) +def driver(sink, us) -> Dispatcher: + return Dispatcher(sink, us) def warp(driver, output="hh-alpha", x=0.5, y=0.5): @@ -90,7 +144,7 @@ def test_a_click_is_warp_button_frame(driver, sink): ("button", "hh-alpha", LEFT, UP), ("frame", "hh-alpha"), ] - assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": []} + assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": [], "keys": []} def test_the_boundary_coordinates_are_accepted(driver, sink): @@ -160,7 +214,11 @@ def test_pressed_reports_what_is_down_oldest_first(driver): warp(driver) driver.handle({"op": "button", "button": "right", "state": "down"}) driver.handle({"op": "button", "button": "left", "state": "down"}) - assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": ["right", "left"]} + assert driver.handle({"op": "pressed"}) == { + "ok": True, + "buttons": ["right", "left"], + "keys": [], + } def test_release_all_lifts_everything_and_frames_once(driver, sink): @@ -169,17 +227,28 @@ def test_release_all_lifts_everything_and_frames_once(driver, sink): driver.handle({"op": "button", "button": "right", "state": "down"}) sink.calls.clear() - assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": ["left", "right"]} + assert driver.handle({"op": "release_all"}) == { + "ok": True, + "lifted": ["left", "right"], + "lifted_keys": [], + } assert sink.calls == [ ("button", "hh-alpha", LEFT, UP), ("button", "hh-alpha", RIGHT, UP), ("frame", "hh-alpha"), ] - assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": []} + assert driver.handle({"op": "pressed"}) == {"ok": True, "buttons": [], "keys": []} def test_release_all_on_a_quiet_driver_lifts_nothing(driver, sink): - assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": []} + assert driver.handle({"op": "release_all"}) == { + "ok": True, + "lifted": [], + "lifted_keys": [], + } + # Including no zeroed `modifiers`: a mask nothing ever set is not ours to + # clear, and on a sink with no keyboard at all sending one would raise and + # abandon the button lifting above. assert sink.calls == [] @@ -196,7 +265,11 @@ def test_release_all_lifts_through_the_pointer_the_press_went_to(driver, sink): driver.handle({"op": "button", "button": "right", "state": "down"}) sink.calls.clear() - assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": ["left", "right"]} + assert driver.handle({"op": "release_all"}) == { + "ok": True, + "lifted": ["left", "right"], + "lifted_keys": [], + } assert sink.calls == [ ("button", "hh-alpha", LEFT, UP), ("button", "hh-beta", RIGHT, UP), @@ -209,7 +282,11 @@ def test_a_lifted_button_is_forgotten(driver): warp(driver) driver.handle({"op": "button", "button": "left", "state": "down"}) driver.handle({"op": "button", "button": "left", "state": "up"}) - assert driver.handle({"op": "release_all"}) == {"ok": True, "lifted": []} + assert driver.handle({"op": "release_all"}) == { + "ok": True, + "lifted": [], + "lifted_keys": [], + } def test_every_known_button_name_round_trips(driver, sink): @@ -227,6 +304,10 @@ def test_button_before_any_warp_is_refused(driver, sink): assert driver.handle({"op": "button", "button": "left", "state": "down"}) == { "ok": False, "error": "no output is aimed; warp before button or frame", + # `refused` and not `invalid_argument`: the request was well formed, + # what is missing is a warp, and the broker reports that as exit 10 + # exactly as it already does for an unknown button. + "kind": "refused", } assert sink.calls == [] @@ -277,8 +358,8 @@ def test_a_failed_warp_does_not_change_the_aim(): ({"op": "axis", "value": -1e9}, "wheel-click limit"), ], ) -def test_malformed_requests_are_answered_not_fatal(sink, request_, fragment): - driver = Dispatcher(sink) +def test_malformed_requests_are_answered_not_fatal(sink, us, request_, fragment): + driver = Dispatcher(sink, us) # Aim first, so a refusal is about the field under test rather than the aim. warp(driver) sink.calls.clear() @@ -300,9 +381,11 @@ def test_the_contracts_ops_are_exactly_what_is_implemented() -> None: An op that exists here and nowhere in the contract -- or the reverse -- fails this test rather than surprising whoever reads the contract next. - ``axis`` is the one addition since the freeze, made deliberately so that a - session can scroll; the set is edited by hand, which is the reminder to - write it down. + ``axis`` was the first addition since the freeze, so a session could + scroll; ``key`` and ``type`` are the second, and there is deliberately no + keyboard ``frame`` or ``release_all_keys`` beside them -- the protocol has + no frame, and expiry has exactly one call site. The set is edited by hand, + which is the reminder to write it down. """ assert set(Dispatcher._ops) == { @@ -310,6 +393,344 @@ def test_the_contracts_ops_are_exactly_what_is_implemented() -> None: "button", "axis", "frame", + "key", + "type", "pressed", "release_all", } + + +# -- key: one keysym at a time ---------------------------------------------- +# +# Names on this socket, evdev codes on the Wayland request -- the same division +# `buttons.py` draws, and the reason `pressed` answers "Control_L" rather than +# 29. These tests assert both halves: the response names, the sink codes. + + +def test_key_down_sends_the_code_and_lists_the_name(driver, sink): + assert driver.handle({"op": "key", "key": "Return", "state": "down"}) == { + "ok": True, + "keys": ["Return"], + "lifted": [], + } + assert sink.calls == [("key", KEY_ENTER, DOWN)] + assert driver.handle({"op": "pressed"})["keys"] == ["Return"] + + +def test_key_needs_no_warp(sink, us): + """A keyboard has no output, so `type` must not demand an aim. + + Deliberately the one test in this file that never warps: a virtual keyboard + is seat-global, so requiring a warp first would refuse a caller who only + ever wanted to type -- and every other test here warps out of habit, which + is exactly how that bug would survive. + """ + + driver = Dispatcher(sink, us) + assert driver.handle({"op": "type", "text": "Hi"})["ok"] is True + assert driver.handle({"op": "key", "key": "a", "state": "down"})["ok"] is True + assert ("key", KEY_A, DOWN) in sink.calls + + +def test_a_key_is_not_tagged_with_an_output_even_after_a_warp(driver, sink): + warp(driver, output="hh-beta") + sink.calls.clear() + driver.handle({"op": "key", "key": "a", "state": "down"}) + # Two items, not three: no output travels with a key. A sink that accepted + # one would let a future change route keys per output, which the protocol + # cannot do. + assert sink.calls == [("key", KEY_A, DOWN)] + + +def test_key_up_forgets_the_key(driver, sink): + driver.handle({"op": "key", "key": "a", "state": "down"}) + assert driver.handle({"op": "key", "key": "a", "state": "up"}) == { + "ok": True, + "keys": [], + "lifted": ["a"], + } + assert sink.calls == [("key", KEY_A, DOWN), ("key", KEY_A, UP)] + + +def test_up_of_a_key_that_was_never_down_lifts_nothing_and_emits_nothing(driver, sink): + """Same rule as `unpress` for a button that was never pressed. + + Reported rather than invented, and silent on the wire: a key-up the + compositor has no matching key-down for puts its own `m_pressed` out of + step with ours, and on this build that makes the *next* press of the code + a no-op. + """ + + assert driver.handle({"op": "key", "key": "a", "state": "up"}) == { + "ok": True, + "keys": [], + "lifted": [], + } + assert sink.calls == [] + + +def test_keys_are_reported_oldest_first(driver): + for name in ("Control_L", "Shift_L", "a"): + driver.handle({"op": "key", "key": name, "state": "down"}) + assert driver.handle({"op": "pressed"})["keys"] == ["Control_L", "Shift_L", "a"] + + +# -- the modifier half, which a key-up does not undo ------------------------ + + +def test_a_modifier_down_sends_the_key_and_the_mask(driver, sink, us): + driver.handle({"op": "key", "key": "Shift_L", "state": "down"}) + assert sink.calls == [ + ("key", KEY_LEFTSHIFT, DOWN), + ("modifiers", us.modifier_mask("Shift_L"), 0, 0, 0), + ] + + +def test_a_modifier_up_restores_the_mask_of_whatever_is_still_held(driver, sink, us): + driver.handle({"op": "key", "key": "Shift_L", "state": "down"}) + driver.handle({"op": "key", "key": "Control_L", "state": "down"}) + sink.calls.clear() + + driver.handle({"op": "key", "key": "Shift_L", "state": "up"}) + + # Not zero: Control is still down, so the mask drops to Control's bit + # alone. A key-up changes no modifier state on this compositor, so the + # mask is only ever what we last said it was. + assert sink.calls == [ + ("key", KEY_LEFTSHIFT, UP), + ("modifiers", us.modifier_mask("Control_L"), 0, 0, 0), + ] + + +def test_an_ordinary_key_down_sends_no_mask(driver, sink): + driver.handle({"op": "key", "key": "a", "state": "down"}) + assert sink.calls == [("key", KEY_A, DOWN)] + + +# -- type ------------------------------------------------------------------- + + +def test_type_of_a_capital_is_the_mask_and_not_a_shift_keycode(driver, sink, us): + assert driver.handle({"op": "type", "text": "A"}) == {"ok": True, "keys": []} + shift = us.modifier_mask("Shift_L") + assert sink.calls == [ + # The mask goes FIRST. A client that decodes with the mask from the + # last `wl_keyboard.modifiers` -- foot, GTK -- emits `a` if the key + # arrives before the mask. + ("modifiers", shift, 0, 0, 0), + ("key", KEY_A, DOWN), + ("key", KEY_A, UP), + ("modifiers", 0, 0, 0, 0), + ] + # And no synthetic Shift key anywhere: sending both a mask and KEY_LEFTSHIFT + # is how a toolkit applies Shift twice, or not at all. + assert not any(call[0] == "key" and call[1] == KEY_LEFTSHIFT for call in sink.calls) + + +def test_type_leaves_no_key_held(driver): + driver.handle({"op": "type", "text": "Hello"}) + assert driver.handle({"op": "pressed"})["keys"] == [] + + +def test_type_emits_a_down_up_pair_per_character(driver, sink): + driver.handle({"op": "type", "text": "ab"}) + assert [c for c in sink.calls if c[0] == "key"] == [ + ("key", KEY_A, DOWN), + ("key", KEY_A, UP), + ("key", KEY_B, DOWN), + ("key", KEY_B, UP), + ] + + +def test_type_of_an_empty_string_emits_nothing_and_succeeds(driver, sink): + assert driver.handle({"op": "type", "text": ""}) == {"ok": True, "keys": []} + assert sink.calls == [] + + +def test_type_ors_an_explicitly_held_modifier_and_leaves_it_down(driver, sink, us): + """`down Control_L` then `type c` is Ctrl+C, and Control is still down.""" + + driver.handle({"op": "key", "key": "Control_L", "state": "down"}) + sink.calls.clear() + + assert driver.handle({"op": "type", "text": "c"}) == {"ok": True, "keys": ["Control_L"]} + + control = us.modifier_mask("Control_L") + assert sink.calls == [ + ("modifiers", control, 0, 0, 0), + ("key", us.resolve_name("c").code, DOWN), + ("key", us.resolve_name("c").code, UP), + # Back to the BASELINE, not to zero: Control was not ours to lift. + ("modifiers", control, 0, 0, 0), + ] + assert not any(call[0] == "key" and call[1] == KEY_LEFTCTRL for call in sink.calls) + assert driver.handle({"op": "pressed"})["keys"] == ["Control_L"] + + +def test_type_of_a_capital_under_a_held_control_ors_both_masks(driver, sink, us): + driver.handle({"op": "key", "key": "Control_L", "state": "down"}) + sink.calls.clear() + + driver.handle({"op": "type", "text": "A"}) + + both = us.modifier_mask("Control_L") | us.modifier_mask("Shift_L") + assert sink.calls[0] == ("modifiers", both, 0, 0, 0) + assert sink.calls[-1] == ("modifiers", us.modifier_mask("Control_L"), 0, 0, 0) + + +def test_type_while_a_non_modifier_is_held_emits_nothing(driver, sink): + driver.handle({"op": "key", "key": "a", "state": "down"}) + sink.calls.clear() + + reply = driver.handle({"op": "type", "text": "bc"}) + + assert reply["ok"] is False + assert reply["kind"] == KIND_INVALID + assert sink.calls == [] + # And the held key is untouched: a refused request changes nothing. + assert driver.handle({"op": "pressed"})["keys"] == ["a"] + + +def test_type_while_a_lock_is_held_is_refused_too(driver, sink): + """Caps_Lock reports a *locked* mask, so it is not a modifier. + + Typing under it would produce a case the caller did not ask for, and v1 + refuses rather than guessing which one they meant. + """ + + driver.handle({"op": "key", "key": "Caps_Lock", "state": "down"}) + sink.calls.clear() + + assert driver.handle({"op": "type", "text": "a"})["ok"] is False + assert sink.calls == [] + + +def test_a_string_that_fails_on_its_third_character_emits_nothing(driver, sink): + reply = driver.handle({"op": "type", "text": "abé"}) + assert reply["ok"] is False + # Not "no event carried é" -- that would also pass with a and b typed. + assert sink.calls == [] + + +def test_a_bad_character_is_a_usage_error_and_a_missing_keyboard_is_not(sink, us): + """The two refusals the broker must tell apart (the review's change 1). + + An unmappable character is the caller's; a compositor with no keyboard + global is not. They become exit 2 and exit 10, and the only thing carrying + the difference across the socket is this token. + """ + + usable = Dispatcher(sink, us) + assert usable.handle({"op": "type", "text": "é"})["kind"] == KIND_INVALID + assert usable.handle({"op": "key", "key": "Nope", "state": "down"})["kind"] == KIND_INVALID + assert usable.handle({"op": "key", "key": "a", "state": "sideways"})["kind"] == KIND_INVALID + + absent = Dispatcher(KeyboardlessSink(), us) + assert absent.handle({"op": "type", "text": "a"})["kind"] == KIND_REFUSED + assert absent.handle({"op": "key", "key": "a", "state": "down"})["kind"] == KIND_REFUSED + + +def test_without_a_keymap_at_all_the_keyboard_ops_refuse_and_the_cursor_works(sink): + """A driver started with no layout still moves the cursor.""" + + driver = Dispatcher(sink, None) + assert warp(driver)["ok"] is True + assert driver.handle({"op": "button", "button": "left", "state": "down"})["ok"] is True + reply = driver.handle({"op": "type", "text": "a"}) + assert reply["ok"] is False and reply["kind"] == KIND_REFUSED + + +# -- release_all, with keys ------------------------------------------------ + + +def test_release_all_lifts_keys_in_press_order_then_zeroes_the_mask(driver, sink): + driver.handle({"op": "key", "key": "Control_L", "state": "down"}) + driver.handle({"op": "key", "key": "a", "state": "down"}) + sink.calls.clear() + + assert driver.handle({"op": "release_all"}) == { + "ok": True, + "lifted": [], + "lifted_keys": ["Control_L", "a"], + } + assert sink.calls == [ + ("key", KEY_LEFTCTRL, UP), + ("key", KEY_A, UP), + # The part that is easy to leave out. A virtual key-up clears no + # modifier state, so without this the next holder gets a keyboard + # where every letter is a capital. + ("modifiers", 0, 0, 0, 0), + ] + assert driver.handle({"op": "pressed"})["keys"] == [] + + +def test_release_all_lifts_keys_after_buttons_and_adds_no_keyboard_frame(driver, sink): + warp(driver) + driver.handle({"op": "button", "button": "left", "state": "down"}) + driver.handle({"op": "key", "key": "Shift_L", "state": "down"}) + sink.calls.clear() + + driver.handle({"op": "release_all"}) + + assert sink.calls == [ + ("button", "hh-alpha", LEFT, UP), + ("frame", "hh-alpha"), + ("key", KEY_LEFTSHIFT, UP), + ("modifiers", 0, 0, 0, 0), + ] + # Exactly one frame, for the pointer. `zwp_virtual_keyboard_v1` has none, + # and a key that waited for one would never arrive. + assert sum(1 for call in sink.calls if call[0] == "frame") == 1 + + +def test_release_all_lifts_keys_even_after_a_warp_to_another_output(driver, sink): + """Keys are not per output, and this is the test that says so. + + The button path has to lift through the pointer the press went to; the key + path has nothing to choose, and a sink that silently ignored an output + argument would make a per-output implementation look correct here. + """ + + warp(driver, output="hh-alpha") + driver.handle({"op": "key", "key": "a", "state": "down"}) + warp(driver, output="hh-beta") + sink.calls.clear() + + assert driver.handle({"op": "release_all"})["lifted_keys"] == ["a"] + assert sink.calls == [("key", KEY_A, UP)] + + +def test_release_all_without_a_keyboard_still_lifts_buttons(us): + """The review's change 3, and the reason the mask is conditional. + + `SessionManager._expire_pointer` calls `release_all` exactly once, so an + exception from the key half would abandon the buttons -- and a lease that + expired with a mouse button down is the failure the whole TTL exists to + prevent. + """ + + sink = KeyboardlessSink() + driver = Dispatcher(sink, us) + warp(driver) + driver.handle({"op": "button", "button": "left", "state": "down"}) + sink.calls.clear() + + assert driver.handle({"op": "release_all"}) == { + "ok": True, + "lifted": ["left"], + "lifted_keys": [], + } + assert sink.calls == [("button", "hh-alpha", LEFT, UP), ("frame", "hh-alpha")] + + +def test_release_all_after_a_type_zeroes_the_mask_once_more(driver, sink): + """A `type` restored the baseline itself, and `release_all` still zeroes. + + Cheap, and it is the crash-mid-string case: the mask the last character set + is the compositor's until something says otherwise. + """ + + driver.handle({"op": "type", "text": "A"}) + sink.calls.clear() + driver.handle({"op": "release_all"}) + assert sink.calls == [("modifiers", 0, 0, 0, 0)] diff --git a/tests/pointer/test_pointer_server.py b/tests/pointer/test_pointer_server.py index 767b095..a518e31 100644 --- a/tests/pointer/test_pointer_server.py +++ b/tests/pointer/test_pointer_server.py @@ -78,7 +78,7 @@ class _Client: def test_one_request_gets_one_response(connection): client, _ = connection - assert client.call({"op": "pressed"}) == {"ok": True, "buttons": []} + assert client.call({"op": "pressed"}) == {"ok": True, "buttons": [], "keys": []} def test_many_requests_share_one_connection(connection): @@ -86,8 +86,16 @@ def test_many_requests_share_one_connection(connection): assert client.call({"op": "warp", "output": "hh-a", "x": 0.5, "y": 0.5}) == {"ok": True} assert client.call({"op": "button", "button": "left", "state": "down"}) == {"ok": True} assert client.call({"op": "frame"}) == {"ok": True} - assert client.call({"op": "pressed"}) == {"ok": True, "buttons": ["left"]} - assert client.call({"op": "release_all"}) == {"ok": True, "lifted": ["left"]} + assert client.call({"op": "pressed"}) == { + "ok": True, + "buttons": ["left"], + "keys": [], + } + assert client.call({"op": "release_all"}) == { + "ok": True, + "lifted": ["left"], + "lifted_keys": [], + } assert [c[0] for c in sink.calls] == ["motion", "button", "frame", "button", "frame"] diff --git a/tests/pointer/test_vendored_protocol.py b/tests/pointer/test_vendored_protocol.py index 5d4c143..a3abd11 100644 --- a/tests/pointer/test_vendored_protocol.py +++ b/tests/pointer/test_vendored_protocol.py @@ -29,6 +29,9 @@ assert _spec is not None and _spec.origin, "hhstream_pointer is not importable" PACKAGE = Path(_spec.origin).parent PROTOCOL_DIR = PACKAGE / "_protocol/wlr_virtual_pointer_unstable_v1" MANAGER = PROTOCOL_DIR / "zwlr_virtual_pointer_manager_v1.py" +KEYBOARD_DIR = PACKAGE / "_protocol/virtual_keyboard_unstable_v1" +KEYBOARD_MANAGER = KEYBOARD_DIR / "zwp_virtual_keyboard_manager_v1.py" +KEYBOARD = KEYBOARD_DIR / "zwp_virtual_keyboard_v1.py" #: Only present in a checkout; a build sandbox gets the test directory alone. PYPROJECT = Path(__file__).resolve().parents[2] / "pyproject.toml" @@ -57,10 +60,81 @@ def test_the_shim_resolves_the_generated_relative_import(): @pytest.mark.skipif(not PYPROJECT.is_file(), reason="not running from a checkout") -def test_pyproject_declares_the_entry_point_and_the_dependency(): +def test_pyproject_declares_the_entry_point_and_the_dependencies(): pyproject = PYPROJECT.read_text() assert 'hhstream-pointer = "hhstream_pointer.__main__:main"' in pyproject assert "pywayland" in pyproject + # Not optional, and the comment beside it in pyproject.toml says why: an + # optional xkbcommon would let test_keymap.py skip, and the + # unmappable-character path is the one that must not rot. + assert "xkbcommon" in pyproject + + +# -- the virtual keyboard -------------------------------------------------- + + +def test_the_keyboard_protocol_is_vendored_beside_the_pointer_one(): + assert (KEYBOARD_DIR / "__init__.py").is_file() + assert KEYBOARD_MANAGER.is_file() + assert KEYBOARD.is_file() + for path in KEYBOARD_DIR.glob("*.py"): + assert path.read_text().startswith("# This file has been autogenerated") + + +def test_the_keyboard_manager_is_version_1_with_the_seat_only_request(): + source = KEYBOARD_MANAGER.read_text() + assert 'name = "zwp_virtual_keyboard_manager_v1"' in source + assert " version = 1" in source + # Seat and nothing else: a virtual keyboard has no output argument, which + # is why `ops.py` must not route a key through `_aimed()`. + assert "def create_virtual_keyboard(self, seat: WlSeat)" in source + assert "WlOutput" not in source + + +def test_the_keyboard_carries_keymap_key_and_modifiers(): + source = KEYBOARD.read_text() + assert 'name = "zwp_virtual_keyboard_v1"' in source + assert " version = 1" in source + assert "def keymap(self, format: int, fd: int, size: int)" in source + assert "def key(self, time: int, key: int, state: int)" in source + assert ( + "def modifiers(self, mods_depressed: int, mods_latched: int, " + "mods_locked: int, group: int)" in source + ) + # The keymap fd really is an fd on the wire, not a number we invented. + assert "ArgumentType.FileDescriptor" in source + # No frame, and there is nothing to add one from: `ops.py` says why a key + # queued until one would never arrive. + assert "def frame(" not in source + + +def test_the_integers_the_xml_names_but_does_not_define_live_in_our_code(): + """The one real cost of using Hyprland's copy of the XML. + + It names `keymap_format` and `key_state` in the request descriptions and + defines neither enum, so the scanner emits no `IntEnum` for either. Both + are therefore written down with a citation, and this test is what notices + if a future regeneration against a *complete* XML makes them redundant -- + at which point they should be deleted rather than left to drift. + """ + + source = KEYBOARD.read_text() + assert "keymap_format" in source, "the description still refers to it" + assert "class keymap_format" not in source, "...and still does not define it" + assert "class key_state" not in source + + from hhstream_pointer import buttons + from hhstream_pointer.keymap import XKB_V1 + + assert XKB_V1 == 1 + # `wl_pointer.button_state` and `wl_keyboard.key_state` agree on these two, + # which is why there is one table rather than a second that can drift. + assert buttons.STATES["up"] == 0 + assert buttons.STATES["down"] == 1 + + +def test_the_shim_resolves_the_keyboard_relative_import(): + assert "from ..wayland import WlSeat" in KEYBOARD_MANAGER.read_text() @pytest.mark.skipif( @@ -80,6 +154,39 @@ def test_the_protocol_binds_against_the_installed_pywayland(): ) +@pytest.mark.skipif( + not HAVE_PYWAYLAND, + reason="pywayland is not in this environment (it is in the built package)", +) +def test_the_keyboard_protocol_binds_against_the_installed_pywayland(): + from hhstream_pointer._protocol.virtual_keyboard_unstable_v1 import ( + ZwpVirtualKeyboardManagerV1, + ZwpVirtualKeyboardV1, + ) + + assert ZwpVirtualKeyboardManagerV1.name == "zwp_virtual_keyboard_manager_v1" + assert ZwpVirtualKeyboardManagerV1.version == 1 + assert ZwpVirtualKeyboardV1.version == 1 + for request in ("keymap", "key", "modifiers", "destroy"): + assert hasattr(ZwpVirtualKeyboardV1.proxy_class, request) + assert hasattr(ZwpVirtualKeyboardManagerV1.proxy_class, "create_virtual_keyboard") + + +@pytest.mark.skipif( + not HAVE_PYWAYLAND, + reason="pywayland is not in this environment (it is in the built package)", +) +def test_the_backend_binds_the_keyboard_manager_at_version_1_and_survives_its_absence(): + from hhstream_pointer.backend import KEYBOARD_MANAGER_VERSION, WaylandSink + + assert KEYBOARD_MANAGER_VERSION == 1 + # A sink that never connected has no keyboard and says so rather than + # raising: `ops.release_all` asks this question precisely so that a + # compositor with no keyboard global still gets its buttons lifted. + sink = WaylandSink(Path("/nonexistent")) + assert sink.has_keyboard() is False + + @pytest.mark.skipif( not HAVE_PYWAYLAND, reason="pywayland is not in this environment (it is in the built package)",