#!/usr/bin/env python3
"Read gestures from libinput touchpad and action shell commands."

from __future__ import annotations

# Mark Blakeney, Sep 2015.
import argparse
import fcntl
import getpass
import hashlib
import math
import os
import platform
import re
import shlex
import subprocess
import sys
import threading
from abc import ABC
from io import TextIOWrapper
from pathlib import Path
from time import monotonic
from typing import Callable, Iterator, Sequence

VERSION = '2.80'

dbus_imported = True
try:
    import dbus  # type: ignore
    from dbus.mainloop.glib import DBusGMainLoop  # type: ignore
    from gi.repository import GLib  # type: ignore
except ImportError:
    dbus_imported = False

session_locked = False

PROGPATH = Path(sys.argv[0])
PROGNAME = PROGPATH.stem
HOME = Path('~').expanduser()

# Conf file containing gesture commands.
# Search first for user file then system file.
CONFNAME = f'{PROGNAME}.conf'
USERDIR = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
CONFDIRS = (USERDIR, '/etc')

# Ratio of X/Y (or Y/X) at which we consider an oblique swipe gesture.
# The number is the trigger angle in degrees and set to 360/8/2.
OBLIQUE_RATIO = math.tan(math.radians(22.5))

# Default minimum significant distance to move for swipes, in dots.
# Can be changed using configuration command.
swipe_min_threshold = 0

args: argparse.Namespace
abzsquare: float

# Timeout on gesture action from start to end. 0 = no timeout. In secs.
# Can be changed using configuration command.
DEFAULT_TIMEOUT = 1.5
timeoutv = DEFAULT_TIMEOUT

# Rotation threshold in degrees to discriminate pinch rotate from in/out
ROTATE_ANGLE = 15.0


