#!/usr/bin/python3 """Thread-safe callback dispatcher for the GTK main loop. Background threads submit work via ``Dispatcher.submit()``; a periodic timeout pump drains the queue on the GTK main thread. This replaces scattered ``GLib.idle_add`` calls with a single injectable coordinator, making the threading layer swappable and testable. """ from __future__ import annotations from collections.abc import Callable from queue import Queue from typing import Any class GtkDispatcher: """Drains a thread-safe callback queue onto the GTK main loop. Parameters ---------- pump_fn : callable A function that creates a periodic timeout on the GTK main thread and returns its source ID (e.g. ``lambda d: GLib.timeout_add(50, d.pump)``). """ def __init__(self, pump_fn: Callable[[GtkDispatcher], int | None]) -> None: self._queue: Queue[tuple[Callable, tuple[Any, ...]]] = Queue() self._pump_id: int | None = pump_fn(self) # ── Public API ────────────────────────────────────────────────────── def submit(self, fn: Callable, *args: Any) -> None: """Schedule *fn* to be called with *args* on the GTK main thread. Safe to call from any thread. """ self._queue.put((fn, args)) def pump(self) -> bool: """Drain the queue. Returns ``True`` to keep the timeout alive.""" while not self._queue.empty(): fn, args = self._queue.get_nowait() fn(*args) return True def stop(self) -> None: """Remove the timeout source and clear pending callbacks.""" if self._pump_id is not None: from gi.repository import GLib # type: ignore[import-untyped] GLib.source_remove(self._pump_id) self._pump_id = None self._queue.queue.clear() # --------------------------------------------------------------------------- # Convenience — no-op dispatcher for when none is supplied # --------------------------------------------------------------------------- class _NoOpDispatcher: """A dispatcher that discards all submissions (no-op).""" def submit(self, fn: Callable, *args: Any) -> None: fn(*args) # call directly — assumes main-thread context def stop(self) -> None: pass