about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@fakecake.org>2026-07-04 13:27:56 +0300
committerAndrew Dolgov <fox@fakecake.org>2026-07-04 13:27:56 +0300
commita2594fbd38afc711560aed2e9b4e703a2b57dcbe (patch)
tree99894dbf3f78f97f715c6de2e0d30f9021cf4c9b
parent57721c1c69fd2d7c2032b6e32c4bb83e4849cd36 (diff)
downloadfungus-launcher-a2594fbd38afc711560aed2e9b4e703a2b57dcbe.tar.gz
fungus-launcher-a2594fbd38afc711560aed2e9b4e703a2b57dcbe.tar.xz
abstract glib.idle_add into a separate dispatcher
-rw-r--r--fungus/add_game_dialog.py22
-rw-r--r--fungus/dispatcher.py70
-rw-r--r--fungus/main_window.py9
-rw-r--r--fungus/meson.build1
-rw-r--r--fungus/settings_dialog.py38
5 files changed, 109 insertions, 31 deletions
diff --git a/fungus/add_game_dialog.py b/fungus/add_game_dialog.py
index a1161f3..65af71b 100644
--- a/fungus/add_game_dialog.py
+++ b/fungus/add_game_dialog.py
@@ -27,6 +27,7 @@ from fungus.constants import (
     icons_dir,
     prefixes_dir,
 )
+from fungus.dispatcher import GtkDispatcher
 
 from fungus.shortcuts import (
     set_default_icon,
@@ -43,7 +44,7 @@ from fungus.utils import (
 
 
 class AddGame(EntryTooltipMixin, Gtk.Dialog):
-    def __init__(self, parent, file_path, is_editing=False):
+    def __init__(self, parent, file_path, is_editing=False, dispatcher=None):
         """Build the AddGame dialog UI with two notebook pages and wire up all handlers."""
         self._is_editing = is_editing
         # Initialize the AddGame dialog
@@ -51,6 +52,7 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog):
         self.set_resizable(False)
         self.set_modal(True)
         self.parent_window = parent
+        self.dispatcher = dispatcher or GtkDispatcher(lambda _: None)
         self.set_icon_from_file(fungus_png)
         self.icon_directory = f"{icons_dir}/icon_temp/"
 
@@ -480,9 +482,9 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog):
                     [sys.executable, fungus_run_path, "--game", title_formatted, "--cmd", file_run],
                 )
                 process.wait()
-                GLib.idle_add(self.set_sensitive, True)
-                GLib.idle_add(self.parent_window.set_sensitive, True)
-                GLib.idle_add(self.blocking_window.destroy)
+                self.dispatcher.submit(self.set_sensitive, True)
+                self.dispatcher.submit(self.parent_window.set_sensitive, True)
+                self.dispatcher.submit(self.blocking_window.destroy)
 
             self.blocking_window = Gtk.Window()
             self.blocking_window.set_transient_for(self.parent_window)
@@ -682,9 +684,9 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog):
                 [sys.executable, fungus_run_path, "--game", title_formatted, "--cmd", "winecfg"],
             )
             process.wait()
-            GLib.idle_add(self.set_sensitive, True)
-            GLib.idle_add(self.parent_window.set_sensitive, True)
-            GLib.idle_add(self.blocking_window.destroy)
+            self.dispatcher.submit(self.set_sensitive, True)
+            self.dispatcher.submit(self.parent_window.set_sensitive, True)
+            self.dispatcher.submit(self.blocking_window.destroy)
 
         self.blocking_window = Gtk.Window()
         self.blocking_window.set_transient_for(self.parent_window)
@@ -713,9 +715,9 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog):
                 [sys.executable, fungus_run_path, "--game", title_formatted, "--cmd", "winetricks"],
             )
             process.wait()
-            GLib.idle_add(self.set_sensitive, True)
-            GLib.idle_add(self.parent_window.set_sensitive, True)
-            GLib.idle_add(self.blocking_window.destroy)
+            self.dispatcher.submit(self.set_sensitive, True)
+            self.dispatcher.submit(self.parent_window.set_sensitive, True)
+            self.dispatcher.submit(self.blocking_window.destroy)
 
         self.blocking_window = Gtk.Window()
         self.blocking_window.set_transient_for(self.parent_window)
