about summary refs log tree commit diff stats
path: root/fungus/dispatcher.py
blob: fd922a7cb90e34007853a086c0e3c93e7643cf1c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/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