#!/usr/bin/env python3
# summary: Watch desktop events and handle brightness, microphone mute, and sound feedback.
"""starchaser shell events watch: the shell's shared service events and backlight control.

Uses GIO subscriptions and logind on persistent connections. Ends with the owning shell.
Built-in brightness uses logind; external monitors use an asynchronous DDC worker; sound assets are prepared once at startup.
"""
import ctypes
import json
import os
import queue
import runpy
import select
import signal
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_lights import screen_backlights


def network_tree_change(interface, member):
    """Saved profiles and device topology change rows; state/statistics signals only change badges."""
    return ((interface == 'org.freedesktop.NetworkManager.Settings' and member in ('NewConnection', 'ConnectionRemoved'))
            or (interface == 'org.freedesktop.NetworkManager.Settings.Connection' and member in ('Updated', 'Removed'))
            or (interface == 'org.freedesktop.NetworkManager' and member in ('DeviceAdded', 'DeviceRemoved')))


def menu_file_targets(home, config, data, state):
    """Tree inputs that can change without a package transaction; values mark recursive picture sources."""
    repo = Path(__file__).resolve().parent.parent
    return {Path('/usr/share/applications'): False, Path('/var/lib/flatpak/exports/share/applications'): False,
            home / '.local/share/applications': False, home / '.local/share/flatpak/exports/share/applications': False,
            home / 'Applications': False, home / 'Work': None, home / '.local/bin': False,
            home / 'Pictures/Wallpapers': True, home / 'Documents/Starchaser/Wallpapers': True,
            data / 'starchaser/wallpapers': True, Path('/usr/share/starchaser/wallpapers'): True,
            config / 'starchaser/themes': True, Path('/usr/share/starchaser/themes'): True,
            repo / 'themes': True, repo / 'share/wallpapers': True,
            config / 'keybinds/menu.py': False, config / 'keybinds/apps.json': False,
            config / 'starchaser/software/catalog.json': False, config / 'starchaser/ai.json': False,
            config / 'agents/default': False, config / 'starchaser/theme-overrides.json': False,
            state / 'starchaser/welcome-waiting': False}


class MenuFiles:
    """Follow tree inputs across creation, replacement, and external symlink edits."""
    def __init__(self, gio, glib, targets, changed):
        self.gio, self.glib, self.targets, self.changed = gio, glib, targets, changed
        self.monitors, self.identities = {}, {}
        self.pending = 0
        self.refresh()

    def linked_targets(self):
        # Directory monitors do not report writes through a symlink outside that directory.
        # Keep each link and its destination so atomic saves, retargeting, and broken links recover.
        targets, seen = {}, set()
        pending = [(path, recursive, 0) for path, recursive in self.targets.items()]
        while pending:
            target, recursive, depth = pending.pop()
            if depth > 40 or (target, recursive) in seen:
                continue
            seen.add((target, recursive))
            resolved = Path('/') if target.is_absolute() else Path.cwd()
            parts = list(target.parts[1:] if target.is_absolute() else target.parts)
            links = 0
            while parts:
                name = parts.pop(0)
                if name == '..':
                    # This directory must still exist even when '..' leaves it. In particular,
                    # resolve preceding symlinks before taking the parent, just as open() does.
                    targets.setdefault(resolved, None)
                    resolved = resolved.parent
                    continue
                component = resolved / name
                if component.is_symlink():
                    targets.setdefault(component, None)
                    try:
                        destination = Path(os.readlink(component))
                    except OSError:
                        break
                    links += 1
                    if links > 40:  # Match the filesystem's bound, including cyclic links.
                        break
                    if destination.is_absolute():
                        resolved = Path('/')
                        parts[:0] = destination.parts[1:]
                    else:
                        parts[:0] = destination.parts
                else:
                    resolved = component
            else:
                target = resolved
                if target not in targets or (recursive is not None and targets[target] is not True):
                    targets[target] = recursive
                if recursive is not None and target.is_dir():
                    try:
                        children = ((Path(folder) / name for folder, dirs, files in os.walk(target) for name in dirs + files)
                                    if recursive else target.iterdir())
                        pending.extend((child, recursive, depth + 1) for child in children if child.is_symlink())
                    except OSError:
                        pass
        return targets

    def refresh(self):
        self.inputs = self.linked_targets()
        directories = set()
        for target, recursive in self.inputs.items():
            ancestor = target.parent
            while not ancestor.is_dir() and ancestor != ancestor.parent:
                ancestor = ancestor.parent
            directories.add(ancestor)
            if recursive is not None and target.is_dir():
                directories.add(target)
                if recursive:
                    directories.update(Path(folder) for folder, _, _ in os.walk(target))
        identities = {}
        for directory in directories:
            try:
                info = directory.stat()
                identities[directory] = (info.st_dev, info.st_ino)
            except OSError:
                pass
        for path in list(self.monitors):
            if self.identities.get(path) != identities.get(path):
                self.monitors.pop(path).cancel()
        for path in identities:
            if path not in self.monitors:
                try:
                    observer = self.gio.File.new_for_path(str(path)).monitor_directory(self.gio.FileMonitorFlags.WATCH_MOVES, None)
                    observer.connect('changed', self.on_change)
                    self.monitors[path] = observer
                except self.glib.Error as error:
                    print(f'starchaser shell events: menu input: {error}', file=sys.stderr)
        self.identities = identities

    def on_change(self, _observer, file, other, _event):
        paths = [Path(f.get_path()) for f in (file, other) if f is not None and f.get_path()]
        if not any(path == target or target.is_relative_to(path)
                   or (recursive is not None and path.is_relative_to(target))
                   for path in paths for target, recursive in self.inputs.items()):
            return
        if self.pending:
            self.glib.source_remove(self.pending)
        self.pending = self.glib.timeout_add(300, self.settled)

    def settled(self):
        self.pending = 0
        self.refresh()  # subscribe new directories before asking the menu to take its snapshot
        self.changed()
        return False

    def close(self):
        if self.pending:
            self.glib.source_remove(self.pending)
            self.pending = 0
        for observer in self.monitors.values():
            observer.cancel()
        self.monitors.clear()