diff --git a/fungus/dispatcher.py b/fungus/dispatcher.py
new file mode 100644
index 0000000..fd922a7
--- /dev/null
+++ b/fungus/dispatcher.py
@@ -0,0 +1,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
diff --git a/fungus/main_window.py b/fungus/main_window.py
index 1f90e08..b17b119 100644
--- a/fungus/main_window.py
+++ b/fungus/main_window.py
@@ -36,6 +36,7 @@ from fungus.game_model import (
     Game,
     GameLibrary,
 )
+from fungus.dispatcher import GtkDispatcher
 from fungus.settings_dialog import SettingsDialog
 from fungus.utils import format_title, is_safe_prefix_path
 
@@ -55,6 +56,7 @@ class Main(Gtk.ApplicationWindow):
         self.current_prefix = None
         self.games = []
         self.flowbox_child = None
+        self.dispatcher = GtkDispatcher(lambda d: GLib.timeout_add(50, d.pump))
 
         self.last_click_time = 0
         self.last_clicked_item = None
@@ -155,6 +157,7 @@ class Main(Gtk.ApplicationWindow):
 
     def on_destroy(self, *args):
         """Handle the destroy signal by quitting the application."""
+        self.dispatcher.stop()
         self.get_application().quit()
 
     def load_config(self):
@@ -672,7 +675,7 @@ class Main(Gtk.ApplicationWindow):
 
     def on_button_settings_clicked(self, widget):
         """Open the Settings dialog."""
-        settings_dialog = SettingsDialog(self)
+        settings_dialog = SettingsDialog(self, self.dispatcher)
         settings_dialog.connect("response", self.on_settings_dialog_response, settings_dialog)
         settings_dialog.show()
 
@@ -680,7 +683,7 @@ class Main(Gtk.ApplicationWindow):
         """Open the Add Game dialog."""
         file_path = ""
         from fungus.add_game_dialog import AddGame
-        add_game_dialog = AddGame(self, file_path)
+        add_game_dialog = AddGame(self, file_path, dispatcher=self.dispatcher)
         add_game_dialog.connect("response", self.on_dialog_response, add_game_dialog)
         add_game_dialog.show()
 
@@ -694,7 +697,7 @@ class Main(Gtk.ApplicationWindow):
         game = selected_child.game
 
         if game:
-            edit_game_dialog = AddGame(self, file_path, is_editing=True)
+            edit_game_dialog = AddGame(self, file_path, is_editing=True, dispatcher=self.dispatcher)
             edit_game_dialog.connect("response", self.on_edit_dialog_response, edit_game_dialog, game)
 
             model_runner = edit_game_dialog.combobox_runner.get_model()
