#!/usr/bin/python3
"""Volume Up + Power chord = screenshot. All other key events pass through unchanged via a uinput device."""
import asyncio, subprocess, time
from evdev import InputDevice, UInput, ecodes as e, list_devices

WINDOW = 0.30           # seconds to wait for the second key of the chord
COOLDOWN = 1.5
NAMES = {'mt6779-keypad', 'mtk-pmic-keys'}
VU, PW = e.KEY_VOLUMEUP, e.KEY_POWER

devs = []
for p in list_devices():
    d = InputDevice(p)
    if d.name in NAMES:
        devs.append(d)
if not devs:
    raise SystemExit('no matching input devices')
ui = UInput.from_device(*devs, name='begonia-keys')
for d in devs:
    d.grab()

state = {VU: None, PW: None}      # None | 'pending' | 'forwarded' | 'consumed'
timers = {}
last_shot = 0.0

def fwd(code, value):
    ui.write(e.EV_KEY, code, value); ui.syn()

async def screenshot():
    global last_shot
    if time.monotonic() - last_shot < COOLDOWN:
        return
    last_shot = time.monotonic()
    await asyncio.create_subprocess_exec(
        'runuser', '-u', 'user', '--', 'env', 'HOME=/home/user', 'XDG_RUNTIME_DIR=/run/user/1000',
        'DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus', '/usr/local/bin/begonia-screenshot')

async def delayed_forward(code):
    try:
        await asyncio.sleep(WINDOW)
    except asyncio.CancelledError:
        return
    if state[code] == 'pending':
        state[code] = 'forwarded'
        fwd(code, 1)

def handle_chord_key(code, value):
    other = PW if code == VU else VU
    if value == 1:
        if state[other] in ('pending', 'forwarded'):
            t = timers.pop(other, None)
            if t: t.cancel()
            state[other] = 'consumed'; state[code] = 'consumed'
            asyncio.ensure_future(screenshot())
        else:
            state[code] = 'pending'
            timers[code] = asyncio.ensure_future(delayed_forward(code))
    elif value == 0:
        st = state[code]
        if st == 'pending':
            t = timers.pop(code, None)
            if t: t.cancel()
            fwd(code, 1); fwd(code, 0)
        elif st == 'forwarded':
            fwd(code, 0)
        state[code] = None
    else:  # autorepeat
        if state[code] == 'forwarded':
            fwd(code, 2)

async def pump(dev):
    async for ev in dev.async_read_loop():
        if ev.type == e.EV_KEY and ev.code in (VU, PW):
            handle_chord_key(ev.code, ev.value)
        elif ev.type == e.EV_SYN:
            continue
        else:
            ui.write(ev.type, ev.code, ev.value); ui.syn()

async def main():
    await asyncio.gather(*(pump(d) for d in devs))

asyncio.run(main())