def network_change(member, parameters):
    """Only changes used by the network UI; nmcli's own permission checks must not cause another probe."""
    if member in ('StateChanged', 'DeviceAdded', 'DeviceRemoved', 'Updated', 'Removed'):
        return True
    if member != 'PropertiesChanged':
        return False
    if len(parameters) == 3 and isinstance(parameters[1], dict):
        keys = set(parameters[1]) | set(parameters[2])
    elif len(parameters) == 1 and isinstance(parameters[0], dict):
        keys = set(parameters[0])
    else:
        return False
    return bool(keys & {'State', 'StateReason', 'Connectivity', 'NetworkingEnabled', 'WirelessEnabled',
        'WirelessHardwareEnabled', 'WwanEnabled', 'WwanHardwareEnabled', 'PrimaryConnection', 'ActiveConnections',
        'Devices', 'AllDevices', 'ActiveConnection', 'ActiveAccessPoint', 'AccessPoints', 'AvailableConnections',
        'Carrier', 'Interface', 'IpInterface', 'Managed', 'Id', 'Ssid', 'Strength', 'VpnState'})


def brightness_level(current, maximum, direction):
    # Match brightnessctl's perceptual exponent (-e4), 5% step and raw minimum (-n2).
    percent = 100 * (max(0, current) / max(1, maximum)) ** .25
    percent = min(100, max(0, percent + direction * 5))
    return min(maximum, max(2, round(maximum * (percent / 100) ** 4)))


def retire_standalone_corners(helper):
    """Migrate the previous session's same-engine daemon, without touching one-shot checks or another account."""
    for process in Path('/proc').glob('[0-9]*'):
        fd = None
        try:
            # Open the process identity before reading metadata, so PID reuse can never redirect the signal.
            fd = os.pidfd_open(int(process.name))
            if process.stat().st_uid != os.getuid() or int(process.name) == os.getpid():
                continue
            args = [a for a in (process / 'cmdline').read_bytes().split(b'\0') if a]
            if len(args) != 2 or Path(os.fsdecode(args[1])).resolve() != helper:
                continue
            signal.pidfd_send_signal(fd, signal.SIGTERM)
            select.select([fd], [], [], 2)
        except (OSError, ValueError):
            continue
        finally:
            if fd is not None:
                os.close(fd)


def corners_worker():
    helper = Path(__file__).resolve().with_name('starchaser-corners')
    try:
        retire_standalone_corners(helper)
        engine = runpy.run_path(str(helper))
        engine['single_instance']()
        if engine['load_shaders']():
            engine['Corners']().listen()
    except SystemExit:
        pass
    except Exception as error:
        print(f'starchaser shell events: corners: {error}', file=sys.stderr, flush=True)


