diff --git a/pkgs/niri-touchscreen-gestures/README.md b/pkgs/niri-touchscreen-gestures/README.md index 3af066a..806659e 100644 --- a/pkgs/niri-touchscreen-gestures/README.md +++ b/pkgs/niri-touchscreen-gestures/README.md @@ -71,6 +71,9 @@ niri-touchscreen-gestures --threshold 40 # Use a specific device (bypasses auto-detection) niri-touchscreen-gestures --device /dev/input/event5 + +# Pick which niri output the touchscreen maps to (only needed with >1 output connected) +niri-touchscreen-gestures --touch-output eDP-1 ``` ### Command-line options @@ -78,9 +81,24 @@ niri-touchscreen-gestures --device /dev/input/event5 - `--config PATH`: Path to TOML configuration file (optional — uses built-in defaults) - `--threshold N` (default: 60): Minimum pixels of movement to register a swipe - `--device /dev/input/eventX`: Explicit evdev device (bypasses auto-detection) +- `--touch-output NAME`: Name of the niri output the touchscreen is mapped to (e.g. `eDP-1`, + matching niri's `input { touch { map-to-output "..." } }` config). Forwarded clicks are placed + at the tapped location by mapping the raw touch coordinate onto this output's logical geometry + (queried from niri's `Outputs` IPC request). If omitted, the daemon auto-selects the sole + enabled output — pass this explicitly once a second monitor is connected. The program must run with access to `/dev/input/event*` devices (typically via the `input` group) and with the `NIRI_SOCKET` environment variable set. +### Forwarded clicks click where you tapped + +Since `wlrctl pointer move` is relative-only (no absolute positioning, and no way to query the +pointer's current position), a forwarded click warps the pointer to the tapped location before +clicking: one large relative move clamps it to niri's logical origin `(0, 0)`, then a second move +by the tap's mapped logical coordinate lands it exactly there. This assumes niri's default +layout (some output at `(0, 0)`, outputs arranged contiguously) — an unusual multi-monitor +arrangement with gaps could make this land in the wrong spot, but this isn't a concern on a +single-display laptop. + ## Configuration The tool ships with **sensible defaults** that match the example below. You only need to provide a config file if you want to customize the mappings. diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/argparser.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/argparser.py index 88ba5bd..a8b9350 100644 --- a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/argparser.py +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/argparser.py @@ -5,6 +5,7 @@ from __future__ import annotations import argparse import logging import os +from dataclasses import dataclass import evdev @@ -14,6 +15,16 @@ from .detector.touchscreen_identifier import identify_touchscreen_via_evdev logger = logging.getLogger(__name__) +@dataclass +class RuntimeConfig: + config: GestureConfig + device: evdev.InputDevice + threshold: int + touch_output: str | None + touch_x_range: tuple[int, int] + touch_y_range: tuple[int, int] + + def get_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Touchscreen gesture detector for niri" @@ -33,12 +44,31 @@ def get_parser() -> argparse.ArgumentParser: "--device", help="Explicit evdev device path (default: auto-detect first touchscreen)", ) + parser.add_argument( + "--touch-output", + default=None, + help=( + "Name of the niri output (e.g. eDP-1) the touchscreen is mapped to " + "(used to place forwarded clicks at the tapped location). Required " + "only if more than one niri output is connected." + ), + ) return parser -def process_args( - args: argparse.Namespace, -) -> tuple[GestureConfig, evdev.InputDevice, int]: +def get_touch_absinfo( + device: evdev.InputDevice, +) -> tuple[tuple[int, int], tuple[int, int]]: + """Returns ((x_min, x_max), (y_min, y_max)) for the device's touch axes.""" + absinfo = dict(device.capabilities(absinfo=True).get(evdev.ecodes.EV_ABS, [])) + x = absinfo.get(evdev.ecodes.ABS_MT_POSITION_X) or absinfo.get(evdev.ecodes.ABS_X) + y = absinfo.get(evdev.ecodes.ABS_MT_POSITION_Y) or absinfo.get(evdev.ecodes.ABS_Y) + if x is None or y is None: + raise RuntimeError(f"{device.path} doesn't report an ABS_MT_POSITION_X/Y range") + return (x.min, x.max), (y.min, y.max) + + +def process_args(args: argparse.Namespace) -> RuntimeConfig: if args.config is None: config = GestureConfig( **{ @@ -73,4 +103,13 @@ def process_args( device = evdev.InputDevice(args.device) logger.info(f"niri-touchscreen-gestures: using device {device.path}") - return config, device, args.threshold + touch_x_range, touch_y_range = get_touch_absinfo(device) + + return RuntimeConfig( + config=config, + device=device, + threshold=args.threshold, + touch_output=args.touch_output, + touch_x_range=touch_x_range, + touch_y_range=touch_y_range, + ) diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/coords.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/coords.py new file mode 100644 index 0000000..554d7f1 --- /dev/null +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/coords.py @@ -0,0 +1,14 @@ +"""Maps a touchscreen device coordinate onto niri's logical screen space.""" + + +def map_to_logical( + value: int, touch_min: int, touch_max: int, output_offset: int, output_extent: int +) -> int: + """Map `value` (in the touch device's own coordinate range) to an absolute + logical-pixel coordinate within an output spanning + [output_offset, output_offset + output_extent).""" + span = touch_max - touch_min + if span <= 0: + return output_offset + frac = (value - touch_min) / span + return output_offset + round(frac * output_extent) diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/detector/gestures.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/detector/gestures.py index 9c2c8ce..346591e 100644 --- a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/detector/gestures.py +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/detector/gestures.py @@ -71,7 +71,7 @@ class GestureDetector: def __init__( self, config: GestureConfig, - dispatch: Callable[[GestureAction, float], None], + dispatch: Callable[[GestureAction, float, tuple[int, int] | None], None], get_app_id: Callable[[], str | None], threshold: int = 60, timer_factory: Callable[..., threading.Timer] = threading.Timer, @@ -115,13 +115,15 @@ class GestureDetector: action = self.config.resolve(signal.key, self._current_app_id()) if isinstance(action, ForwardScroll): self._scroll_active = True - self.dispatch(action, signal.delta) + self.dispatch(action, signal.delta, None) elif isinstance(signal, _TapSignal): self._process_tap(signal) def _process_tap(self, tap: _TapSignal) -> None: if tap.kind == "long-tap": - self._resolve_and_dispatch("1-finger-long-tap", self._current_app_id()) + self._resolve_and_dispatch( + "1-finger-long-tap", self._current_app_id(), (tap.x, tap.y) + ) return with self._lock: @@ -142,7 +144,9 @@ class GestureDetector: pending.timer.cancel() app_id = self._current_app_id() timer = self.timer_factory( - DOUBLE_TAP_WINDOW_S, self._resolve_pending_tap, args=(app_id,) + DOUBLE_TAP_WINDOW_S, + self._resolve_pending_tap, + args=(app_id, tap.x, tap.y), ) self._pending_tap = _PendingTap( timer=timer, x=tap.x, y=tap.y, time=tap.time, app_id=app_id @@ -151,18 +155,20 @@ class GestureDetector: timer.start() if is_second_tap: - self._resolve_and_dispatch("1-finger-double-tap", app_id) + self._resolve_and_dispatch("1-finger-double-tap", app_id, (tap.x, tap.y)) - def _resolve_pending_tap(self, app_id: str | None) -> None: + def _resolve_pending_tap(self, app_id: str | None, x: int, y: int) -> None: with self._lock: self._pending_tap = None - self._resolve_and_dispatch("1-finger-tap", app_id) + self._resolve_and_dispatch("1-finger-tap", app_id, (x, y)) - def _resolve_and_dispatch(self, key: str, app_id: str | None) -> None: + def _resolve_and_dispatch( + self, key: str, app_id: str | None, touch_xy: tuple[int, int] | None = None + ) -> None: logger.info(f"Detected {key=} {app_id=}") action = self.config.resolve(key, app_id) if action is not None: - self.dispatch(action, 0.0) + self.dispatch(action, 0.0, touch_xy) def _handle_event( diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/forwarder.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/forwarder.py index f26b11b..60f1223 100644 --- a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/forwarder.py +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/forwarder.py @@ -9,8 +9,26 @@ from typing import Literal logger = logging.getLogger(__name__) -def send_click(button: Literal["left", "right"]) -> None: - logger.info(f"niri-touchscreen-gestures: forwarding click {button=}") +# Larger than any realistic logical-layout size, to reliably clamp the +# pointer to the logical origin (0, 0) regardless of where it currently is. +_WARP_MAGNITUDE = 100_000 + + +def send_click_at(button: Literal["left", "right"], x: int, y: int) -> None: + """Move the pointer to the absolute logical coordinate (x, y) and click. + + wlrctl's `pointer move` is relative-only and there's no way to query the + pointer's current position, so we warp it to the logical origin first + (niri places the primary output there and arranges outputs contiguously, + so this reliably clamps regardless of the pointer's prior position) and + then move by the exact target offset. + """ + logger.info(f"niri-touchscreen-gestures: forwarding click {button=} at ({x}, {y})") + subprocess.run( + ["wlrctl", "pointer", "move", str(-_WARP_MAGNITUDE), str(-_WARP_MAGNITUDE)], + check=True, + ) + subprocess.run(["wlrctl", "pointer", "move", str(x), str(y)], check=True) subprocess.run(["wlrctl", "pointer", "click", button], check=True) diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/main.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/main.py index da80bd7..7aa251e 100644 --- a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/main.py +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/main.py @@ -1,8 +1,10 @@ import logging +from typing import Any, Callable from niri_touchscreen_gestures import forwarder, nirictl from niri_touchscreen_gestures.actions import ForwardClick, ForwardScroll, GestureAction from niri_touchscreen_gestures.argparser import get_parser, process_args +from niri_touchscreen_gestures.coords import map_to_logical from niri_touchscreen_gestures.detector.gestures import GestureDetector logging.basicConfig(level=logging.INFO) @@ -10,14 +12,49 @@ logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) -def dispatch(action: GestureAction, delta: float) -> None: - logger.info(f"niri-touchscreen-gestures: dispatching {action=} {delta=}") - if isinstance(action, ForwardClick): - forwarder.send_click(action.button) - elif isinstance(action, ForwardScroll): - forwarder.send_scroll(delta) - else: - nirictl.send_niri_action(action) +def resolve_touch_output( + outputs: dict[str, Any], requested_name: str | None +) -> dict[str, Any]: + """Returns the `logical` geometry of the output the touchscreen maps to.""" + if requested_name is not None: + output = outputs.get(requested_name) + if output is None or output.get("logical") is None: + raise RuntimeError(f"Output {requested_name!r} not found or not enabled") + return output["logical"] + + enabled = {name: o for name, o in outputs.items() if o.get("logical") is not None} + if len(enabled) == 1: + return next(iter(enabled.values()))["logical"] + raise RuntimeError( + f"Expected exactly one enabled output, found {list(enabled)}. " + "Pass --touch-output NAME to pick which one the touchscreen maps to." + ) + + +def make_dispatch( + touch_x_range: tuple[int, int], + touch_y_range: tuple[int, int], + output_logical: dict[str, Any], +) -> Callable[[GestureAction, float, tuple[int, int] | None], None]: + def dispatch( + action: GestureAction, delta: float, touch_xy: tuple[int, int] | None + ) -> None: + logger.info(f"niri-touchscreen-gestures: dispatching {action=} {delta=} {touch_xy=}") + if isinstance(action, ForwardClick): + touch_x, touch_y = touch_xy if touch_xy is not None else (0, 0) + x = map_to_logical( + touch_x, *touch_x_range, output_logical["x"], output_logical["width"] + ) + y = map_to_logical( + touch_y, *touch_y_range, output_logical["y"], output_logical["height"] + ) + forwarder.send_click_at(action.button, x, y) + elif isinstance(action, ForwardScroll): + forwarder.send_scroll(delta) + else: + nirictl.send_niri_action(action) + + return dispatch def get_focused_app_id() -> str | None: @@ -27,16 +64,20 @@ def get_focused_app_id() -> str | None: def main_runtime() -> None: logger.info("niri-touchscreen-gestures: starting") - config, dev, threshold = process_args(get_parser().parse_args()) + runtime = process_args(get_parser().parse_args()) + + output_logical = resolve_touch_output(nirictl.get_outputs(), runtime.touch_output) detector = GestureDetector( - config, - dispatch=dispatch, + runtime.config, + dispatch=make_dispatch( + runtime.touch_x_range, runtime.touch_y_range, output_logical + ), get_app_id=get_focused_app_id, - threshold=threshold, + threshold=runtime.threshold, ) - for ev in dev.read_loop(): + for ev in runtime.device.read_loop(): detector.handle_event(ev) diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/nirictl.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/nirictl.py index 62ed497..2db1cb7 100644 --- a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/nirictl.py +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/nirictl.py @@ -72,3 +72,14 @@ def get_focused_window() -> dict[str, Any] | None: """Query niri for the currently focused window (includes its `app_id`).""" reply = send_niri_command("FocusedWindow") return reply.get("Ok", {}).get("FocusedWindow") + + +def get_outputs() -> dict[str, Any]: + """Query niri for all connected outputs, keyed by output name (e.g. "eDP-1"). + + Each output's `logical` field (None if disabled) gives its position/size + in niri's global logical coordinate space: {x, y, width, height, scale, + transform}. + """ + reply = send_niri_command("Outputs") + return reply.get("Ok", {}).get("Outputs", {}) diff --git a/pkgs/niri-touchscreen-gestures/tests/detector/test_gestures.py b/pkgs/niri-touchscreen-gestures/tests/detector/test_gestures.py index 5cacc2f..49cc4db 100644 --- a/pkgs/niri-touchscreen-gestures/tests/detector/test_gestures.py +++ b/pkgs/niri-touchscreen-gestures/tests/detector/test_gestures.py @@ -1,5 +1,6 @@ from niri_touchscreen_gestures.actions import ForwardClick from niri_touchscreen_gestures.config import GestureConfig +from niri_touchscreen_gestures.coords import map_to_logical from niri_touchscreen_gestures.detector.classifiers import classify_tap, count_active_fingers from niri_touchscreen_gestures.detector.gestures import ( _PendingTap, @@ -8,6 +9,21 @@ from niri_touchscreen_gestures.detector.gestures import ( ) +class TestMapToLogical: + def test_maps_touch_range_onto_output_extent(self): + assert map_to_logical(0, 0, 4095, output_offset=0, output_extent=1920) == 0 + assert map_to_logical(4095, 0, 4095, output_offset=0, output_extent=1920) == 1920 + assert map_to_logical(2048 - 1, 0, 4095, output_offset=0, output_extent=1920) == 960 + + def test_offsets_by_output_position(self): + # A second output starting at logical x=1920. + assert map_to_logical(0, 0, 4095, output_offset=1920, output_extent=1920) == 1920 + assert map_to_logical(4095, 0, 4095, output_offset=1920, output_extent=1920) == 3840 + + def test_degenerate_touch_range_falls_back_to_offset(self): + assert map_to_logical(50, 100, 100, output_offset=42, output_extent=1920) == 42 + + class FakeTimer: """Records the callback instead of scheduling it on a real thread, so debounce tests can fire (or skip) it deterministically.""" @@ -46,7 +62,9 @@ class TestTapDebounce: dispatched = [] detector = GestureDetector( config or GestureConfig(), - dispatch=lambda action, delta: dispatched.append((action, delta)), + dispatch=lambda action, delta, touch_xy: dispatched.append( + (action, delta, touch_xy) + ), get_app_id=lambda: None, timer_factory=FakeTimer, ) @@ -63,7 +81,7 @@ class TestTapDebounce: assert isinstance(pending, _PendingTap) pending.timer.fire() - assert dispatched == [(ForwardClick(button="left"), 0.0)] + assert dispatched == [(ForwardClick(button="left"), 0.0, (100, 100))] def test_second_tap_within_window_cancels_timer_and_dispatches_double_tap(self): config = GestureConfig( @@ -82,7 +100,7 @@ class TestTapDebounce: assert first_timer.cancelled assert detector._pending_tap is None - assert dispatched == [(ForwardClick(button="right"), 0.0)] + assert dispatched == [(ForwardClick(button="right"), 0.0, (105, 98))] def test_second_tap_outside_window_is_treated_as_a_new_lone_tap(self): config = GestureConfig( @@ -100,7 +118,7 @@ class TestTapDebounce: assert dispatched == [] detector._pending_tap.timer.fire() - assert dispatched == [(ForwardClick(button="left"), 0.0)] + assert dispatched == [(ForwardClick(button="left"), 0.0, (100, 100))] def test_long_tap_dispatches_immediately(self): config = GestureConfig(**{"global": {"1-finger-long-tap": "forward:click-right"}}) @@ -108,7 +126,7 @@ class TestTapDebounce: detector._process_signal(_TapSignal("long-tap", 100, 100, 1.0)) - assert dispatched == [(ForwardClick(button="right"), 0.0)] + assert dispatched == [(ForwardClick(button="right"), 0.0, (100, 100))] assert detector._pending_tap is None