From df2540c6b7f29e68bdf6e43473d1b53a4193633d Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Tue, 28 Jul 2026 22:31:03 -0400 Subject: [PATCH] trying new lib --- .../tiler/niri-touchscreen-gestures.nix | 131 ++++++++++++ pkgs/flake-patched.nix | 191 ++++++++++++++++++ pkgs/niri-touchscreen-gestures/default.nix | 3 +- .../niri_touchscreen_gestures/__init__.py | 12 +- .../niri_touchscreen_gestures/coords.py | 8 + .../niri_touchscreen_gestures/forwarder.py | 40 ++-- .../niri_touchscreen_gestures/logger.py | 9 + .../niri_touchscreen_gestures/main.py | 14 +- .../tests/test_forwarder.py | 52 +++++ 9 files changed, 434 insertions(+), 26 deletions(-) create mode 100644 modules/nixos/desktop/tiler/niri-touchscreen-gestures.nix create mode 100644 pkgs/flake-patched.nix create mode 100644 pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/logger.py create mode 100644 pkgs/niri-touchscreen-gestures/tests/test_forwarder.py diff --git a/modules/nixos/desktop/tiler/niri-touchscreen-gestures.nix b/modules/nixos/desktop/tiler/niri-touchscreen-gestures.nix new file mode 100644 index 0000000..b54bde4 --- /dev/null +++ b/modules/nixos/desktop/tiler/niri-touchscreen-gestures.nix @@ -0,0 +1,131 @@ +{ config +, lib +, pkgs +, ... +}: +let + cfg = config.skyg.nixos.desktop.tiler.niri.touchscreen-gestures; + skygUser = config.skyg.user; + + gestureArgs = + lib.optionals (cfg.touchOutput != null) [ "--touch-output" cfg.touchOutput ] + ++ lib.optionals (cfg.device != null) [ "--device" cfg.device ] + ++ lib.optionals (cfg.configFile != null) [ "--config" cfg.configFile ] + ++ [ "--threshold" (toString cfg.threshold) ]; +in +{ + options = { + skyg.nixos.desktop.tiler.niri.touchscreen-gestures = { + enable = lib.mkEnableOption "touchscreen gesture support for niri"; + + touchOutput = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + example = "eDP-1"; + description = '' + Name of the niri output the touchscreen is mapped to, used to place + forwarded taps at the position actually touched. Should match the + `touch { map-to-output }` target in the niri config. + + Required whenever more than one output is enabled — the daemon cannot + guess which one the panel corresponds to and will refuse to start. + ''; + }; + + device = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + example = "/dev/input/event5"; + description = '' + Explicit evdev device path. Leave null to auto-detect, which fails if + the machine exposes more than one touchscreen. + ''; + }; + + threshold = lib.mkOption { + type = lib.types.ints.positive; + default = 60; + description = "Minimum pixels of movement before a swipe registers."; + }; + + configFile = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + example = "%h/.config/niri/gestures.toml"; + description = '' + Path to a TOML gesture config. Leave null to use the built-in defaults + (3-finger swipes for workspace/column navigation, 4-finger for + overview). systemd specifiers such as `%h` are expanded. + + The file must exist if set — the daemon treats a missing config as a + fatal error rather than falling back to defaults. + ''; + }; + }; + }; + + config = lib.mkIf cfg.enable { + assertions = [ + { + assertion = config.skyg.nixos.desktop.tiler.niri.enable; + message = '' + skyg.nixos.desktop.tiler.niri.touchscreen-gestures.enable requires + skyg.nixos.desktop.tiler.niri.enable — the daemon drives niri over its + IPC socket and has no meaning under another compositor. + ''; + } + ]; + + environment.systemPackages = [ + pkgs.niri-touchscreen-gestures + # dotool provides the absolute pointer positioning used to forward taps. + # ydotool is deliberately not used here: its `mousemove --absolute` is + # really a warp-to-corner plus a *relative* delta, so the compositor's + # pointer acceleration scales it (measured at exactly 2x on this layout, + # saturating at the screen edge). dotool registers a uinput device with a + # declared absolute axis range instead, which no acceleration curve can + # distort. + pkgs.dotool + ]; + + # dotool writes to /dev/uinput, which this makes group-accessible (0660, + # group "uinput") and loads the kernel module for. Note that dotool ships no + # udev rules of its own in nixpkgs, so this is the only thing granting access. + hardware.uinput.enable = true; + + # "input" is already granted by tiler.enable (needed to read /dev/input for + # the touchscreen); "uinput" is what hardware.uinput.enable creates. + users.users.${skygUser.name}.extraGroups = [ "input" "uinput" ]; + + systemd.user.services = { + # Registering a uinput device costs a noticeable startup delay, so keep one + # long-running daemon rather than paying it on every tap. + dotoold = { + description = "dotoold - uinput backend for absolute pointer positioning"; + after = [ "graphical-session.target" ]; + partOf = [ "graphical-session.target" ]; + wantedBy = [ "graphical-session.target" ]; + serviceConfig = { + ExecStart = lib.getExe' pkgs.dotool "dotoold"; + Restart = "on-failure"; + RestartSec = 2; + }; + }; + + niri-touchscreen-gestures = { + description = "Touchscreen gesture bridge for niri"; + # Needs the niri IPC socket, which only exists once the compositor is up, + # and dotoold's virtual device before it can forward a tap. + after = [ "graphical-session.target" "dotoold.service" ]; + wants = [ "dotoold.service" ]; + partOf = [ "graphical-session.target" ]; + wantedBy = [ "graphical-session.target" ]; + serviceConfig = { + ExecStart = "${lib.getExe pkgs.niri-touchscreen-gestures} ${lib.escapeShellArgs gestureArgs}"; + Restart = "on-failure"; + RestartSec = 2; + }; + }; + }; + }; +} diff --git a/pkgs/flake-patched.nix b/pkgs/flake-patched.nix new file mode 100644 index 0000000..d5d254b --- /dev/null +++ b/pkgs/flake-patched.nix @@ -0,0 +1,191 @@ +{ + description = "colibrì — run GLM-5.2 (744B MoE) on a consumer machine with ~25 GB RAM"; + + # Reproducibility: these inputs track a branch, so torch/numpy/etc. float across + # rebuilds. For deterministic builds run `nix flake lock` once and COMMIT the + # generated flake.lock (it pins each input to a commit SHA). (#D2) + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = { + self, + nixpkgs, + flake-utils, + }: + flake-utils.lib.eachDefaultSystem ( + system: let + pkgs = import nixpkgs {inherit system;}; + + # Python with the packages needed by the offline converter tools + pythonEnv = pkgs.python3.withPackages ( + ps: + with ps; [ + torch + safetensors + huggingface-hub + numpy + tokenizers + datasets + ] + ); + + colibri = pkgs.stdenv.mkDerivation { + pname = "colibri"; + version = "1.0"; + src = ./.; + + nativeBuildInputs = with pkgs; [makeWrapper]; + + buildInputs = with pkgs; [ + gcc + gmp + ]; + + # python3 is needed by checkPhase: `make test-c` shells out to + # `python3 tools/run_tests.py` (see c/Makefile, PYTHON ?= python3). + nativeCheckInputs = with pkgs; [python3]; + + # Use x86-64-v3 (AVX2) for a portable binary; override with ARCH=native for local builds + ARCH = + if pkgs.stdenv.hostPlatform.isx86_64 + then "x86-64-v3" + else "native"; + + buildPhase = '' + runHook preBuild + make -C c glm ARCH="$ARCH" + runHook postBuild + ''; + + installPhase = '' + runHook preInstall + + # Self-contained layout under $out/lib/colibri that mirrors the + # source tree `coli` runs in (see the path-resolution logic at the + # top of c/coli): the engine, the coli CLI script, the support + # modules it imports (openai_server.py, resource_plan.py, + # doctor.py), and tools/ all sit next to each other. + mkdir -p $out/lib/colibri/tools $out/bin + cp c/glm $out/lib/colibri/glm + cp c/coli $out/lib/colibri/coli + chmod +x $out/lib/colibri/coli + cp c/openai_server.py c/resource_plan.py c/doctor.py c/version.py \ + $out/lib/colibri/ + cp -r c/tools/* $out/lib/colibri/tools/ + + # $out/bin holds the user-facing entry points. + ln -s ../lib/colibri/glm $out/bin/glm + + # Wrap coli: point it at the bundled engine (COLI_ENGINE) so it is + # found by default, and at the module dir (PYTHONPATH) so + # `import openai_server` / `resource_plan` / `doctor` resolve. + makeWrapper ${pythonEnv}/bin/python $out/bin/coli \ + --add-flags "$out/lib/colibri/coli" \ + --set-default COLI_ENGINE "$out/lib/colibri/glm" \ + --set PYTHONPATH "$out/lib/colibri:${pythonEnv}/${pkgs.python3.sitePackages}" + runHook postInstall + ''; + + checkPhase = '' + runHook preCheck + cd c + make test-c + cd .. + runHook postCheck + ''; + + doCheck = true; + + meta = with pkgs.lib; { + description = "Run GLM-5.2 (744B MoE) on a consumer machine with ~25 GB RAM"; + homepage = "https://github.com/JustVugg/colibri"; + license = licenses.asl20; + platforms = with platforms; linux ++ darwin; + mainProgram = "coli"; + }; + }; + + # ROCm/HIP variant: same package as `colibri`, plus the optional GPU + # expert tier built for AMD via the engine's HIP=1 path (see c/Makefile). + # Tuned for the Framework Desktop's Radeon 8060S/8050S iGPU == gfx1151. + # Linux-only (HIP=1 errors out on non-Linux in the Makefile). + # + # nix build .#colibri-rocm + # COLI_MODEL=/nvme/glm52_i4 CUDA_EXPERT_GB=auto nix run .#colibri-rocm -- chat + # + # If a gfx1151 kernel misbehaves on your ROCm version, run with + # HSA_OVERRIDE_GFX_VERSION=11.0.0 + colibri-rocm = colibri.overrideAttrs (old: { + pname = "colibri-rocm"; + + buildInputs = + old.buildInputs + ++ (with pkgs.rocmPackages; [clr rocm-runtime hipblas]); + + buildPhase = '' + runHook preBuild + make -C c glm \ + ARCH="$ARCH" \ + HIP=1 \ + HIP_ARCH="gfx1151" \ + ROCM_HOME="${pkgs.rocmPackages.clr}" \ + HIPCC="${pkgs.rocmPackages.clr}/bin/hipcc" + runHook postBuild + ''; + + # test-c would relink the engine WITHOUT HIP=1 (clobbering the GPU + # build), and the GPU path needs real hardware — so skip the suite. + doCheck = false; + + meta = old.meta // {platforms = pkgs.lib.platforms.linux;}; + }); + in { + packages = + { + default = colibri; + inherit colibri; + } + # Only expose the ROCm package on Linux (HIP build is Linux-only). + // pkgs.lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { + inherit colibri-rocm; + }; + + apps = { + default = { + type = "app"; + program = pkgs.lib.getExe colibri; + }; + glm = { + type = "app"; + program = "${colibri}/share/colibri/glm"; + }; + }; + + formatter = pkgs.alejandra; + + devShells.default = pkgs.mkShell { + inputsFrom = [colibri]; + + packages = with pkgs; [ + pythonEnv + gcc + gnumake + clang-tools # clangd / clang-tidy for IDE support + pkg-config + ]; + + shellHook = '' + echo "🐦 colibrì dev shell" + echo " gcc: $(gcc --version | head -1)" + echo " python: $(python3 --version)" + echo "" + echo "Build the engine: make -C c glm" + echo "Run the converter: python c/coli convert --model /path/to/glm52_i4" + echo "Chat: COLI_MODEL=/path/to/glm52_i4 ./c/glm ..." + ''; + }; + } + ); +} diff --git a/pkgs/niri-touchscreen-gestures/default.nix b/pkgs/niri-touchscreen-gestures/default.nix index 879c88c..89918bb 100644 --- a/pkgs/niri-touchscreen-gestures/default.nix +++ b/pkgs/niri-touchscreen-gestures/default.nix @@ -1,6 +1,7 @@ { lib , python3 , wlrctl +, ydotool , ... }: @@ -30,7 +31,7 @@ python3.pkgs.buildPythonApplication { "--prefix" "PATH" ":" - (lib.makeBinPath [ wlrctl ]) + (lib.makeBinPath [ wlrctl ydotool ]) ]; meta = { diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/__init__.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/__init__.py index 3dc1f76..0ab3ad5 100644 --- a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/__init__.py +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/__init__.py @@ -1 +1,11 @@ -__version__ = "0.1.0" +import os +from datetime import datetime, timezone + +__version__ = os.environ.get( + "BUILD_VERSION", + datetime.now(timezone.utc).strftime("%Y.%m.%d%H%M%S"), +) + + +if __name__ == "__main__": + print(__version__) diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/coords.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/coords.py index 554d7f1..449c7d1 100644 --- a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/coords.py +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/coords.py @@ -1,5 +1,9 @@ """Maps a touchscreen device coordinate onto niri's logical screen space.""" +import logging + +logger = logging.getLogger(__name__) + def map_to_logical( value: int, touch_min: int, touch_max: int, output_offset: int, output_extent: int @@ -7,6 +11,10 @@ def map_to_logical( """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).""" + logger.info( + f"niri-touchscreen-gestures: mapping {value=} to logical space with {touch_min=}, {touch_max=}, {output_offset=}, {output_extent=}" + ) + span = touch_max - touch_min if span <= 0: return output_offset diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/forwarder.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/forwarder.py index 60f1223..f428314 100644 --- a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/forwarder.py +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/forwarder.py @@ -1,6 +1,8 @@ """Forwards synthetic input to whatever window currently has compositor -focus, via wlrctl (wlr-virtual-pointer-unstable-v1 / virtual-keyboard-unstable-v1). -Niri implements both protocols, so no root daemon / uinput access is needed.""" +focus. Clicks are forwarded via ydotool (uinput), which requires ydotoold to +be running with --touch-on so its virtual device exposes absolute axes. +Scrolling is forwarded via wlrctl (wlr-virtual-pointer-unstable-v1), which +ydotool has no equivalent subcommand for.""" import logging import subprocess @@ -8,30 +10,30 @@ from typing import Literal logger = logging.getLogger(__name__) +_CLICK_CODES: dict[Literal["left", "right"], str] = { + "left": "0xC0", + "right": "0xC1", +} -# 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 _run_subprocess(*args: str) -> None: + logger.info(f"niri-touchscreen-gestures: running subprocess {' '.join(args)}") + subprocess.run(list(args), check=True) 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, + _run_subprocess( + "ydotool", + "mousemove", + "--absolute", + "--", + str(x), + str(y), ) - subprocess.run(["wlrctl", "pointer", "move", str(x), str(y)], check=True) - subprocess.run(["wlrctl", "pointer", "click", button], check=True) + _run_subprocess("ydotool", "click", _CLICK_CODES[button]) def send_scroll(dy: float) -> None: logger.info(f"niri-touchscreen-gestures: forwarding scroll {dy=}") - subprocess.run(["wlrctl", "pointer", "scroll", str(dy)], check=True) + _run_subprocess("wlrctl", "pointer", "scroll", str(dy)) diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/logger.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/logger.py new file mode 100644 index 0000000..4fc62e1 --- /dev/null +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/logger.py @@ -0,0 +1,9 @@ +import logging + + +def set_logging(level: int = logging.INFO) -> None: + logging.basicConfig( + level=level, + format="%(asctime)s|%(levelname)s|> %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) diff --git a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/main.py b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/main.py index 7aa251e..152e0a2 100644 --- a/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/main.py +++ b/pkgs/niri-touchscreen-gestures/niri_touchscreen_gestures/main.py @@ -1,13 +1,13 @@ import logging -from typing import Any, Callable +from collections.abc import Callable +from typing import Any -from niri_touchscreen_gestures import forwarder, nirictl +from niri_touchscreen_gestures import __version__, 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) +from niri_touchscreen_gestures.logger import set_logging logger = logging.getLogger(__name__) @@ -39,7 +39,9 @@ def make_dispatch( def dispatch( action: GestureAction, delta: float, touch_xy: tuple[int, int] | None ) -> None: - logger.info(f"niri-touchscreen-gestures: dispatching {action=} {delta=} {touch_xy=}") + 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( @@ -63,7 +65,9 @@ def get_focused_app_id() -> str | None: def main_runtime() -> None: + set_logging() logger.info("niri-touchscreen-gestures: starting") + logger.info(f"version: {__version__}") runtime = process_args(get_parser().parse_args()) output_logical = resolve_touch_output(nirictl.get_outputs(), runtime.touch_output) diff --git a/pkgs/niri-touchscreen-gestures/tests/test_forwarder.py b/pkgs/niri-touchscreen-gestures/tests/test_forwarder.py new file mode 100644 index 0000000..a622a0b --- /dev/null +++ b/pkgs/niri-touchscreen-gestures/tests/test_forwarder.py @@ -0,0 +1,52 @@ +import subprocess + +import pytest + +from niri_touchscreen_gestures import forwarder + + +class FakeRun: + def __init__(self): + self.calls = [] + + def __call__(self, args, **kwargs): + self.calls.append((args, kwargs)) + + +@pytest.fixture +def fake_run(monkeypatch): + fake = FakeRun() + monkeypatch.setattr(forwarder.subprocess, "run", fake) + return fake + + +def test_send_click_at_left_moves_then_clicks(fake_run): + forwarder.send_click_at("left", 100, 200) + assert fake_run.calls == [ + (["ydotool", "mousemove", "--absolute", "--", "100", "200"], {"check": True}), + (["ydotool", "click", "0xC0"], {"check": True}), + ] + + +def test_send_click_at_right_uses_0xc1(fake_run): + forwarder.send_click_at("right", 5, 6) + assert fake_run.calls[1] == (["ydotool", "click", "0xC1"], {"check": True}) + + +def test_send_scroll_positive_delta(fake_run): + forwarder.send_scroll(5.0) + assert fake_run.calls == [(["wlrctl", "pointer", "scroll", "5.0"], {"check": True})] + + +def test_send_scroll_negative_delta_not_absolute_valued(fake_run): + forwarder.send_scroll(-2.5) + assert fake_run.calls == [(["wlrctl", "pointer", "scroll", "-2.5"], {"check": True})] + + +def test_send_click_at_propagates_subprocess_failure(monkeypatch): + def raise_called_process_error(args, **kwargs): + raise subprocess.CalledProcessError(1, args) + + monkeypatch.setattr(forwarder.subprocess, "run", raise_called_process_error) + with pytest.raises(subprocess.CalledProcessError): + forwarder.send_click_at("left", 0, 0)