class TerminalObserver:
    """Keep the existing terminal-specific opacity policy, driven by the shell's focus/file events."""
    def __init__(self, engine):
        self.engine = engine
        self.focused = ''
        self.update(None)

    def update(self, address):
        e = self.engine
        new = e['focused_now']() if address is None else address.removeprefix('0x')
        if e['load_look'](force=address is None) or address is None:
            e['apply_all'](new)
        elif new != self.focused:
            current = e['clients']()
            for addr, alpha in ((self.focused, e['INACTIVE']), (new, e['ACTIVE'])):
                if addr in current and e['is_terminal'](current[addr]):
                    e['set_opacity'](current[addr], alpha)
        self.focused = new


def terminal_worker(requests):
    helper = Path(__file__).resolve().parent.parent / 'config/hypr/scripts/term-focus.py'
    personal = Path.home() / '.config/hypr/scripts/term-focus.py'
    while True:
        try:
            if personal.is_file() and personal.read_bytes() != helper.read_bytes():
                requests.disabled = True  # Hyprland starts personal replacements; do not retain their events.
                return
            for old in (helper, personal, Path('/usr/share/starchaser/config/hypr/scripts/term-focus.py')):
                if old.is_file() and old.read_bytes() == helper.read_bytes():
                    retire_standalone_corners(old.resolve())
            namespace = runpy.run_path(str(helper))
            observer = TerminalObserver(namespace['main'].__globals__)
            break
        except Exception as error:
            print(f'starchaser shell events: terminals: {error}', file=sys.stderr, flush=True)
            time.sleep(2)  # retry initialization failures; the healthy observer waits only for events
    while True:
        try:
            observer.update(requests.get())
        except Exception as error:
            print(f'starchaser shell events: terminals: {error}', file=sys.stderr, flush=True)


def sound_files():
    sound = Path('/usr/share/sounds/freedesktop/stereo/audio-volume-change.oga')
    if not sound.is_file():
        return {}
    result = {'plain': sound.as_uri()}
    cache = Path(os.environ.get('XDG_CACHE_HOME') or Path.home() / '.cache') / 'starchaser'
    cache.mkdir(parents=True, exist_ok=True)
    for lead in ('.25', '.7'):
        dest = cache / ('volume-key-' + lead + '.oga')
        if not dest.is_file():
            fd, name = tempfile.mkstemp(dir=cache, prefix='volume-key-', suffix='.oga')
            os.close(fd)
            tmp = Path(name)
            try:
                subprocess.run(['ffmpeg', '-loglevel', 'error', '-y', '-i', str(sound),
                                '-af', f'adelay={round(float(lead)*1000)}:all=1', '-c:a', 'libvorbis', str(tmp)],
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10, check=True)
                tmp.replace(dest)
            except (OSError, subprocess.SubprocessError):
                tmp.unlink(missing_ok=True)
        result[lead] = dest.as_uri() if dest.is_file() else sound.as_uri()
    return result


