#!/usr/bin/env python3 """A Wayland client that says where it was clicked, in its own words. The VM checks need two things no application in nixpkgs gives them together: * **a window that lands in its container.** The broker stamps a session's identity into the environment only (``$HHSTREAM_APP_ID``, see ``hhstreamd/launcher.py``), because the alternative -- a per-app ``--app-id`` flag -- would have to come out of the allowlist. ``foot`` and ``wev`` ignore the environment and keep their own class, so their windows match no per-session rule and are swept into quarantine. This client reads the variable and sets ``xdg_toplevel.set_app_id`` to it, which is what the rule ``match:initial_class ^hh-$`` is written against. * **a report of pointer events from the application's side.** PLAN ยง14 is explicit that "a click lands where aimed" must be verified by reading back *the application's* state and not by comparing pixels: a pixel comparison proves the compositor drew a cursor, not that the client was told about a button. Every event below is printed as the client received it, with the surface-local coordinates the compositor sent, and flushed -- the broker captures stdout into the session log, so ``hhstream session logs`` is the read-back. It is deliberately minimal and deliberately loud: it prints what it bound, what size it was configured at, and every pointer event, so a check that fails says whether the window was never mapped, never entered, or entered somewhere other than where the warp aimed. """ from __future__ import annotations import argparse import mmap import os import signal import struct import sys from pywayland.client import Display from pywayland.protocol.wayland import WlCompositor, WlPointer, WlSeat, WlShm from pywayland.protocol.xdg_shell import XdgWmBase #: Opaque 32-bit colour. Something has to be in the buffer for the compositor #: to map the surface at all, and a flat fill is the least that will do. FILL = 0xFF3050A0 #: Fallback size for a compositor that configures 0x0 (meaning "you choose"). DEFAULT_SIZE = (640, 360) def say(line: str) -> None: """One line, flushed. Unbuffered because the reader is a log tail.""" print(line, flush=True) class Target: def __init__(self, app_id: str, title: str, windows: int) -> None: self.app_id = app_id self.title = title self.windows = windows self.display: Display | None = None self.compositor = None self.shm = None self.wm_base = None self.seat = None self.surfaces: list[_Window] = [] #: Last position the compositor reported, per surface, so a button #: event can be printed with the place it happened. The protocol does #: not put coordinates on `button`; `enter` and `motion` carry them. self.pointer = None # -- setup --------------------------------------------------------- def run(self) -> int: self.display = Display() self.display.connect() registry = self.display.get_registry() registry.dispatcher["global"] = self._on_global self.display.roundtrip() missing = [ name for name, value in ( ("wl_compositor", self.compositor), ("wl_shm", self.shm), ("xdg_wm_base", self.wm_base), ("wl_seat", self.seat), ) if value is None ] if missing: say(f"target: FATAL missing globals: {', '.join(missing)}") return 1 self.wm_base.dispatcher["ping"] = lambda base, serial: base.pong(serial) self.seat.dispatcher["capabilities"] = self._on_capabilities for index in range(self.windows): self.surfaces.append(_Window(self, index)) self.display.roundtrip() say(f"target: app_id={self.app_id} windows={self.windows} pid={os.getpid()}") while True: # Blocking dispatch: this process exists to report events, so there # is nothing to do between them and nothing to poll for. if self.display.dispatch(block=True) < 0: say("target: display disconnected") return 1 def _on_global(self, registry, global_id: int, interface: str, version: int) -> None: if interface == WlCompositor.name: self.compositor = registry.bind(global_id, WlCompositor, min(version, 4)) elif interface == WlShm.name: self.shm = registry.bind(global_id, WlShm, 1) elif interface == XdgWmBase.name: self.wm_base = registry.bind(global_id, XdgWmBase, min(version, 2)) elif interface == WlSeat.name and self.seat is None: self.seat = registry.bind(global_id, WlSeat, min(version, 5)) def _on_capabilities(self, seat, capabilities: int) -> None: if not capabilities & WlSeat.capability.pointer.value: # Said out loud: a seat with no pointer capability is the headless # case where nothing has ever created a virtual pointer, and it is # indistinguishable from "the warp did not arrive" unless reported. say("target: seat has no pointer capability yet") return if self.pointer is not None: return self.pointer = seat.get_pointer() self.pointer.dispatcher["enter"] = self._on_enter self.pointer.dispatcher["leave"] = self._on_leave self.pointer.dispatcher["motion"] = self._on_motion self.pointer.dispatcher["button"] = self._on_button say("target: pointer bound") # -- pointer ------------------------------------------------------- def _window_of(self, surface) -> "_Window | None": for window in self.surfaces: if window.surface == surface: return window return None def _on_enter(self, pointer, serial, surface, x, y) -> None: window = self._window_of(surface) if window is not None: window.at = (x, y) say(f"pointer enter window={_name(window)} x={x:.2f} y={y:.2f}") def _on_leave(self, pointer, serial, surface) -> None: say(f"pointer leave window={_name(self._window_of(surface))}") def _on_motion(self, pointer, time, x, y) -> None: for window in self.surfaces: # Motion carries no surface; the focused one is whichever was # entered last, and with one window per container that is the only # one. Recording it on all of them keeps the button line honest # without inventing a focus model this client does not need. window.at = (x, y) say(f"pointer motion x={x:.2f} y={y:.2f}") def _on_button(self, pointer, serial, time, button, state) -> None: where = self.surfaces[0].at if self.surfaces else None position = "x=? y=?" if where is None else f"x={where[0]:.2f} y={where[1]:.2f}" say( f"pointer button code={button} state=" f"{'pressed' if state else 'released'} {position}" ) def _name(window: "_Window | None") -> str: return "?" if window is None else str(window.index) class _Window: """One toplevel: a surface, its xdg wrapper, and an shm buffer.""" def __init__(self, target: Target, index: int) -> None: self.target = target self.index = index self.at: tuple[float, float] | None = None self.size = DEFAULT_SIZE self.buffer = None self._pool = None self._map: mmap.mmap | None = None self.surface = target.compositor.create_surface() self.xdg_surface = target.wm_base.get_xdg_surface(self.surface) self.xdg_surface.dispatcher["configure"] = self._on_configure self.toplevel = self.xdg_surface.get_toplevel() # The whole reason this program exists rather than `wev`. self.toplevel.set_app_id(target.app_id) self.toplevel.set_title(f"{target.title}-{index}") self.toplevel.dispatcher["configure"] = self._on_toplevel_configure self.toplevel.dispatcher["close"] = lambda *_: sys.exit(0) self.surface.commit() def _on_toplevel_configure(self, toplevel, width, height, states) -> None: if width and height: self.size = (width, height) def _on_configure(self, xdg_surface, serial) -> None: xdg_surface.ack_configure(serial) self._paint() say(f"target: window {self.index} configured {self.size[0]}x{self.size[1]}") def _paint(self) -> None: width, height = self.size stride = width * 4 size = stride * height if self._map is None or self._map.size() < size: self._allocate(size) # A flat fill, written once per resize: the pixels are not the subject # of any assertion, they only make the surface mappable. self._map.seek(0) self._map.write(struct.pack(" None: fd = os.memfd_create(f"hhs-target-{self.index}", 0) os.ftruncate(fd, size) self._map = mmap.mmap(fd, size) self._pool = self.target.shm.create_pool(fd, size) os.close(fd) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( prog="hhs-pointer-target", description="A Wayland window that reports the pointer events it receives.", ) parser.add_argument( "--app-id", default=None, help="xdg_toplevel app id; the default is $HHSTREAM_APP_ID, which is how " "a session's window rule finds its container", ) parser.add_argument("--title", default="hhs-target") parser.add_argument( "--windows", type=int, default=1, help="how many toplevels to open, all with the same app id", ) args = parser.parse_args(argv) app_id = args.app_id or os.environ.get("HHSTREAM_APP_ID") if not app_id: print( "hhs-pointer-target: no --app-id and no $HHSTREAM_APP_ID; refusing to " "guess, because the app id is the whole point of this program", file=sys.stderr, ) return 2 # The broker kills the process group; exit on the first signal rather than # leaving the compositor to notice a dead client. signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) signal.signal(signal.SIGINT, lambda *_: sys.exit(0)) return Target(app_id, args.title, max(1, args.windows)).run() if __name__ == "__main__": sys.exit(main())