#!/usr/bin/env python3
"""macOS-style momentum scrolling for the Apple Magic Mouse.

The kernel driver (hid_magicmouse) turns a finger sliding on the mouse into
scroll-wheel events. Apps treat wheel events as discrete notches, so nothing
glides after the finger lifts. This service grabs the mouse and:

  * passes pointer motion and clicks through a virtual mouse ("Magic Mouse Glide"),
  * drops the driver's emulated wheel events,
  * replays a sliding finger as a two-finger swipe on a virtual touchpad
    ("Magic Mouse Glide Surface"), lifting both fingers when the real one lifts.

libinput then reports touchpad scrolling with a proper scroll stop, and apps
(Chromium, GTK, Firefox, ...) add their own kinetic glide, as they do for the
built-in trackpad. Direction follows Hyprland's touchpad natural_scroll.

systemd user service: magicmouse-glide.service
"""

import os
import select
import sys
import time

import evdev
from evdev import UInput, AbsInfo, ecodes as e

# Tunables -------------------------------------------------------------------
GAIN = float(os.environ.get("GLIDE_GAIN", "1.0"))  # finger mm -> virtual pad mm
START_MM = 1.2       # finger must travel this far before it counts as a scroll
FINGER_GAP_MM = 12   # distance between the two virtual fingers
PAD_MM = 400         # virtual pad size; big so a long swipe never hits an edge
PAD_RES = 20         # units per mm on the virtual pad
# -----------------------------------------------------------------------------

PAD_MAX = PAD_MM * PAD_RES
CENTER = PAD_MAX // 2


def log(*a):
    print(*a, file=sys.stderr, flush=True)


def find_mouse():
    for path in evdev.list_devices():
        try:
            d = evdev.InputDevice(path)
        except OSError:
            continue
        caps = d.capabilities()
        abs_codes = {c for c, _ in caps.get(e.EV_ABS, [])}
        if ("magic mouse" in d.name.lower() and "glide" not in d.name.lower()
                and e.ABS_MT_POSITION_X in abs_codes and e.EV_REL in caps):
            return d
        d.close()
    return None


def make_virtual_mouse():
    return UInput(
        {
            e.EV_KEY: [e.BTN_LEFT, e.BTN_RIGHT, e.BTN_MIDDLE],
            e.EV_REL: [e.REL_X, e.REL_Y],
        },
        name="Magic Mouse Glide",
        bustype=e.BUS_BLUETOOTH,
        vendor=0x1d6b, product=0x0a01,
    )


def make_virtual_pad():
    ax = lambda mx: AbsInfo(value=0, min=0, max=mx, fuzz=0, flat=0, resolution=PAD_RES)
    return UInput(
        {
            e.EV_KEY: [e.BTN_LEFT, e.BTN_TOUCH, e.BTN_TOOL_FINGER, e.BTN_TOOL_DOUBLETAP],
            e.EV_ABS: [
                (e.ABS_X, ax(PAD_MAX)),
                (e.ABS_Y, ax(PAD_MAX)),
                (e.ABS_MT_SLOT, AbsInfo(0, 0, 1, 0, 0, 0)),
                (e.ABS_MT_TRACKING_ID, AbsInfo(0, 0, 65535, 0, 0, 0)),
                (e.ABS_MT_POSITION_X, ax(PAD_MAX)),
                (e.ABS_MT_POSITION_Y, ax(PAD_MAX)),
            ],
        },
        name="Magic Mouse Glide Surface",
        bustype=e.BUS_BLUETOOTH,
        vendor=0x1d6b, product=0x0a02,
        input_props=[e.INPUT_PROP_POINTER],
    )


class Pad:
    """Two virtual fingers that move together."""

    def __init__(self, ui):
        self.ui = ui
        self.down = False
        self.x = self.y = 0.0
        self.tid = 0

    def _fingers(self):
        x, y = int(self.x), int(self.y)
        w = self.ui.write
        for slot, dx in ((0, 0), (1, FINGER_GAP_MM * PAD_RES)):
            w(e.EV_ABS, e.ABS_MT_SLOT, slot)
            w(e.EV_ABS, e.ABS_MT_POSITION_X, x + dx)
            w(e.EV_ABS, e.ABS_MT_POSITION_Y, y)
        w(e.EV_ABS, e.ABS_X, x)
        w(e.EV_ABS, e.ABS_Y, y)

    def press(self):
        self.x = self.y = float(CENTER)
        w = self.ui.write
        for slot in (0, 1):
            self.tid = (self.tid + 1) % 65535
            w(e.EV_ABS, e.ABS_MT_SLOT, slot)
            w(e.EV_ABS, e.ABS_MT_TRACKING_ID, self.tid)
        self._fingers()
        w(e.EV_KEY, e.BTN_TOUCH, 1)
        w(e.EV_KEY, e.BTN_TOOL_DOUBLETAP, 1)
        self.ui.syn()
        self.down = True

    def move(self, dx_mm, dy_mm):
        self.x = min(max(self.x + dx_mm * GAIN * PAD_RES, 0), PAD_MAX - FINGER_GAP_MM * PAD_RES)
        self.y = min(max(self.y + dy_mm * GAIN * PAD_RES, 0), PAD_MAX)
        self._fingers()
        self.ui.syn()

    def release(self):
        if not self.down:
            return
        w = self.ui.write
        for slot in (0, 1):
            w(e.EV_ABS, e.ABS_MT_SLOT, slot)
            w(e.EV_ABS, e.ABS_MT_TRACKING_ID, -1)
        w(e.EV_KEY, e.BTN_TOUCH, 0)
        w(e.EV_KEY, e.BTN_TOOL_DOUBLETAP, 0)
        self.ui.syn()
        self.down = False