class PulseMicrophone:
    """libpulse fallback for virtual inputs Quickshell exposes without an audio object."""
    def __init__(self):
        self.lib = ctypes.CDLL('libpulse.so.0')
        ptr, integer, string = ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p
        functions = {
            'pa_mainloop_new': ([], ptr), 'pa_mainloop_get_api': ([ptr], ptr),
            'pa_mainloop_iterate': ([ptr, integer, ptr], integer), 'pa_mainloop_free': ([ptr], None),
            'pa_context_new': ([ptr, string], ptr), 'pa_context_connect': ([ptr, string, integer, ptr], integer),
            'pa_context_get_state': ([ptr], integer), 'pa_context_disconnect': ([ptr], None),
            'pa_context_unref': ([ptr], None), 'pa_operation_get_state': ([ptr], integer),
            'pa_operation_unref': ([ptr], None),
            'pa_context_get_source_info_by_name': ([ptr, string, ptr, ptr], ptr),
            'pa_context_set_source_mute_by_name': ([ptr, string, integer, ptr, ptr], ptr),
        }
        for name, (args, result) in functions.items():
            getattr(self.lib, name).argtypes = args
            getattr(self.lib, name).restype = result
        self.loop = self.lib.pa_mainloop_new()
        self.context = self.lib.pa_context_new(self.lib.pa_mainloop_get_api(self.loop), b'Starchaser keys')
        self.lib.pa_context_connect(self.context, None, 0, None)

    def wait(self, done):
        deadline = time.monotonic() + 2
        while not done() and time.monotonic() < deadline:
            if self.lib.pa_context_get_state(self.context) in (5, 6):
                raise OSError('Audio server disconnected')
            self.lib.pa_mainloop_iterate(self.loop, 0, None)
            time.sleep(.002)
        if not done():
            raise OSError("Audio server didn't answer")

    def toggle(self):
        class Spec(ctypes.Structure):
            _fields_ = [('format', ctypes.c_int), ('rate', ctypes.c_uint32), ('channels', ctypes.c_uint8)]
        class Map(ctypes.Structure):
            _fields_ = [('channels', ctypes.c_uint8), ('map', ctypes.c_int * 32)]
        class Volume(ctypes.Structure):
            _fields_ = [('channels', ctypes.c_uint8), ('values', ctypes.c_uint32 * 32)]
        class Info(ctypes.Structure):
            _fields_ = [('name', ctypes.c_char_p), ('index', ctypes.c_uint32), ('description', ctypes.c_char_p),
                        ('spec', Spec), ('map', Map), ('owner', ctypes.c_uint32), ('volume', Volume), ('mute', ctypes.c_int)]
        self.wait(lambda: self.lib.pa_context_get_state(self.context) == 4)
        result = {}
        @ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(Info), ctypes.c_int, ctypes.c_void_p)
        def info(_context, source, end, _data):
            if source and not end:
                value = source.contents
                result.update(name=value.name, muted=not bool(value.mute),
                              percent=round(sum(value.volume.values[:value.volume.channels]) * 100
                                            / max(1, value.volume.channels) / 65536))
        op = self.lib.pa_context_get_source_info_by_name(self.context, b'@DEFAULT_SOURCE@', info, None)
        if not op:
            raise OSError('No microphone')
        try:
            self.wait(lambda: self.lib.pa_operation_get_state(op) != 0)
        finally:
            self.lib.pa_operation_unref(op)
        if not result:
            raise OSError('No microphone')
        succeeded = []
        @ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p)
        def changed(_context, success, _data):
            succeeded.append(bool(success))
        op = self.lib.pa_context_set_source_mute_by_name(self.context, result['name'], result['muted'], changed, None)
        if not op:
            raise OSError("Couldn't mute microphone")
        try:
            self.wait(lambda: self.lib.pa_operation_get_state(op) != 0)
        finally:
            self.lib.pa_operation_unref(op)
        if succeeded != [True]:
            raise OSError("Couldn't mute microphone")
        return result

    def close(self):
        self.lib.pa_context_disconnect(self.context)
        self.lib.pa_context_unref(self.context)
        self.lib.pa_mainloop_free(self.loop)


