#!/usr/bin/env python3
"""Lock the touchpad as soon as you type; unlock it only with a physical click.

libinput's disable-while-typing only blocks the touchpad for ~0.5 s after a key,
so resting palms still move the pointer. This keeps it off until the touchpad's
button is physically pressed (BTN_LEFT from the hardware) or Esc is pressed.
Taps and touches never unlock it.

Keyboard events are read from every keyboard, including Toshy's virtual one
(Toshy grabs the physical keyboard, so its events only appear there). Lone
modifier keys don't lock, so Cmd+click still works.

Needs python-evdev (Toshy's venv has it, see the .service file). Runs as the systemd user service
typing-touchpad-lock.service.
"""

import os
import selectors
import subprocess
import sys
import time

import evdev
from evdev import ecodes as e

RESCAN_SECONDS = 5
# Omarchy's own touchpad toggle (XF86TouchpadToggle) persists its disable here;
# while it exists the user turned the touchpad off on purpose, so never unlock.
OMARCHY_DISABLED = os.path.expanduser("~/.local/state/omarchy/toggles/hypr/touchpad-disabled-name")

# Lock only after this many typed characters in a row, each within
# STREAK_GAP seconds of the previous one. Chords (Cmd+V, Ctrl+Opt+arrow, ...)
# never count and reset the streak.
STREAK_KEYS = 3
STREAK_GAP = 1.5

# Modifiers that turn a key into a shortcut. Shift doesn't: it's still typing.
CHORD_MODIFIERS = {
    e.KEY_LEFTCTRL, e.KEY_RIGHTCTRL, e.KEY_LEFTALT, e.KEY_RIGHTALT,
    e.KEY_LEFTMETA, e.KEY_RIGHTMETA,
}

# Keys that produce text: digits/punctuation rows, letters, space, the ISO key
# left of Y on the Swiss layout, and the keypad digits.
TYPING_KEYS = (
    set(range(e.KEY_1, e.KEY_EQUAL + 1))
    | set(range(e.KEY_Q, e.KEY_RIGHTBRACE + 1))
    | set(range(e.KEY_A, e.KEY_GRAVE + 1))
    | set(range(e.KEY_BACKSLASH, e.KEY_SLASH + 1))
    | {e.KEY_SPACE, e.KEY_102ND}
    | {e.KEY_KP0, e.KEY_KP1, e.KEY_KP2, e.KEY_KP3, e.KEY_KP4,
       e.KEY_KP5, e.KEY_KP6, e.KEY_KP7, e.KEY_KP8, e.KEY_KP9}
)

MODIFIERS = {
    e.KEY_LEFTCTRL, e.KEY_RIGHTCTRL, e.KEY_LEFTSHIFT, e.KEY_RIGHTSHIFT,
    e.KEY_LEFTALT, e.KEY_RIGHTALT, e.KEY_LEFTMETA, e.KEY_RIGHTMETA,
    e.KEY_CAPSLOCK, e.KEY_FN, e.KEY_COMPOSE,
}


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


def hypr_touchpad_name():
    try:
        out = subprocess.run(["omarchy-hw-touchpad"], capture_output=True, text=True, timeout=5)
        return out.stdout.strip() or None
    except Exception as exc:
        log("omarchy-hw-touchpad failed:", exc)
        return None


def set_enabled(name, enabled):
    quoted = name.replace("\\", "\\\\").replace('"', '\\"')
    lua = f'hl.device({{ name = "{quoted}", enabled = {"true" if enabled else "false"} }})'
    subprocess.run(["hyprctl", "eval", lua], capture_output=True, timeout=5)


def classify(dev):
    caps = dev.capabilities()
    keys = set(caps.get(e.EV_KEY, []))
    abs_codes = {code for code, _ in caps.get(e.EV_ABS, [])}
    if e.ABS_MT_POSITION_X in abs_codes and e.BTN_LEFT in keys:
        return "touchpad"
    if e.KEY_A in keys and e.KEY_SPACE in keys:
        return "keyboard"
    return None


class Lock:
    def __init__(self):
        self.sel = selectors.DefaultSelector()
        self.devices = {}  # path -> InputDevice
        self.locked = False
        self.name = None
        self.asserted = 0.0
        self.held = set()        # chord modifiers currently held (all keyboards)
        self.streak = 0
        self.last_typed = 0.0

    def rescan(self):
        for path in evdev.list_devices():
            if path in self.devices:
                continue
            try:
                dev = evdev.InputDevice(path)
                kind = classify(dev)
            except OSError:
                continue
            if kind is None:
                dev.close()
                continue
            self.devices[path] = dev
            self.sel.register(dev, selectors.EVENT_READ, kind)
            log(f"watching {kind}: {dev.name} ({path})")

    def drop(self, dev):
        try:
            self.sel.unregister(dev)
        except Exception:
            pass
        self.devices.pop(dev.path, None)
        try:
            dev.close()
        except Exception:
            pass

    def lock(self):
        # Re-assert at most every 2 s while typing: a Hyprland config reload
        # re-enables the device behind our back.
        now = time.monotonic()
        if self.locked and now - self.asserted < 2:
            return
        self.asserted = now
        self.name = self.name or hypr_touchpad_name()
        if not self.name:
            return
        set_enabled(self.name, False)
        self.locked = True

    def unlock(self):
        if not self.locked:
            return
        self.locked = False
        if os.path.exists(OMARCHY_DISABLED):
            return
        self.name = hypr_touchpad_name() or self.name
        if self.name:
            set_enabled(self.name, True)

    def on_key(self, code, value):
        if code in CHORD_MODIFIERS:
            if value == 1:
                self.held.add(code)
            elif value == 0:
                self.held.discard(code)
            return
        if value != 1:
            return
        if code == e.KEY_ESC:
            self.streak = 0
            self.unlock()
            return
        if self.held or code not in TYPING_KEYS:
            # A shortcut, or a navigation/editing key: not typing.
            if self.held:
                self.streak = 0
            return
        now = time.monotonic()
        self.streak = self.streak + 1 if now - self.last_typed <= STREAK_GAP else 1
        self.last_typed = now
        if self.streak >= STREAK_KEYS:
            self.lock()

    def run(self):
        self.rescan()
        last_scan = time.monotonic()
        while True:
            for key, _ in self.sel.select(timeout=RESCAN_SECONDS):
                dev, kind = key.fileobj, key.data
                try:
                    events = list(dev.read())
                except (OSError, BlockingIOError) as exc:
                    if isinstance(exc, BlockingIOError):
                        continue
                    log(f"lost {dev.path}")
                    self.drop(dev)
                    continue
                for ev in events:
                    if ev.type != e.EV_KEY:
                        continue
                    if kind == "keyboard":
                        self.on_key(ev.code, ev.value)
                    elif ev.code == e.BTN_LEFT and ev.value == 1:
                        self.unlock()
            if time.monotonic() - last_scan >= RESCAN_SECONDS:
                self.rescan()
                last_scan = time.monotonic()


if __name__ == "__main__":
    lock = Lock()
    # Start unlocked, even if a previous run died while locked.
    lock.locked = True
    lock.unlock()
    try:
        lock.run()
    finally:
        # Never leave the touchpad disabled when the service stops.
        lock.unlock()
