#!/usr/bin/python3
# SPDX-License-Identifier: GPL-2.0-or-later
"""Pocket DS — user-session listener that toggles the Onboard on-screen
keyboard when the joymouse ("keyboard mode") profile fires `dbus: ui_osk`.

InputPlumber emits, on the *system* bus:
    org.shadowblip.Input.DBusDevice.InputEvent  (string action, double value)
Receiving these signals is permitted for normal users (the InputPlumber
policy leaves signal reception allowed). We run in the user session so we
can reach Onboard's *session*-bus service to toggle it.
"""
import subprocess
import time

import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib

DBusGMainLoop(set_as_default=True)

TOGGLE = "/usr/bin/pocketds-osk-toggle"
LAST_FIRE = 0.0


def on_input_event(action, value):
    global LAST_FIRE
    if value < 0.5:                 # act on press only
        return
    if action != "ui_osk":
        return
    now = time.monotonic()
    if now - LAST_FIRE < 0.25:      # debounce
        return
    LAST_FIRE = now
    subprocess.Popen([TOGGLE],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


bus = dbus.SystemBus()
bus.add_signal_receiver(
    on_input_event,
    signal_name="InputEvent",
    dbus_interface="org.shadowblip.Input.DBusDevice",
    bus_name="org.shadowblip.InputPlumber",
)
GLib.MainLoop().run()