def run(dev, vmouse, pad):
    absinfo = dict(dev.capabilities()[e.EV_ABS])
    res_x = absinfo[e.ABS_MT_POSITION_X].resolution or 26
    res_y = absinfo[e.ABS_MT_POSITION_Y].resolution or 70

    slots = {}          # slot -> {"x","y","sx","sy"} (start pos), current tracking
    slotpos = {}        # slot -> [x, y]; the kernel skips repeated values, so remember them
    slot = 0
    dirty = set()       # slots touched in this frame
    lifted = set()
    scroller = None     # slot that drives the virtual fingers
    last = None         # scroller's last (x, y)

    dev.grab()
    log(f"grabbed {dev.name} ({dev.path})")
    try:
        for ev in dev.read_loop():
            if ev.type == e.EV_ABS:
                if ev.code == e.ABS_MT_SLOT:
                    slot = ev.value
                elif ev.code == e.ABS_MT_TRACKING_ID:
                    if ev.value < 0:
                        lifted.add(slot)
                    else:
                        px, py = slotpos.get(slot, (None, None))
                        slots[slot] = {"x": px, "y": py, "sx": px, "sy": py}
                        lifted.discard(slot)
                elif ev.code in (e.ABS_MT_POSITION_X, e.ABS_MT_POSITION_Y):
                    t = slots.setdefault(slot, {"x": None, "y": None, "sx": None, "sy": None})
                    k = "x" if ev.code == e.ABS_MT_POSITION_X else "y"
                    t[k] = ev.value
                    slotpos.setdefault(slot, [None, None])[0 if k == "x" else 1] = ev.value
                    if t["s" + k] is None:
                        t["s" + k] = ev.value
                    dirty.add(slot)
            elif ev.type == e.EV_REL:
                if ev.code in (e.REL_X, e.REL_Y):
                    vmouse.write(e.EV_REL, ev.code, ev.value)
                # wheel / hi-res wheel: dropped, the virtual pad scrolls instead
            elif ev.type == e.EV_KEY:
                vmouse.write(e.EV_KEY, ev.code, ev.value)
            elif ev.type == e.EV_SYN and ev.code == e.SYN_REPORT:
                vmouse.syn()

                # Lifts first.
                for s in lifted:
                    slots.pop(s, None)
                    if s == scroller:
                        pad.release()
                        scroller, last = None, None
                lifted.clear()

                # Pick a scroller: the first touch that slid far enough.
                if scroller is None:
                    for s in dirty:
                        t = slots.get(s)
                        if not t or None in (t["x"], t["y"], t["sx"], t["sy"]):
                            continue
                        mx = (t["x"] - t["sx"]) / res_x
                        my = (t["y"] - t["sy"]) / res_y
                        if (mx * mx + my * my) ** 0.5 >= START_MM:
                            scroller, last = s, (t["x"], t["y"])
                            pad.press()
                            break
                elif scroller in dirty:
                    t = slots[scroller]
                    dx = (t["x"] - last[0]) / res_x
                    dy = (t["y"] - last[1]) / res_y
                    last = (t["x"], t["y"])
                    if dx or dy:
                        pad.move(dx, dy)
                dirty.clear()
    finally:
        pad.release()
        try:
            dev.ungrab()
        except OSError:
            pass


def main():
    vmouse = make_virtual_mouse()
    pad = Pad(make_virtual_pad())
    log("virtual devices ready")
    while True:
        dev = find_mouse()
        if dev is None:
            time.sleep(2)
            continue
        try:
            run(dev, vmouse, pad)
        except OSError as exc:
            log(f"mouse gone ({exc}); waiting for it to come back")
        finally:
            try:
                dev.close()
            except OSError:
                pass
        time.sleep(1)


if __name__ == "__main__":
    main()