diff --git a/fungus/meson.build b/fungus/meson.build
index 8c86698..88ff23f 100644
--- a/fungus/meson.build
+++ b/fungus/meson.build
@@ -17,6 +17,7 @@ py.install_sources(
   'config_manager.py',
   'dark_theme.py',
   'dialogs.py',
+  'dispatcher.py',
   'game_launcher.py',
   'game_model.py',
   'logger.py',
diff --git a/fungus/settings_dialog.py b/fungus/settings_dialog.py
index 0f54654..9d37465 100644
--- a/fungus/settings_dialog.py
+++ b/fungus/settings_dialog.py
@@ -7,7 +7,7 @@ import threading
 
 import gi
 gi.require_version('Gtk', '3.0')
-from gi.repository import Gtk, Gdk, GLib, Pango # type: ignore
+from gi.repository import Gtk, Gdk, Pango # type: ignore
 
 from fungus.constants import (
     fungus_version,
@@ -18,6 +18,7 @@ from fungus.constants import (
 )
 from fungus.config_manager import ConfigManager
 from fungus.dialogs import show_warning_dialog
+from fungus.dispatcher import GtkDispatcher
 from fungus.utils import EntryTooltipMixin, pick_folder
 from fungus.umu_manager import (
     check_and_install_if_needed,
@@ -31,13 +32,14 @@ from fungus.umu_manager import (
 
 
 class SettingsDialog(EntryTooltipMixin, Gtk.Dialog):
-    def __init__(self, parent):
+    def __init__(self, parent, dispatcher: GtkDispatcher | None = None):
         """Build the settings UI, load config, and wire up all handlers."""
         # Initialize the Settings dialog
         super().__init__(title="Settings", transient_for=parent, modal=True)  # type: ignore[misc]
         self.set_resizable(False)
         self.set_icon_from_file(fungus_png)
         self.parent = parent
+        self.dispatcher = dispatcher or GtkDispatcher(lambda _: None)
         self.modified = False
 
         css_provider = Gtk.CssProvider()
@@ -552,12 +554,12 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog):
             process = subprocess.Popen([sys.executable, proton_manager])
             process.wait()
 
-            GLib.idle_add(self.set_sensitive, True)
-            GLib.idle_add(self.parent.set_sensitive, True)
-            GLib.idle_add(self.blocking_window.destroy)
+            self.dispatcher.submit(self.set_sensitive, True)
+            self.dispatcher.submit(self.parent.set_sensitive, True)
+            self.dispatcher.submit(self.blocking_window.destroy)
 
-            GLib.idle_add(self.combobox_runner.remove_all)
-            GLib.idle_add(self.populate_combobox_with_runners)
+            self.dispatcher.submit(self.combobox_runner.remove_all)
+            self.dispatcher.submit(self.populate_combobox_with_runners)
 
             def restore_selection():
                 if current_runner:
@@ -566,7 +568,7 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog):
                             self.combobox_runner.set_active(i)
                             break
 
-            GLib.idle_add(restore_selection)
+            self.dispatcher.submit(restore_selection)
 
         self.blocking_window = Gtk.Window()
         self.blocking_window.set_transient_for(self.parent)
@@ -588,7 +590,7 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog):
 
         def check_thread():
             latest = get_latest_umu_version()
-            GLib.idle_add(self._on_umu_version_checked, latest, widget)
+            self.dispatcher.submit(self._on_umu_version_checked, latest, widget)
 
         threading.Thread(target=check_thread, daemon=True).start()
 
@@ -625,12 +627,12 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog):
 
         def download_thread():
             def progress_cb(percent):
-                GLib.idle_add(self.progress_umu.set_fraction, percent / 100.0)
-                GLib.idle_add(self.progress_umu.set_text, f"{percent}%")
+                self.dispatcher.submit(self.progress_umu.set_fraction, percent / 100.0)
+                self.dispatcher.submit(self.progress_umu.set_text, f"{percent}%")
 
             success, status = check_and_install_if_needed(progress_callback=progress_cb)
-            GLib.idle_add(self.progress_umu.set_visible, False)
-            GLib.idle_add(self._on_umu_download_done, success, status)
+            self.dispatcher.submit(self.progress_umu.set_visible, False)
+            self.dispatcher.submit(self._on_umu_download_done, success, status)
 
         threading.Thread(target=download_thread, daemon=True).start()
 
@@ -708,15 +710,15 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog):
         def runtime_thread():
             runner = self.get_default_runner()
             if not runner:
-                GLib.idle_add(self._on_runtime_done, False, "No Proton selected")
+                self.dispatcher.submit(self._on_runtime_done, False, "No Proton selected")
                 return
 
             def update_progress(line):
-                GLib.idle_add(self.progress_steam_runtime.set_text, line.strip())
+                self.dispatcher.submit(self.progress_steam_runtime.set_text, line.strip())
 
             def progress_cb(percent):
-                GLib.idle_add(self.progress_steam_runtime.set_fraction, percent / 100.0)
-                GLib.idle_add(update_progress, "Updating…")
+                self.dispatcher.submit(self.progress_steam_runtime.set_fraction, percent / 100.0)
+                self.dispatcher.submit(update_progress, "Updating…")
 
             def on_success():
                 save_steamrt_last_check()
@@ -724,7 +726,7 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog):
             success, message = update_steam_runtime(
                 runner, progress_callback=progress_cb, on_success=on_success
             )
-            GLib.idle_add(self._on_runtime_done, success, message)
+            self.dispatcher.submit(self._on_runtime_done, success, message)
 
         threading.Thread(target=runtime_thread, daemon=True).start()