def watch():
    import gi
    gi.require_version('Gio', '2.0')
    gi.require_version('Gst', '1.0')
    from gi.repository import Gio, GLib, Gst
    loop = GLib.MainLoop()
    stopping = False
    def stop(*_):
        nonlocal stopping
        stopping = True
        loop.quit()
    parent = os.getppid()
    signal.signal(signal.SIGTERM, stop)
    ctypes.CDLL(None).prctl(1, signal.SIGTERM, 0, 0, 0)
    if os.getppid() != parent:
        return
    threading.Thread(target=corners_worker, daemon=True).start()
    terminals = queue.Queue()
    threading.Thread(target=terminal_worker, args=(terminals,), daemon=True).start()
    sounds = sound_files()
    Gst.init(None)
    player = Gst.ElementFactory.make('playbin', 'volume-feedback')
    sink = Gst.ElementFactory.make('pulsesink', 'volume-output')
    if sink is not None:
        sink.set_property('stream-properties', Gst.Structure.from_string('props,media.role=(string)Notification')[0])
        player.set_property('audio-sink', sink)
    player.set_state(Gst.State.READY)
    media_bus = player.get_bus()
    media_bus.add_signal_watch()
    def media_finished(_bus, message):
        if message.type in (Gst.MessageType.EOS, Gst.MessageType.ERROR):
            player.set_state(Gst.State.READY)  # release the audio stream between keys
    media_bus.connect('message', media_finished)
    def emit(event, **values):
        print(json.dumps(dict(event=event, **values)), flush=True)
    bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
    def network_signal(_bus, _sender, _path, interface, member, parameters, *_):
        if network_change(member, parameters.unpack()):
            emit('network')
        if network_tree_change(interface, member):
            emit('menu-inputs')
    bus.signal_subscribe('org.freedesktop.NetworkManager', None, None, None, None,
                         Gio.DBusSignalFlags.NONE, network_signal)
    session_bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
    session_bus.signal_subscribe('org.freedesktop.DBus', 'org.freedesktop.DBus', 'NameOwnerChanged',
                                 '/org/freedesktop/DBus', 'org.freedesktop.Notifications',
                                 Gio.DBusSignalFlags.NONE, lambda *_: emit('notification-owner'))
    runtime = Path(os.environ.get('XDG_RUNTIME_DIR') or f'/run/user/{os.getuid()}')
    sessions = runtime / 'starchaser-agents'
    sessions.mkdir(exist_ok=True)
    monitor = Gio.File.new_for_path(str(sessions)).monitor_directory(Gio.FileMonitorFlags.NONE, None)
    monitor.connect('changed', lambda *_: emit('agents'))
    monitors = []
    config = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config')
    state = Path(os.environ.get('XDG_STATE_HOME') or Path.home() / '.local/state')
    data = Path(os.environ.get('XDG_DATA_HOME') or Path.home() / '.local/share')
    menu_files = MenuFiles(Gio, GLib, menu_file_targets(Path.home(), config, data, state), lambda: emit('menu-inputs'))
    for service in ('net.hadess.PowerProfiles', 'org.freedesktop.UPower.PowerProfiles'):
        bus.signal_subscribe(service, 'org.freedesktop.DBus.Properties', 'PropertiesChanged', None, None,
                             Gio.DBusSignalFlags.NONE, lambda *_: emit('menu-inputs'))
    def watch_file(path, event):
        observer = Gio.File.new_for_path(str(path)).monitor_file(Gio.FileMonitorFlags.WATCH_MOVES, None)
        observer.connect('changed', lambda *_: emit(event))
        monitors.append(observer)
    # A direct database update also invalidates the resident menu; no menu-open scan or idle polling.
    package_wait = 0
    def packages_settled():
        nonlocal package_wait
        if Path('/var/lib/pacman/db.lck').exists():
            return True  # only while the transaction is active
        package_wait = 0
        emit('packages')
        return False
    def packages_changed(*_):
        nonlocal package_wait
        if package_wait:
            GLib.source_remove(package_wait)
        package_wait = GLib.timeout_add(1000, packages_settled)
    for directory in (Path('/var/lib/pacman/local'), Path('/var/lib/pacman/sync')):
        observer = Gio.File.new_for_path(str(directory)).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None)
        observer.connect('changed', packages_changed)
        monitors.append(observer)
    watch_file(config / 'starchaser/fleet-settings.json', 'fleet-settings')
    for name in ('cockpit.json', 'theme-overrides.json', 'notifications.json', 'power.json', 'shortcuts.json'):
        watch_file(config / 'starchaser' / name, 'settings-owner')
    for name in ('input.lua', 'shortcut-profile'):
        watch_file(config / 'hypr' / name, 'settings-owner')
    watch_file(state / 'starchaser/theme.json', 'settings-owner')
    for directory in (state / 'starchaser/fleet-settings', runtime / 'starchaser/fleet-settings'):
        directory.mkdir(parents=True, exist_ok=True, mode=0o700)
        for name in ('state.json', 'catch-up.json'):
            watch_file(directory / name, 'fleet-settings')
    watch_file(Path('/run/starchaser/firewall-public-pause.json'), 'pause')
    # Taskbar reads that used to poll: a help grant (starchaser link writes the lease, pairing writes the peers) and
    # the add-ons that can put tiles on the desktop or in Quick settings (the add-on settings and their folder).
    devices = data / 'starchaser/devices'
    for name in ('help-lease.json', 'peers.json'):
        watch_file(devices / name, 'help')
    watch_file(config / 'starchaser/satellites.json', 'addons')
    addons = Gio.File.new_for_path(str(data / 'starchaser/satellites')).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None)
    addons.connect('changed', lambda *_: emit('addons'))
    monitors.append(addons)
    session_path = None
    ddc_pending = 0
    ddc_running = False
    ddc_timer = 0
    def ddc_done(process, result):
        nonlocal ddc_running
        try:
            success, output, errors = process.communicate_utf8_finish(result)
            data = json.loads(output)
            if data.get('percent') is not None and not list(Path('/sys/class/backlight').glob('*')):
                emit('brightness', percent=data['percent'])
        except Exception:
            pass
        ddc_running = False
        if ddc_pending: ddc_start()
    def ddc_start():
        nonlocal ddc_pending, ddc_running, ddc_timer
        ddc_timer = 0
        if ddc_running or not ddc_pending: return False
        step = max(-20, min(20, ddc_pending)); ddc_pending = 0
        try:
            worker = Gio.Subprocess.new(['starchaser', 'laptop', 'step-monitors', str(step)],
                Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_SILENCE)
            ddc_running = True
            worker.communicate_utf8_async(None, None, ddc_done)
        except Exception:
            ddc_running = False
        return False
    def key(direction):
        nonlocal ddc_pending, ddc_timer
        ddc_pending = max(-20, min(20, ddc_pending + direction * 5))
        if not ddc_timer and not ddc_running: ddc_timer = GLib.timeout_add(150, ddc_start)
        nonlocal session_path
        # The same choice as the Brightness slider: the device that changes the panel, not the first one listed.
        devices = screen_backlights()
        if not devices:
            return
        if session_path is None:
            result = bus.call_sync('org.freedesktop.login1', '/org/freedesktop/login1',
                                   'org.freedesktop.login1.Manager', 'GetSessionByPID',
                                   GLib.Variant('(u)', (os.getpid(),)), None, Gio.DBusCallFlags.NONE, 2000, None)
            session_path = result.unpack()[0]
        shown = None
        for device in devices:
            value = brightness_level(device['current'], device['maximum'], direction)
            bus.call_sync('org.freedesktop.login1', session_path, 'org.freedesktop.login1.Session',
                          'SetBrightness', GLib.Variant('(ssu)', ('backlight', device['id'], value)),
                          None, Gio.DBusCallFlags.NONE, 2000, None)
            # The OSD reports the hardware level, as the existing script did, not the exponent-adjusted step.
            if shown is None: shown = round(value * 100 / max(1, device['maximum']))
        emit('brightness', percent=shown)
    pending = b''
    pulse = None
    def input_ready(fd, condition):
        nonlocal pending, pulse
        raw = os.read(fd, 65536)
        if not raw:
            loop.quit()
            return False
        pending += raw
        while b'\n' in pending:
            line, pending = pending.split(b'\n', 1)
            try:
                request = json.loads(line)
                if 'terminal-focus' in request and (request['terminal-focus'] is None or isinstance(request['terminal-focus'], str)):
                    if not getattr(terminals, 'disabled', False):
                        terminals.put(request['terminal-focus'])
                elif request.get('brightness') in (-1, 1):
                    key(request['brightness'])
                elif request.get('mic') == 'toggle':
                    if pulse is None:
                        pulse = PulseMicrophone()
                    result = pulse.toggle()
                    emit('mic', percent=result['percent'], muted=result['muted'])
                elif request.get('sound') in sounds.values():
                    media_bus.set_flushing(True)
                    player.set_state(Gst.State.READY)  # key repeat replaces, rather than stacks, the previous blip
                    player.set_property('uri', request['sound'])
                    media_bus.set_flushing(False)
                    player.set_state(Gst.State.PLAYING)
            except (ValueError, OSError, GLib.Error):
                if pulse is not None:
                    pulse.close()
                    pulse = None
        return True
    GLib.io_add_watch(sys.stdin.fileno(), GLib.IO_IN | GLib.IO_HUP, input_ready)
    emit('ready', sounds=sounds)
    emit('menu-inputs')  # reconcile any changes while the bridge was disconnected
    try:
        if not stopping:
            loop.run()
    finally:
        # Finish native audio work before interpreter teardown, including a normal session sign-out.
        player.set_state(Gst.State.NULL)
        if pulse is not None:
            pulse.close()
        monitor.cancel()
        menu_files.close()
        for observer in monitors:
            observer.cancel()


if __name__ == '__main__':
    if sys.argv[1:] in (['--help'], ['-h'], ['help']):
        print(__doc__)
    elif sys.argv[1:] == ['watch']:
        watch()
    else:
        sys.exit('Usage: starchaser shell events watch')
