#!/usr/bin/python3 """GTK adapter for game launching. All Gtk/Glib/D-Bus coupling lives here. For pure business logic, see ``fungus.game_launcher.GameLauncher``. """ from __future__ import annotations import os import sys from threading import Thread import gi # type: ignore gi.require_version("Gtk", "3.0") from gi.repository import Gtk, GLib # type: ignore from fungus.game_launcher import ( GameLauncher, LaunchHandle, load_game as _load_game, run_winetricks as _run_winetricks, ) from fungus.splash_window import SplashWindow from fungus.dialogs import ( SandboxWarningDialog, create_error_dialog, ) from fungus.logger import get_logger log = get_logger(__name__) # Backward-compatibility alias for tests that import FungusRun directly FungusRun = GameLauncher # --------------------------------------------------------------------------- # GTK-specific error dialog helpers # --------------------------------------------------------------------------- def _show_error_dialog_steam_runtime() -> None: create_error_dialog( title="Fungus Launcher", primary="The UMU Steam Runtime directory was not found.", secondary=( "Games using UMU-Launcher will not be able to run. " "Please open Settings → UMU-Launcher and update the runtime." ), quit_app=True, ) def _show_error_dialog_no_proton() -> None: create_error_dialog( title="Fungus Launcher", primary="No Proton version is installed.", secondary="Please install one via Settings → Proton Manager.", quit_app=True, ) def _show_error_dialog_proton_path(protonpath: str) -> None: create_error_dialog( title="Fungus Launcher", primary=f"{protonpath} was not found.", secondary="Please install it or use another Proton version.", quit_app=True, ) def _show_spawn_error(error_msg: str) -> None: create_error_dialog( title="Fungus Launcher", primary="The game runner could not be started.", secondary="Check the terminal output for details.", error_text=error_msg, quit_app=True, ) # --------------------------------------------------------------------------- # handle_command — main entry point # --------------------------------------------------------------------------- def handle_command( game, cmd_override: str | None = None, igpu: bool = False, ) -> None: """Entry point: launch winetricks or the game.""" # ── Unsandboxed winetricks path ─────────────────────────────── if cmd_override == "winetricks": _run_winetricks(game) return if cmd_override: game.path = cmd_override game.game_arguments = "" # ── Show splash window ──────────────────────────────────────── title = game.title or game.gameid or "" # ── Build callbacks (forward refs resolved below) ───────────── splash_container: list[SplashWindow | None] = [None] # mutable container for forward reference def on_output_line(line: str, is_stderr: bool) -> None: color = "#e06c75" if is_stderr else None # soft red for stderr s = splash_container[0] if s is not None: GLib.idle_add( lambda: s.append_output(f"{line}", color=color) ) def on_error(msg: str) -> None: log.error("GameLauncher error: %s", msg) def on_process_exit() -> None: log.debug("on_process_exit: destroying splash and quitting GTK") s = splash_container[0] if s is not None: GLib.idle_add(s._destroy) GLib.idle_add(Gtk.main_quit) def on_process_fail(exit_code: int) -> None: """Handle a non-zero process exit — show error in the splash.""" log.debug("on_process_fail: exit_code=%d", exit_code) s = splash_container[0] if s is not None: GLib.idle_add(s.show_error, exit_code) else: log.warning("Splash unavailable for error display (exit_code=%d)", exit_code) # Splash was already destroyed — quit GTK so the app doesn't hang. GLib.idle_add(Gtk.main_quit) def on_sandbox_warning(exec_path: str, valid_dirs: list[str]) -> None: GLib.idle_add(SandboxWarningDialog, exec_path, valid_dirs) def on_steam_runtime_missing() -> None: GLib.idle_add(_show_error_dialog_steam_runtime) def on_proton_missing() -> None: GLib.idle_add(_show_error_dialog_no_proton) def on_proton_path_missing(protonpath: str) -> None: GLib.idle_add(_show_error_dialog_proton_path, protonpath) def on_spawn_error(error_msg: str) -> None: GLib.idle_add(_show_spawn_error, error_msg) def _on_splash_close() -> None: """Schedule splash window close on the GTK main thread. Called from the I/O watch thread when a game-running signal (e.g. "fsync") is detected in the output. """ log.debug("_on_splash_close: scheduling splash close") s = splash_container[0] if s is not None and hasattr(s, 'close'): GLib.idle_add(s.close) def on_process_started() -> None: pass # splash is already shown # ── Create splash and wire it ───────────────────────────────── splash = SplashWindow(title, _on_splash_close) splash.show() splash_container[0] = splash # ── Create launcher and start ───────────────────────────────── launcher = GameLauncher( game, igpu=igpu, on_output_line=on_output_line, on_error=on_error, on_process_exit=on_process_exit, on_process_fail=on_process_fail, on_sandbox_warning=on_sandbox_warning, on_steam_runtime_missing=on_steam_runtime_missing, on_proton_missing=on_proton_missing, on_proton_path_missing=on_proton_path_missing, on_spawn_error=on_spawn_error, on_splash_close=_on_splash_close, on_process_started=on_process_started, ) handle: LaunchHandle = launcher.start() # If start() returned a handle with process=None, validation failed — # the appropriate error dialog is already shown via callbacks. if handle.process is not None: # ── Attach GLib I/O watches ─────────────────────────────── def make_io_handler(is_stderr: bool): """Create an I/O line handler for the given stream.""" def io_handler(source, condition): raw = source.readline() if raw: launcher._on_io_line(raw, is_stderr=is_stderr) return True return io_handler GLib.io_add_watch( handle.process.stdout, GLib.PRIORITY_LOW, GLib.IO_IN, make_io_handler(False), ) GLib.io_add_watch( handle.process.stderr, GLib.PRIORITY_LOW, GLib.IO_IN, make_io_handler(True), ) def _on_child_exit(pid: int, condition: int) -> bool: """GLib child watch callback — fires when the bwrap process exits. Extracts the exit code from *condition* and dispatches cleanup appropriately: success (0) → ``on_process_exit``, failure (non-zero) → ``on_process_fail``. """ if os.WIFEXITED(condition): exit_code = os.WEXITSTATUS(condition) elif os.WIFSIGNALED(condition): exit_code = -os.WTERMSIG(condition) else: exit_code = condition log.debug( "_on_child_exit: pid=%d condition=%d → exit_code=%d", pid, condition, exit_code, ) launcher.cleanup(exit_code) return False GLib.child_watch_add( GLib.PRIORITY_DEFAULT, handle.pid, _on_child_exit, ) # ── Start process in a thread and enter the event loop ───────── # The child watch handles process lifecycle entirely. The thread # is kept as a no-op placeholder; it must NOT call wait() because # that would reap the child and prevent GLib's child watch from # firing (glib docs: waitid ECHILD when child already reaped). def run_process(): pass process_thread = Thread(target=run_process, daemon=True) process_thread.start() Gtk.main() process_thread.join() sys.exit(0) # --------------------------------------------------------------------------- # Convenience: load a game from the library # --------------------------------------------------------------------------- def load_game(gameid: str): return _load_game(gameid)