Stage 1: the driver learns to type
`zwp_virtual_keyboard_v1`, spoken by the process that already speaks
`zwlr_virtual_pointer_v1`. One device for the seat, one keymap uploaded
once, keysym names on our socket and evdev codes only on the Wayland
request -- the division buttons.py already draws.
keymap.py is the new seam, and it holds the three decisions that have a
wrong version which looks right:
* A capital is the MASK, not a synthetic Shift keycode. Hyprland's
virtual keyboard never runs updateXkbStateWithKey, so a virtual
KEY_LEFTSHIFT changes no modifier state at all -- and sending both
is how a toolkit applies Shift twice.
* A modifier is whatever the keymap says is one, measured by pressing
each key in a throwaway xkb state. Not a name list: `@` on `de` is a
level-three symbol, and a Shift-only special case types the wrong
character. (The measured set is also smaller than the canonical one,
because no keycode on us/pc105 carries Meta or Hyper.)
* A lock is not a modifier. Caps_Lock reports a *locked* mask, so
`type` refuses while it is held rather than guessing the case.
The whole string resolves before anything is emitted, and every refusal
names the scalar INDEX, never the character: these messages reach the
driver's log and the string is a password as often as not.
Folding in the review's changes 1, 2, 3 and 6:
1 a Rejected now carries a `kind`. A bad keysym or an unmappable
character is `invalid_argument`; a missing keyboard global is
`refused`. Without the token the broker would have to tell exit 2
from exit 10 by reading English, and _drive maps every `ok: false`
to driver_refused today.
2 the keymap `size` on the wire includes the trailing NUL, and the fd
outlives a roundtrip rather than a flush. Hyprland mmaps exactly
that many bytes and hands the pointer to xkb_keymap_new_from_string.
3 release_all lifts buttons, then keys in press order, then zeroes the
mask -- and the mask only if something set it, so a compositor with
no keyboard global still gets its buttons lifted. One release_all is
the whole of expiry; an exception in the key half would abandon it.
6 `key` and `type` never call _aimed(). A keyboard has no output, and
one test deliberately never warps so that stays true.
Also: `--xkb-layout/-model/-variant/-options`, compiled BEFORE any
Wayland call so a bad layout is exit 2 rather than exit 10; a comma in
the layout refused outright, because v1 always sends group 0 and
xkbcommon would hand back a second group nothing could reach; the
keymap uploaded after connect and before listen, with one
modifiers(0,0,0,0) after it; and xkbcommon as a hard, non-optional
dependency -- an optional one would let test_keymap.py skip, and the
unmappable-character path is the one that must not rot.
nix develop -c python -m pytest tests/pointer tests/sessions/unit -q
549 passed in 25.70s
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GhNPM6rGcuzxocM1nATnuM
This commit is contained in:
1 parent
19e484b388
commit
f931858f30
19 files changed
+2461
-107
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
+95
@@ -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
|
||||
+176
@@ -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()
|
||||
<pywayland.protocol.wayland.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
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
+255
-13
@@ -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")
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user