def open_lock(user: str) -> tuple[TextIOWrapper | None, TextIOWrapper | None]:
    "Create and return lock and pid files for given user"
    # We use exclusive assess to a file for this
    flock = Path(f'/tmp/{PROGNAME}-{user}.lock')
    flock_fp = flock.open('w')
    try:
        fcntl.lockf(flock_fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        return None, None

    # Return lock file and pid file handles
    return flock_fp, flock.with_suffix('.pid').open('w')


def runcmd(cmd: Sequence[str], *, check: bool = True, block: bool = True) -> str:
    "Run function and return standard output, Popen() handle, or None"
    try:
        if block:
            result = subprocess.check_output(
                cmd,
                universal_newlines=True,
                stderr=(None if check else subprocess.DEVNULL),
            )
        else:
            result = 'ok' if subprocess.Popen(cmd) else ''
    except Exception as e:
        result = ''
        if check:
            print(str(e), file=sys.stderr)

    return result


def get_libinput_vers() -> tuple[str | None, bool]:
    "Return the libinput installed version number string"
    # Try to use newer libinput interface then fall back to old
    # (depreciated) interface.
    if res := runcmd(('libinput', '--version'), check=False):
        return res.strip(), True

    res = runcmd(('libinput-list-devices', '--version'), check=False)
    return res and res.strip(), False


def get_devices_list(
    cmd_list_devices: str, device_list: str
) -> Iterator[dict[str, str]]:
    "Get list of devices and their attributes (as a dict) from libinput"
    if device_list:
        with open(device_list) as fd:
            stdout = fd.read()
    else:
        stdout = runcmd(cmd_list_devices.split())

    if stdout:
        dev = {}
        for line in stdout.splitlines():
            line = line.strip()
            if line and ':' in line:
                key, value = line.split(':', maxsplit=1)
                dev[key.strip().lower()] = value.strip()
            elif dev:
                yield dev
                dev = {}

        # Ensure we include last device
        if dev:
            yield dev


def get_device_info(
    name: str, cmd_list_devices: str, device_list: str
) -> dict[str, str]:
    "Determine libinput touchpad device and return device info"
    if not (devices := list(get_devices_list(cmd_list_devices, device_list))):
        print(
            'Can not see any devices, did you add yourself to the '
            'input group and reboot?',
            file=sys.stderr,
        )
        return {}

    # If a specific device name was asked for then return that device
    # This is the "Device" name from libinput list-devices command.
    if name:
        kdev = str(Path(name).resolve()) if name[0] == '/' else None
        for d in devices:
            # If the device name starts with a '/' then it is instead
            # considered as the explicit device path although since
            # device paths can change through reboots this is best to be
            # a symlink. E.g. users should use the corresponding full
            # path link under /dev/input/by-path/ or /dev/input/by-id/.
            if kdev:
                if d.get('kernel') == kdev:
                    return d
            elif d.get('device') == name:
                return d
        return {}

    # Otherwise filter for devices with touchpad capabilities
    touchpads = [
        d for d in devices if 'size' in d and 'pointer' in d.get('capabilities', {})
    ]

    if touchpads:
        devices = touchpads

    # Look for 1st device with touchpad in it's name
    # or, failing that, 1st device with trackpad in it's name
    for txt in ('touch ?pad', 'track ?pad'):
        for d in devices:
            if re.search(txt, d.get('device', ''), re.I):
                return d

    return touchpads[0] if touchpads else {}


def get_device(name: str, cmd_list_devices: str, device_list: str) -> dict[str, str]:
    "Determine libinput touchpad device and add fixed path info"
    if dev := get_device_info(name, cmd_list_devices, device_list):
        devname = dev.get('kernel')
        evname = ''
        if devname:
            devpath = Path(devname)

            # Also determine and prefer a non-volatile path merely
            # because it is more identifying for users.
            for dirstr in ('/dev/input/by-path', '/dev/input/by-id'):
                dirpath = Path(dirstr)
                if dirpath.exists():
                    for path in dirpath.iterdir():
                        if path.resolve() == devpath:
                            devname = str(path)
                            evname = f'({devpath.name})'
                            break
                    if evname:
                        break

        if devname:
            dev['_path'] = devname

        dev['_diag'] = f'{devname}{evname}: {dev.get("device", "?")}'
    return dev


class COMMAND:
    "Generic command handler"

    def __init__(self, largs: list[str]):
        self.reprstr = ' '.join(largs)

        # Expand '~' and env vars in executable command name
        largs[0] = os.path.expandvars(os.path.expanduser(largs[0]))
        self.argslist = largs

    def run(self) -> str | None:
        "Run this command + arguments"
        runcmd(self.argslist, block=False)

    def __str__(self) -> str:
        "Return string representation"
        return self.reprstr


# Table of internal commands
internal_commands = {}


def add_internal_command(cls) -> None:
    "Add configuration command to command lookup table based on name"
    internal_commands[re.sub('^COMMAND', '', cls.__name__)] = cls


class MyArgumentParser(argparse.ArgumentParser):
    "Custom ArgumentParser to return error text"

    def error(self, message):
        raise Exception(message)


@add_internal_command
class COMMAND_internal(COMMAND):
    "Internal command handler."

    # Commands currently supported follow. Each is configured with the
    # (X,Y) translation to be applied to the desktop grid.
    commands = (
        ('ws_up', (0, 1)),  # noqa: E241,E201
        ('ws_down', (0, -1)),  # noqa: E241,E201
        ('ws_left', (1, 0)),  # noqa: E241,E201
        ('ws_right', (-1, 0)),  # noqa: E241,E201
        ('ws_left_up', (1, 1)),  # noqa: E241,E201
        ('ws_left_down', (1, -1)),  # noqa: E241,E201
        ('ws_right_up', (-1, 1)),  # noqa: E241,E201
        ('ws_right_down', (-1, -1)),  # noqa: E241,E201
    )

    commands_list = [c[0] for c in commands]

    CMDTEST = 'wmctrl -m'.split()
    CMDLIST = 'wmctrl -d'.split()
    CMDSET = 'wmctrl -s'.split()

    def __init__(self, largs: list):
        "Action internal swipe commands"
        super().__init__(largs)

        # Set up command line arguments
        opt = MyArgumentParser(prog=self.argslist[0], description=self.__doc__)
        opt.add_argument(
            '-w',
            '--wrap',
            action='store_true',
            help='wrap workspaces when switching to/from start/end',
        )
        opt.add_argument(
            '-c',
            '--cols',
            type=int,
            help='number of columns in virtual desktop grid, default=1',
        )
        opt.add_argument('--row', type=int, default=0, help=argparse.SUPPRESS)
        opt.add_argument('--col', type=int, default=0, help=argparse.SUPPRESS)
        opt.add_argument(
            'action', choices=self.commands_list, help='Internal command to action'
        )
        cargs = opt.parse_args(self.argslist[1:])
        self.nowrap = not cargs.wrap
        self.rows = 0
        self.cols = 0

        if self.CMDTEST[0] and not runcmd(self.CMDTEST, check=False):
            print(
                f'Warning: must install {self.CMDTEST[0]} to use _internal command.',
                file=sys.stderr,
            )

        # Only do above check once
        self.CMDTEST[0] = ''

        if (cmdi := self.commands_list.index(cargs.action)) >= 2:
            if cargs.row or cargs.col:
                opt.error('Legacy "--row" and "--col" not supported')
            if cargs.cols is None:
                if cmdi < 4:
                    self.cols = 1
                    cmdi -= 2
                else:
                    opt.error('"--cols" must be specified')
            elif cargs.cols < 1:
                opt.error('"--cols" must be >= 1')
            else:
                self.cols = cargs.cols
        else:
            # Convert old legacy/depreciated arguments to new arguments
            if cargs.cols is not None:
                if cargs.cols < 1:
                    opt.error('"--cols" must be >= 1')
                self.cols = cargs.cols
            elif cargs.row:
                cmdi += 2
                self.cols = cargs.row
            elif cargs.col:
                self.rows = cargs.col
            else:
                self.cols = 1

        # Save the translations appropriate to this command
        self.xmove, self.ymove = self.commands[cmdi][1]

    def run(self, block: bool = False) -> str | None:
        "Get list of current workspaces and select next one"
        if not (stdout := runcmd(self.CMDLIST, check=False)):
            # This command can fail on GNOME when you have only a single
            # dynamic workspace (probably a GNOME bug) so let's just
            # fudge that default case.
            stdout = '0 *\n1 -'

        # Parse the output of above command
        lines = [ln.split(maxsplit=2)[1] for ln in stdout.strip().splitlines()]
        start = index = lines.index('*')
        num = len(lines)
        cols = self.cols or num // self.rows
        numv = ((num - 1) // cols + 1) * cols

        # Calculate new workspace X direction index
        if (count := self.xmove) < 0:
            if index % cols == 0:
                if self.nowrap:
                    return None
                index += cols - 1
                if index >= num:
                    if self.ymove == 0:
                        if self.nowrap:
                            return None
                        index = num - 1
            else:
                index += count
        elif count > 0:
            index += count
            if index % cols == 0:
                if self.nowrap:
                    return None
                index -= cols
            elif index >= num:
                if self.ymove == 0:
                    if self.nowrap:
                        return None
                    index -= numv - index

        # Calculate new workspace Y direction index
        if (count := self.ymove * cols) < 0:
            if index < cols and self.nowrap:
                return None
            index = (index + count) % numv
            if index >= num:
                index += count
        elif count > 0:
            index += count
            if index >= numv:
                if self.nowrap:
                    return None
                index = index % numv
            elif index >= num:
                if self.nowrap:
                    return None
                index = (index + count) % numv

        # Switch to desired workspace
        return (
            runcmd(self.CMDSET + [str(index)], block=block) if index != start else None
        )


# Table of gesture handlers
handlers = {}


def add_gesture_handler(cls) -> None:
    "Create gesture handler instance and add to lookup table based on name"
    handlers[cls.__name__] = cls()


class GESTURE(ABC):
    "Abstract base class for handling for gestures"

    extended_text = ''
    option_text = ''
    SUPPORTED_MOTIONS: tuple = tuple()

    def check_option(self, option) -> str | None:
        return None

    def __init__(self):
        "Initialise this gesture at program start"
        self.name = type(self).__name__
        self.motions = {}
        self.options = {}
        self.has_extended = False

    def add(self, motion: str, fingers: str, command: str) -> str | None:
        "Add a configured motion command for this gesture"
        motion_key = motion

        if self.option_text:
            if self.option_text in motion:
                motion_key, option = motion.split(self.option_text, maxsplit=1)
                err = self.check_option(option)
                if err:
                    return err

        if motion_key not in self.SUPPORTED_MOTIONS:
            opts = '" or "'.join(self.SUPPORTED_MOTIONS)
            if self.option_text:
                opts += '" or "' + '" or "'.join(
                    f'{i}{self.option_text}option' for i in self.SUPPORTED_MOTIONS
                )
            return (
                f'Gesture {self.name.lower()} does not support '
                f'motion "{motion_key}".\nMust be "{opts}"'
            )
        if not command:
            return 'No command configured'

        # If any extended gestures configured then set flag to enable
        # their discrimination
        if self.extended_text and self.extended_text in motion_key:
            self.has_extended = True

        try:
            cmds = shlex.split(command)
        except Exception as e:
            return str(e)

        cls = internal_commands.get(cmds[0], COMMAND)
        key = (motion, fingers) if fingers else motion

        try:
            self.motions[key] = cls(cmds)
        except Exception as e:
            return str(e)

        return None

    def begin(self, fingers: str) -> None:
        "Initialise this gesture at the start of motion"
        self.fingers = fingers
        self.data = [0.0, 0.0]
        self.starttime = monotonic()

    def update(self, coords: str) -> bool:
        return True

    def action(self, motion: str, *, command: COMMAND | None = None) -> None:
        "Action a motion command for this gesture"
        if command is None:
            command = self.motions.get((motion, self.fingers)) or self.motions.get(
                motion
            )

        if args.verbose:
            print(f'{PROGNAME}: {self.name} {motion} {self.fingers} {self.data}')
            if command:
                print('  ', command)

        if self.timeout > 0 and (self.starttime + self.timeout) < monotonic():
            if args.verbose:
                print('  ', 'timeout - no action')
            return

        if command and not args.debug:
            command.run()

    def complete_setup(self) -> None:
        "Complete setup of this gesture"
        self.timeout = timeoutv


@add_gesture_handler
class SWIPE(GESTURE):
    "Class to handle this type of gesture"

    SUPPORTED_MOTIONS = (
        'left',
        'right',
        'up',
        'down',
        'left_up',
        'right_up',
        'left_down',
        'right_down',
    )
    extended_text = '_'

    def update(self, coords: str) -> bool:
        "Update this gesture for a motion"
        # Ignore this update if we can not parse the numbers we expect
        try:
            x = float(coords[2])
            y = float(coords[3])
        except (ValueError, IndexError):
            return False

        self.data[0] += x
        self.data[1] += y
        return True

    def end(self) -> None:
        "Action this gesture at the end of a motion sequence"
        x, y = self.data
        abx = abs(x)
        aby = abs(y)

        # Require absolute distance movement beyond a small thresh-hold.
        if abx**2 + aby**2 < abzsquare:
            return

        # Discriminate left/right or up/down.
        # If significant movement in both planes the consider it a
        # oblique swipe (but only if any are configured)
        if abx > aby:
            motion = 'left' if x < 0 else 'right'
            if self.has_extended and abx > 0 and aby / abx > OBLIQUE_RATIO:
                motion += '_up' if y < 0 else '_down'
        else:
            motion = 'up' if y < 0 else 'down'
            if self.has_extended and aby > 0 and abx / aby > OBLIQUE_RATIO:
                motion = ('left_' if x < 0 else 'right_') + motion

        self.action(motion)


@add_gesture_handler
class PINCH(GESTURE):
    "Class to handle this type of gesture"

    SUPPORTED_MOTIONS = ('in', 'out', 'clockwise', 'anticlockwise')
    extended_text = 'clock'

    def update(self, coords: str) -> bool:
        "Update this gesture for a motion"
        # Ignore this update if we can not parse the numbers we expect
        try:
            x = float(coords[4])
            y = float(coords[5])
        except (ValueError, IndexError):
            return False

        self.data[0] += x - 1.0
        self.data[1] += y
        return True

    def end(self) -> None:
        "Action this gesture at the end of a motion sequence"
        ratio, angle = self.data

        if self.has_extended and abs(angle) > ROTATE_ANGLE:
            self.action('clockwise' if angle >= 0.0 else 'anticlockwise')
        elif ratio != 0.0:
            self.action('in' if ratio <= 0.0 else 'out')


@add_gesture_handler
class HOLD(GESTURE):
    "Class to handle this type of gesture"

    SUPPORTED_MOTIONS = ('on',)
    option_text = '+'

    def check_option(self, option: str) -> str | None:
        try:
            _ = float(option)
        except Exception:
            return f'Hold delay "{option}" must be an integer or float value.'
        return None

    def complete_setup(self) -> None:
        "Complete setup of this gesture"
        # No timeout on HOLD gestures
        self.timeout = 0
        self.delays = {}  # type: ignore

        # We parse the motions table to set up a table of delays for efficient
        # lookup at run time.
        for finger in range(0, 6):
            fstr = str(finger)

            # Explicit finger count delays inherit from 0 finger count delays
            delays = self.delays.get('0', {}).copy()

            for key in self.motions:
                motion, finger = key if isinstance(key, tuple) else (key, '0')
                if finger != fstr:
                    continue

                delay = motion.split('+', maxsplit=1)[1] if '+' in motion else '0'
                delays[float(delay)] = key

            # Delays are sorted by highest numeric value so we can
            # search for the largest delay first at run time.
            if delays:
                self.delays[fstr] = dict(sorted(delays.items(), reverse=True))

    def end(self) -> None:
        "Action this gesture at the end of a motion sequence"
        delay = monotonic() - self.starttime
        motion, command = 'on', None
        if delays := self.delays.get(self.fingers or '0'):
            # Work out which command to run based on delay. Action the
            # largest configured delay that is less than or equal to the
            # actual delay.
            for dvalue in delays:
                if delay >= dvalue:
                    motion = delays[dvalue]
                    command = self.motions.get(motion)
                    break
        elif delay > 0:
            # Define which time hold was released for debug monitoring
            motion = f'on-{delay:.2f}'

        self.action(motion, command=command)


# Table of configuration commands
conf_commands = {}


def add_conf_command(func: Callable[[str], str | None]) -> None:
    "Add configuration command to command lookup table based on name"
    conf_commands[re.sub('^conf_', '', func.__name__)] = func


@add_conf_command
def conf_gesture(lineargs: str) -> str | None:
    "Process a single gesture line in conf file"
    fields = lineargs.split(maxsplit=2)

    # Look for configured gesture. Sanity check the line.
    if len(fields) < 3:
        return 'Invalid gesture line - not enough fields'

    gesture, motion, command = fields
    if not (handler := handlers.get(gesture.upper())):
        opts = '" or "'.join([h.lower() for h in handlers])
        return f'Gesture "{gesture}" is not supported.\nMust be "{opts}"'

    # Gesture command can be configured with optional specific finger
    # count so look for that
    fingers, *fcommand = command.split(maxsplit=1)
    if fingers.isdigit() and len(fingers) == 1:
        command = fcommand[0] if fcommand else ''
    else:
        fingers = ''

    # Add the configured gesture
    return handler.add(motion.lower(), fingers, command)


@add_conf_command
def conf_device(lineargs: str) -> str | None:
    "Process a single device line in conf file"
    # Command line overrides configuration file
    if not args.device:
        args.device = lineargs

    return None if args.device else 'No device specified'


@add_conf_command
def swipe_threshold(lineargs: str) -> str | None:
    "Change swipe threshold"
    global swipe_min_threshold
    try:
        swipe_min_threshold = int(lineargs)
    except Exception:
        return 'Must be integer value'

    return None if swipe_min_threshold >= 0 else 'Must be >= 0'


@add_conf_command
def timeout(lineargs: str) -> str | None:
    "Change gesture timeout"
    global timeoutv
    try:
        timeoutv = float(lineargs)
    except Exception:
        return 'Must be float value'

    return None if timeoutv >= 0 else 'Must be >= 0'


def get_conf_line(line: str) -> str | None:
    "Process a single line in conf file"
    key, *argslist = line.split(maxsplit=1)

    # Old format conf files may have a ":" appended to the key
    key = key.rstrip(':')
    if not (conf_func := conf_commands.get(key)):
        opts = '" or "'.join(conf_commands)
        return f'Configuration command "{key}" is not supported.\nMust be "{opts}"'

    return conf_func(argslist[0] if argslist else '')


def get_conf(conffile: Path, confname: str) -> None:
    "Read given configuration file and store internal actions etc"
    with conffile.open() as fp:
        for num, line in enumerate(fp, 1):
            line = line.strip()
            if not line or line[0] == '#':
                continue

            if errmsg := get_conf_line(line):
                sys.exit(
                    f'Error at line {num} in file {confname}:\n>> {line} <<\n{errmsg}.'
                )


def unexpanduser(cfile: Path) -> str:
    "Return absolute path name, with $HOME replaced by ~"
    cfile_abs = cfile.resolve()

    if cfile_abs.parts[: len(HOME.parts)] != HOME.parts:
        return str(cfile_abs)

    return str(Path('~', *cfile_abs.parts[len(HOME.parts) :]))


# Search for configuration file. Use file given as command line
# argument, else look for file in search dir order.
def read_conf(conffile: str, defname: str) -> str:
    if conffile:
        confpath = Path(conffile)
        if not confpath.is_file():
            sys.exit(f'Conf file "{conffile}" is not a file or does not exist.')
    else:
        for confdir in CONFDIRS:
            confpath = Path(confdir, defname)
            if confpath.is_file():
                break
        else:
            opts = ' or '.join([unexpanduser(Path(c)) for c in CONFDIRS])
            sys.exit(f'No file {defname} in {opts}.')

    # Read and process the conf file
    # Hide any personal user dir/names from diag output
    get_conf(confpath, confname := unexpanduser(confpath))

    # Complete any final configuration required
    for h in handlers.values():
        h.complete_setup()

    return confname


def dbus_listener() -> None:
    "Listen on DBus"
    DBusGMainLoop(set_as_default=True)  # type: ignore

    def proc(busname: str, vals: dict[str, str], _) -> None:
        global session_locked
        if busname == 'org.freedesktop.login1.Session':
            if (val := vals.get('LockedHint')) is not None:
                session_locked = bool(val)

    # Listen to get session locked state
    dbus.SystemBus().add_signal_receiver(  # type: ignore
        proc,
        'PropertiesChanged',
        'org.freedesktop.DBus.Properties',
        'org.freedesktop.login1',
    )

    GLib.MainLoop().run()  # type: ignore


def gethash() -> str:
    "Return a crude hash identifier for this software version"
    progs = (PROGPATH, PROGPATH.with_name(PROGNAME + '-setup'))
    return hashlib.md5(
        b''.join(p.read_bytes() for p in progs if p.exists())
    ).hexdigest()


def main() -> None:
    global args, abzsquare

    # Set up command line arguments
    opt = argparse.ArgumentParser(description=__doc__)
    opt.add_argument('-c', '--conffile', help='alternative configuration file')
    opt.add_argument(
        '-v', '--verbose', action='store_true', help='output diagnostic messages'
    )
    opt.add_argument(
        '-d',
        '--debug',
        action='store_true',
        help='output diagnostic messages only, do not action gestures',
    )
    opt.add_argument(
        '-r',
        '--raw',
        action='store_true',
        help='output raw libinput debug-event messages only, do not action gestures',
    )
    opt.add_argument(
        '-l',
        '--list',
        action='store_true',
        help='just show environment and configuration',
    )
    opt.add_argument(
        '-V', '--version', action='store_true', help='just show program version'
    )
    opt.add_argument(
        '--device', help='explicit device name to use (or path if starts with /)'
    )
    # Test/diag hidden option to specify a file containing libinput list
    # device output to parse
    opt.add_argument('--device-list', help=argparse.SUPPRESS)
    args = opt.parse_args()

    if args.version:
        print(f'{PROGNAME} version {VERSION}')
        sys.exit()

    if args.debug or args.raw or args.list:
        args.verbose = True

    # Libinput changed the way in which it's utilities are called
    libvers, has_subcmd = get_libinput_vers()
    if not libvers:
        sys.exit('libinput helper tools do not seem to be installed?')

    if has_subcmd:
        cmd_debug_events = 'libinput debug-events'
        cmd_list_devices = 'libinput list-devices'
    else:
        cmd_debug_events = 'libinput-debug-events'
        cmd_list_devices = 'libinput-list-devices'

    if args.verbose:
        # Output various info/version info
        xsession = (
            os.getenv('XDG_SESSION_DESKTOP')
            or os.getenv('DESKTOP_SESSION')
            or 'unknown'
        )
        xtype = os.getenv('XDG_SESSION_TYPE') or 'unknown'
        xstr = f'session {xsession}+{xtype}'
        pf = platform.platform()
        pfpy = f'python {platform.python_version()}'
        lstr = f'libinput {libvers}'
        print(f'{PROGNAME}: {xstr} on {pf}, {pfpy}, {lstr}')

        # Output hash version/checksum of this program
        print(f'Version = {VERSION}, hash = {gethash()}')

    # Read and process the conf file
    confname = read_conf(args.conffile, CONFNAME)

    # List out available gestures if that is asked for
    if args.verbose:
        if not args.raw:
            print(f'Gestures configured in {confname}:')
            for h in handlers.values():
                for mpair, cmd in h.motions.items():
                    motion, fingers = (mpair, '') if isinstance(mpair, str) else mpair
                    print(f'{h.name.lower()} {motion:10}{fingers:>2} {cmd}')

            if swipe_min_threshold:
                print(f'swipe_threshold {swipe_min_threshold}')
            if timeoutv != DEFAULT_TIMEOUT:
                print(f'timeout {timeoutv}')

        if args.device:
            print(f'device {args.device}')

    # Get touchpad device
    if not args.device or args.device.lower() != 'all':
        if not (device := get_device(args.device, cmd_list_devices, args.device_list)):
            sys.exit('Could not determine touchpad device.')
    else:
        device = None

    if args.verbose:
        if device:
            print(f'{PROGNAME}: device {device.get("_diag")}')
        else:
            print(f'{PROGNAME}: monitoring all devices')

    # If just called to list out above environment info then exit now
    if args.list:
        if status := runcmd((PROGNAME + '-setup', 'status'), check=False):
            print(status.strip())
        sys.exit()

    # Make sure only one instance running for current user
    user = getpass.getuser()
    lockfile, pidfile = open_lock(user)

    # Note we get the lockfile back merely to keep it held open for this
    # running instance
    if not lockfile or not pidfile:
        sys.exit(f'{PROGNAME} is already running for {user}, terminating ..')

    # Set up square of swipe threshold
    abzsquare = float(swipe_min_threshold**2)

    # Note your must "sudo gpasswd -a $USER input" then reboot for
    # permission to access the device.
    devstr = f' --device {device.get("_path")}' if device else ''
    command = f'stdbuf -oL -- {cmd_debug_events}{devstr}'

    if dbus_imported:
        t = threading.Thread(target=dbus_listener)
        t.daemon = True
        t.start()

    cmd = subprocess.Popen(
        shlex.split(command), stdout=subprocess.PIPE, bufsize=1, universal_newlines=True
    )

    # Store PIDs for potential kill
    pidfile.write(f'{os.getpid()}\n{cmd.pid}\n')
    pidfile.flush()
    os.fsync(pidfile.fileno())

    # Sit in a loop forever reading the libinput messages ..
    handler = None
    for line in cmd.stdout or []:
        # Ignore gestures if this session is locked
        if session_locked:
            continue

        # Just output raw messages if in that mode
        if args.raw:
            print(line.strip())
            continue

        # Only interested in gestures
        if 'GESTURE_' not in line or ' +' not in line:
            continue

        # Split received message line into relevant fields
        split1, split2 = line.split(' +', maxsplit=1)

        gevent = split1.split(maxsplit=2)[1]
        try:
            gesture, event = gevent[8:].split('_')
        except Exception:
            continue

        _, fingers, *argslist = split2.split(maxsplit=2)
        params = argslist[0].rstrip() if argslist else ''

        # Action each type of event
        if event == 'UPDATE':
            if handler:
                # Split parameters into list of clean numbers
                if not handler.update(re.split(r'[^-.\d]+', params)):
                    print(
                        f'Could not parse {gesture} {event}: {params}', file=sys.stderr
                    )

        elif event == 'BEGIN':
            if handler := handlers.get(gesture):
                handler.begin(fingers)
            else:
                print(f'Unknown gesture received: {gesture}.', file=sys.stderr)
        elif event == 'END':
            # Ignore gesture if final action is cancelled
            if handler:
                if params != 'cancelled':
                    handler.end()
                handler = None
        else:
            print(
                f'Unknown gesture {gesture} + event {event} received.', file=sys.stderr
            )


if __name__ == '__main__':
    main()
