From b4b9136593888296397b7cbeec537e7917562a4b Mon Sep 17 00:00:00 2001 From: Alexander Heldt Date: Fri, 13 Nov 2026 19:02:11 +0100 Subject: [PATCH] backwards: Add a raw touchpad bridge for the `K400 Plus` The K400 Plus firmware turns two-finger swipes into whole wheel ticks, so every scroll jumps a fixed distance. A trimmed copy of k400-raw's touchpad mode switches the touchpad to raw HID++ reporting and exposes it as a native multitouch touchpad, which GNOME scrolls smoothly. --- hosts/backwards/modules/k400/default.nix | 43 ++ hosts/backwards/modules/k400/k400-touchpad.py | 648 ++++++++++++++++++ 2 files changed, 691 insertions(+) create mode 100644 hosts/backwards/modules/k400/default.nix create mode 100644 hosts/backwards/modules/k400/k400-touchpad.py diff --git a/hosts/backwards/modules/k400/default.nix b/hosts/backwards/modules/k400/default.nix new file mode 100644 index 0000000..72059cb --- /dev/null +++ b/hosts/backwards/modules/k400/default.nix @@ -0,0 +1,43 @@ +{ lib, pkgs, ... }: +let + py = pkgs.python3Packages; +in +{ + # The K400 Plus firmware turns two-finger swipes into coarse wheel ticks. + # This switches its touchpad to raw HID++ reporting and exposes it as a + # native multitouch touchpad, so GNOME scrolls it smoothly. + systemd.services.k400-touchpad = { + description = "Logitech K400 Plus raw touchpad bridge"; + wants = [ "systemd-udevd.service" ]; + after = [ "systemd-udevd.service" ]; + wantedBy = [ "multi-user.target" ]; + + environment = { + # `toPythonModule` exposes Solaar's `logitech_receiver`. Not a + # `withPackages` env, since Solaar bundles a conflicting `hid_parser`. + PYTHONPATH = py.makePythonPath [ + (py.toPythonModule pkgs.solaar) + py.evdev + py.pygobject3 + ]; + + # `logitech_receiver` imports Gdk at load time + GI_TYPELIB_PATH = lib.makeSearchPath "lib/girepository-1.0" [ + pkgs.gtk3 + pkgs.pango.out + pkgs.gdk-pixbuf + pkgs.harfbuzz + pkgs.gobject-introspection + ]; + }; + + serviceConfig = { + ExecStart = "${py.python.interpreter} ${./k400-touchpad.py}"; + Restart = "on-failure"; + RestartSec = 3; + TimeoutStopSec = 8; + }; + }; + + boot.kernelModules = [ "uinput" ]; +} diff --git a/hosts/backwards/modules/k400/k400-touchpad.py b/hosts/backwards/modules/k400/k400-touchpad.py new file mode 100644 index 0000000..74e5ba8 --- /dev/null +++ b/hosts/backwards/modules/k400/k400-touchpad.py @@ -0,0 +1,648 @@ +# Logitech K400 Plus raw touchpad bridge. +# +# Trimmed copy of the touchpad mode of k400-raw +# (https://github.com/Infinality/k400-raw, commit 04f2e58). The K400 Plus +# firmware quantizes touchpad movement into coarse mouse/wheel steps. This +# switches the touchpad to HID++ TOUCHPAD_RAW_XY (0x6100) reporting and +# exposes the raw contacts as a two-finger multitouch touchpad, so +# libinput/GNOME handle motion, tapping and scrolling. The keyboard and the +# physical buttons stay on the kernel's input device. +# +# Dropped from upstream: pointer mode, F-key configuration, CLI tunables and +# receiver/slot overrides. +# +# MIT License +# +# Copyright (c) 2026 Infinality +# +# 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 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. + +import argparse +import logging +import signal +import struct +import threading +import time +from dataclasses import dataclass + +from evdev import AbsInfo, UInput, ecodes + +# Solaar warns at import time when libnotify is missing; nothing here sends +# desktop notifications +logging.getLogger("logitech_receiver.desktop_notifications").setLevel(logging.ERROR) + +from logitech_receiver import base, listener # noqa: E402 +from logitech_receiver import receiver as receiver_mod # noqa: E402 +from logitech_receiver.hidpp20_constants import SupportedFeature # noqa: E402 + +LOG = logging.getLogger("k400-touchpad") + +WPID_K400_PLUS = "404D" +RAW_FEATURE = SupportedFeature.TOUCHPAD_RAW_XY +RAW_FLAG = 0x01 +ENHANCED_FLAG = 0x04 +RAW_ENHANCED = RAW_FLAG | ENHANCED_FLAG +ORIGIN_LOWER_LEFT = 0x01 +ORIGIN_LOWER_RIGHT = 0x02 +ORIGIN_UPPER_RIGHT = 0x04 + +TOUCHPAD_NAME = "Logitech K400 Raw Touchpad" +FEATURE_WAIT_SECONDS = 15.0 +RECONNECT_DELAY_SECONDS = 2.0 + + +class DeviceNotReady(RuntimeError): + """Expected transient state: the K400 is paired but asleep/offline.""" + + +# --- HID++ raw report parsing ------------------------------------------------ + + +@dataclass +class Touch: + finger_id: int + contact_status: int + x: int + y: int + + +@dataclass +class RawFrame: + spurious: bool + touches: tuple[Touch, Touch] + + +@dataclass +class TouchpadInfo: + x_size: int + y_size: int + max_fingers: int + origin: int + dpi: int + + +def parse_touch(data: bytes, offset: int) -> Touch: + x_high = data[offset] + y_high = data[offset + 2] + return Touch( + finger_id=data[offset + 6] >> 4, + contact_status=y_high >> 6, + x=((x_high & 0x3F) << 8) | data[offset + 1], + y=((y_high & 0x3F) << 8) | data[offset + 3], + ) + + +def parse_frame(data: bytes) -> RawFrame | None: + if len(data) < 16: + return None + return RawFrame( + spurious=bool(data[8] & 0x02), + touches=(parse_touch(data, 2), parse_touch(data, 9)), + ) + + +def parse_info(data: bytes) -> TouchpadInfo: + if not data or len(data) < 15: + raise RuntimeError(f"Short/empty TOUCHPAD_RAW_XY GetTouchpadInfo response: {data!r}") + return TouchpadInfo( + x_size=int.from_bytes(data[0:2], "big"), + y_size=int.from_bytes(data[2:4], "big"), + max_fingers=data[7], + origin=data[8], + dpi=int.from_bytes(data[13:15], "big"), + ) + + +def active_touches(frame: RawFrame) -> list[Touch]: + touches = [t for t in frame.touches if t.finger_id != 0 and t.contact_status != 0] + if touches: + return touches + + # Defensive fallback in case this firmware represents contact status + # differently while still supplying finger IDs. + return [t for t in frame.touches if t.finger_id != 0] + + +def origin_inversions(origin: int) -> tuple[bool, bool]: + # Screen-relative coordinates: +X right, +Y down. + invert_x = origin in (ORIGIN_LOWER_RIGHT, ORIGIN_UPPER_RIGHT) + invert_y = origin in (ORIGIN_LOWER_LEFT, ORIGIN_LOWER_RIGHT) + return invert_x, invert_y + + +# --- HID++ device access (via Solaar's logitech_receiver) -------------------- + + +class StartedEventsListener(listener.EventsListener): + def __init__(self, receiver, callback): + self.started_event = threading.Event() + super().__init__(receiver, callback) + + def has_started(self): + self.started_event.set() + + +@dataclass +class Candidate: + receiver: object + device: object + path: str + online: bool + has_raw_feature: bool + + +def find_k400(): + """Find the paired K400 Plus. + + Prefer one that is awake and answers TOUCHPAD_RAW_XY, then one that is + awake. A sole paired K400 is used even while asleep; wait_for_feature() + then waits for it to wake. + """ + opened = [] + candidates = [] + + for dev_info in base.receivers(): + try: + r = receiver_mod.create_receiver(base, dev_info) + if not r: + continue + opened.append(r) + + # Solaar stops iterating after the receiver's paired-device count + for dev in list(r): + if (dev.wpid or "").upper() != WPID_K400_PLUS: + continue + + try: + online = bool(dev.ping()) + except Exception: + online = False + + has_raw_feature = False + if online: + try: + has_raw_feature = bool(dev.features[RAW_FEATURE]) + except Exception as exc: + LOG.debug("K400 slot %d could not probe 0x6100: %s", dev.number, exc) + + candidates.append(Candidate(r, dev, dev_info.path, online, has_raw_feature)) + except Exception as exc: + LOG.debug("Unable to inspect receiver %s: %s", dev_info.path, exc) + + preferred = ( + [c for c in candidates if c.online and c.has_raw_feature] + or [c for c in candidates if c.online] + or candidates + ) + selected = preferred[0] if len(preferred) == 1 else None + + for r in opened: + if selected is None or r is not selected.receiver: + try: + r.close() + except Exception: + pass + + if selected is None: + if not preferred: + raise RuntimeError("Could not find a paired Logitech K400 Plus") + if not any(c.online for c in preferred): + raise DeviceNotReady("Multiple paired K400 Plus records, none responding; waiting for one to wake") + locations = ", ".join(f"{c.path} slot {c.device.number}" for c in preferred) + raise RuntimeError(f"Found multiple responding K400 Plus devices: {locations}") + + LOG.info( + "Selected K400 Plus on receiver %s slot %d (online=%s)", + selected.path, selected.device.number, selected.online, + ) + return selected.receiver, selected.device + + +def wait_for_feature(dev, timeout_seconds: float, interval_seconds: float = 0.25) -> int: + """Wake the device and wait for TOUCHPAD_RAW_XY to become queryable. + + Solaar's FeaturesArray refuses feature discovery while dev.online is false, + and a K400 may be paired but asleep. Retry ping/feature discovery, falling + back to a direct ROOT.GetFeature query. If a transient lookup cached False, + the false entry is removed before installing the known-good feature index. + """ + deadline = time.monotonic() + timeout_seconds + last_error = None + + while time.monotonic() < deadline: + try: + dev.ping() + except Exception as exc: + last_error = exc + + if dev.online: + try: + index = dev.features[RAW_FEATURE] + if index: + return index + except Exception as exc: + last_error = exc + + try: + response = dev.request(0x0000, struct.pack("!H", int(RAW_FEATURE))) + if response and response[0]: + index = response[0] + + # FeaturesArray forbids deletion through its public API, so + # use the underlying dict operation only for this recovery + if dict.get(dev.features, RAW_FEATURE) is False: + dict.__delitem__(dev.features, RAW_FEATURE) + + dev.features[RAW_FEATURE] = index + if len(response) > 1: + dev.features.flags[RAW_FEATURE] = response[1] + if len(response) > 2: + dev.features.version[RAW_FEATURE] = response[2] + return index + except Exception as exc: + last_error = exc + + time.sleep(interval_seconds) + + message = ( + f"Timed out waiting for HID++ feature 0x{int(RAW_FEATURE):04X} " + f"(online={dev.online}; last error: {last_error!r})" + ) + if not dev.online: + raise DeviceNotReady(message) + raise RuntimeError(message) + + +def enable_raw_reports(dev) -> None: + dev.feature_request(RAW_FEATURE, 0x20, bytes([RAW_ENHANCED])) + reply = dev.feature_request(RAW_FEATURE, 0x10) + if not reply or (reply[0] & RAW_FLAG) == 0: + raise RuntimeError(f"Failed to enable HID++ raw reporting; readback was {reply!r}") + if reply[0] != RAW_ENHANCED: + LOG.warning( + "Device did not preserve every requested state bit: requested=0x%02X actual=0x%02X", + RAW_ENHANCED, reply[0], + ) + + +# --- Virtual touchpad -------------------------------------------------------- + + +def make_absinfo(maximum: int, resolution: int = 0) -> AbsInfo: + return AbsInfo(value=0, min=0, max=maximum, fuzz=0, flat=0, resolution=resolution) + + +class VirtualTouchpad: + """Translate K400 raw contacts into a two-slot Linux Type-B MT touchpad. + + The uinput device is created on first connect and kept across HID++ + reconnects, so the desktop keeps its settings for it. + """ + + def __init__(self): + self.ui = None + self.geometry = None + self.invert_x = False + self.invert_y = False + # The HID++ listener thread and the reconnect loop both write events + self.lock = threading.Lock() + + self.finger_to_slot: dict[int, int] = {} + self.slot_to_finger: dict[int, int] = {} + self.slot_xy: dict[int, tuple[int, int]] = {} + self.next_tracking_id = 1 + + self.last_btn_touch = 0 + self.last_tool_finger = 0 + self.last_tool_doubletap = 0 + + def configure(self, info: TouchpadInfo): + self.invert_x, self.invert_y = origin_inversions(info.origin) + resolution = max(1, round(info.dpi / 25.4)) + geometry = (info.x_size, info.y_size, resolution) + + if self.ui is not None: + if geometry != self.geometry: + LOG.warning( + "K400 geometry changed after reconnect: was %s now %s; keeping the original", + self.geometry, geometry, + ) + return + + self.geometry = geometry + x_max, y_max, _ = geometry + self.ui = UInput( + { + ecodes.EV_KEY: [ecodes.BTN_TOUCH, ecodes.BTN_TOOL_FINGER, ecodes.BTN_TOOL_DOUBLETAP], + ecodes.EV_ABS: [ + (ecodes.ABS_X, make_absinfo(x_max, resolution)), + (ecodes.ABS_Y, make_absinfo(y_max, resolution)), + (ecodes.ABS_MT_SLOT, make_absinfo(1)), + (ecodes.ABS_MT_TRACKING_ID, make_absinfo(65535)), + (ecodes.ABS_MT_POSITION_X, make_absinfo(x_max, resolution)), + (ecodes.ABS_MT_POSITION_Y, make_absinfo(y_max, resolution)), + ], + }, + name=TOUCHPAD_NAME, + # Logitech's vendor ID with a deliberately synthetic product ID + vendor=0x046D, + product=0xF400, + version=1, + bustype=ecodes.BUS_USB, + phys="k400-touchpad/input0", + # Indirect pointing device, not a touchscreen + input_props=[ecodes.INPUT_PROP_POINTER], + ) + LOG.info( + "Created virtual touchpad %s, %dx%d, %d units/mm (~%.1fx%.1f mm)", + self.ui.device.path if self.ui.device else self.ui.devnode, + x_max, y_max, resolution, x_max / resolution, y_max / resolution, + ) + # Give udev/libinput time to pick up the device before the first events + time.sleep(0.5) + + def _xy(self, touch: Touch) -> tuple[int, int]: + x_max, y_max, _ = self.geometry + x = x_max - touch.x if self.invert_x else touch.x + y = y_max - touch.y if self.invert_y else touch.y + return max(0, min(x_max, x)), max(0, min(y_max, y)) + + def _new_tracking_id(self) -> int: + tid = self.next_tracking_id + self.next_tracking_id = tid + 1 if tid < 65535 else 1 + return tid + + def release_all(self): + with self.lock: + if self.ui is None: + return + changed = False + + for slot in sorted(self.slot_to_finger): + self.ui.write(ecodes.EV_ABS, ecodes.ABS_MT_SLOT, slot) + self.ui.write(ecodes.EV_ABS, ecodes.ABS_MT_TRACKING_ID, -1) + changed = True + + self.finger_to_slot.clear() + self.slot_to_finger.clear() + self.slot_xy.clear() + + for code, attr in ( + (ecodes.BTN_TOUCH, "last_btn_touch"), + (ecodes.BTN_TOOL_FINGER, "last_tool_finger"), + (ecodes.BTN_TOOL_DOUBLETAP, "last_tool_doubletap"), + ): + if getattr(self, attr): + self.ui.write(ecodes.EV_KEY, code, 0) + setattr(self, attr, 0) + changed = True + + if changed: + self.ui.syn() + + def process(self, frame: RawFrame): + if frame.spurious: + return + + # The K400 reports at most two contacts. If malformed data ever + # contains duplicate IDs, keep only the first occurrence. + current = {} + for touch in active_touches(frame): + current.setdefault(touch.finger_id, touch) + + with self.lock: + if self.ui is None: + return + old_ids = set(self.finger_to_slot) + new_ids = set(current) + + # Release vanished contacts first so a slot can be reused this frame + for finger_id in sorted(old_ids - new_ids): + slot = self.finger_to_slot.pop(finger_id) + self.slot_to_finger.pop(slot, None) + self.slot_xy.pop(slot, None) + self.ui.write(ecodes.EV_ABS, ecodes.ABS_MT_SLOT, slot) + self.ui.write(ecodes.EV_ABS, ecodes.ABS_MT_TRACKING_ID, -1) + + for finger_id in sorted(new_ids - old_ids): + free = next((s for s in (0, 1) if s not in self.slot_to_finger), None) + if free is None: + LOG.warning("More contacts than MT slots; ignoring finger id %d", finger_id) + continue + self.finger_to_slot[finger_id] = free + self.slot_to_finger[free] = finger_id + self.ui.write(ecodes.EV_ABS, ecodes.ABS_MT_SLOT, free) + self.ui.write(ecodes.EV_ABS, ecodes.ABS_MT_TRACKING_ID, self._new_tracking_id()) + + # Emit every tracked contact each frame so libinput sees the raw + # sensor report cadence + for finger_id, slot in sorted(self.finger_to_slot.items(), key=lambda p: p[1]): + touch = current.get(finger_id) + if touch is None: + continue + x, y = self._xy(touch) + self.ui.write(ecodes.EV_ABS, ecodes.ABS_MT_SLOT, slot) + self.ui.write(ecodes.EV_ABS, ecodes.ABS_MT_POSITION_X, x) + self.ui.write(ecodes.EV_ABS, ecodes.ABS_MT_POSITION_Y, y) + self.slot_xy[slot] = (x, y) + + count = len(self.slot_to_finger) + + # Touchpads also need the legacy single-touch axes; mirror the + # lowest-numbered active slot + if count: + xy = self.slot_xy.get(min(self.slot_to_finger)) + if xy is not None: + self.ui.write(ecodes.EV_ABS, ecodes.ABS_X, xy[0]) + self.ui.write(ecodes.EV_ABS, ecodes.ABS_Y, xy[1]) + + for code, attr, value in ( + (ecodes.BTN_TOUCH, "last_btn_touch", int(count > 0)), + (ecodes.BTN_TOOL_FINGER, "last_tool_finger", int(count == 1)), + (ecodes.BTN_TOOL_DOUBLETAP, "last_tool_doubletap", int(count >= 2)), + ): + if value != getattr(self, attr): + self.ui.write(ecodes.EV_KEY, code, value) + setattr(self, attr, value) + + self.ui.syn() + + def close(self): + self.release_all() + if self.ui is not None: + self.ui.close() + self.ui = None + + +# --- Session / reconnect loop ------------------------------------------------ + + +def run(touchpad: VirtualTouchpad, stop: threading.Event): + session = 0 + + while not stop.is_set(): + session += 1 + r = dev = events = None + feature_index = None + old_raw_state = None + raw_enabled = False + reconfigure = threading.Event() + reconfigure_failures = 0 + + try: + r, dev = find_k400() + feature_index = wait_for_feature(dev, FEATURE_WAIT_SECONDS) + + info = parse_info(dev.feature_request(RAW_FEATURE, 0x00)) + LOG.info( + "K400 raw surface: %dx%d, dpi=%d, origin=%d, max_fingers=%d", + info.x_size, info.y_size, info.dpi, info.origin, info.max_fingers, + ) + touchpad.configure(info) + + def callback(n): + if n.devnumber != dev.number: + return + + # Receiver connection notification; the K400 forgets raw mode + # while asleep, so re-enable it on every link-up + if n.sub_id == 0x41: + flags = (n.data[0] & 0xF0) if n.data else 0x40 + dev.online = not (flags & 0x40) + touchpad.release_all() + if dev.online: + LOG.debug("K400 link established; re-enabling raw mode") + reconfigure.set() + else: + LOG.debug("K400 asleep/offline") + return + + if n.sub_id != feature_index or (n.address >> 4) != 0x00: + return + frame = parse_frame(n.data) + if frame is None: + LOG.warning("Short raw XY notification: %r", n.data) + return + touchpad.process(frame) + + events = StartedEventsListener(r, callback) + events.start() + if not events.started_event.wait(timeout=3.0): + raise RuntimeError("Timed out starting HID++ receiver listener") + + state_reply = dev.feature_request(RAW_FEATURE, 0x10) + old_raw_state = state_reply[0] if state_reply else 0x00 + enable_raw_reports(dev) + raw_enabled = True + LOG.info("K400 raw touchpad active (receiver slot %d)", dev.number) + + while not stop.is_set(): + if not events.is_alive(): + raise ConnectionError("HID++ receiver listener stopped") + if not reconfigure.wait(timeout=1.0): + continue + reconfigure.clear() + if stop.is_set(): + break + + touchpad.release_all() + try: + feature_index = wait_for_feature(dev, min(FEATURE_WAIT_SECONDS, 4.0)) + enable_raw_reports(dev) + reconfigure_failures = 0 + LOG.info("K400 raw mode re-enabled after wake") + except DeviceNotReady as exc: + reconfigure_failures = 0 + LOG.debug("K400 went offline during re-enable (%s); waiting for next link-up", exc) + except Exception as exc: + reconfigure_failures += 1 + if not events.is_alive() or reconfigure_failures >= 3: + raise ConnectionError("Repeated raw-mode re-enable failure") from exc + LOG.debug("Transient re-enable failure %d/3: %s", reconfigure_failures, exc) + if stop.wait(RECONNECT_DELAY_SECONDS): + break + reconfigure.set() + + except DeviceNotReady as exc: + LOG.debug("K400 not ready (%s); retrying", exc) + except Exception as exc: + if stop.is_set(): + break + LOG.warning( + "K400 HID++ session #%d lost (%s). Retrying in %.1f s.", + session, exc, RECONNECT_DELAY_SECONDS, + exc_info=LOG.isEnabledFor(logging.DEBUG), + ) + finally: + try: + touchpad.release_all() + except Exception: + LOG.debug("Error releasing touches", exc_info=True) + + if stop.is_set() and dev is not None and raw_enabled: + try: + restore = 0x00 if old_raw_state is None else old_raw_state + dev.feature_request(RAW_FEATURE, 0x20, bytes([restore])) + LOG.info("Restored HID++ raw-report state to 0x%02X", restore) + except Exception: + LOG.warning("Could not restore raw-report state during shutdown") + + if events is not None: + try: + events.stop() + events.join(timeout=2.0) + except Exception: + LOG.debug("Error stopping receiver listener", exc_info=True) + if r is not None: + try: + r.close() + except Exception: + LOG.debug("Error closing receiver", exc_info=True) + + if not stop.is_set(): + stop.wait(RECONNECT_DELAY_SECONDS) + + +def main(): + parser = argparse.ArgumentParser(description="Logitech K400 Plus raw touchpad bridge") + parser.add_argument("-v", "--verbose", action="count", default=0, help="-v for info, -vv for debug") + args = parser.parse_args() + + # Keep Solaar's own logging at WARNING so journald isn't flooded with + # HID++ frames + logging.basicConfig(level=logging.WARNING, format="%(levelname)-8s %(name)s: %(message)s") + LOG.setLevel([logging.WARNING, logging.INFO, logging.DEBUG][min(args.verbose, 2)]) + + touchpad = VirtualTouchpad() + stop = threading.Event() + + def on_signal(signum, _frame): + LOG.info("Received signal %s; stopping", signum) + stop.set() + + signal.signal(signal.SIGINT, on_signal) + signal.signal(signal.SIGTERM, on_signal) + try: + run(touchpad, stop) + finally: + touchpad.close() + + +if __name__ == "__main__": + main()