diff options
| author | fox <fox@fakecake.org> | 2026-07-04 13:44:24 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-07-04 13:44:24 +0300 |
| commit | be30b2a89a4ed2f38ffb4aa40bc7e0fbfd853a46 (patch) | |
| tree | c39952600121dae7f9541d679908cd16c8d6d6ef | |
| parent | 73da29ebcff63c58d28eba51f5029eaf1fa17492 (diff) | |
| parent | 4a64a67380ee91a0cc5b655afd3bc05b38d90e06 (diff) | |
| download | fungus-launcher-be30b2a89a4ed2f38ffb4aa40bc7e0fbfd853a46.tar.gz fungus-launcher-be30b2a89a4ed2f38ffb4aa40bc7e0fbfd853a46.tar.xz | |
Merge branch 'dev' into 'master'
decouple non-gtk logic from run_manager See merge request git/fungus-launcher!37
| -rw-r--r-- | fungus-proton-manager.py | 29 | ||||
| -rw-r--r-- | fungus/__init__.py | 4 | ||||
| -rw-r--r-- | fungus/add_game_dialog.py | 22 | ||||
| -rw-r--r-- | fungus/dispatcher.py | 70 | ||||
| -rw-r--r-- | fungus/game_launcher.py | 653 | ||||
| -rw-r--r-- | fungus/main_window.py | 9 | ||||
| -rw-r--r-- | fungus/meson.build | 2 | ||||
| -rw-r--r-- | fungus/proton_manager.py | 50 | ||||
| -rw-r--r-- | fungus/run_manager.py | 972 | ||||
| -rw-r--r-- | fungus/settings_dialog.py | 38 | ||||
| -rw-r--r-- | tests/test_run_manager.py | 10 |
11 files changed, 1017 insertions, 842 deletions
diff --git a/fungus-proton-manager.py b/fungus-proton-manager.py index 8fb3b8f..1c57aa6 100644 --- a/fungus-proton-manager.py +++ b/fungus-proton-manager.py @@ -33,12 +33,12 @@ def main() -> None: win.connect("destroy", Gtk.main_quit) Gtk.main() from fungus.proton_manager import ( + DEFAULT_UPSTREAM_URLS, RATE_LIMITED_MSG, - _cache_key, - _fetch_with_cache, + clear_cache, download_and_extract, + fetch_all_releases, get_arch_asset, - get_cache_dir, get_installed_path, remove_path, ) @@ -168,17 +168,7 @@ class ProtonDownloader(Gtk.Dialog): def _clear_cache(self): """Remove cached release data for both upstreams.""" - urls = [ - "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases", - "https://api.github.com/repos/Etaash-mathamsetty/Proton/releases", - ] - for url in urls: - cache_path = get_cache_dir() / _cache_key(url) - try: - cache_path.unlink(missing_ok=True) - log.debug("Cache removed: %s", url) - except OSError as exc: - log.warning("Cache removal failed: %s", exc) + clear_cache() def _on_refresh_clicked(self, widget): """Clear cache and re-fetch releases.""" @@ -216,15 +206,12 @@ class ProtonDownloader(Gtk.Dialog): # ── Background fetch ────────────────────────────────────────────── def _fetch_releases_async(self): - """Fetch releases from GitHub in a background thread, then update UI.""" + """Fetch releases from all upstreams in a background thread, then update UI.""" log.debug("Starting async fetch...") try: - ge_releases = _fetch_with_cache( - "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases", - ) - em_releases = _fetch_with_cache( - "https://api.github.com/repos/Etaash-mathamsetty/Proton/releases", - ) + all_releases = fetch_all_releases() + ge_releases = all_releases.get(DEFAULT_UPSTREAM_URLS[0], []) + em_releases = all_releases.get(DEFAULT_UPSTREAM_URLS[1], []) log.info("GE-Proton: %d, Proton-EM: %d", len(ge_releases), len(em_releases)) result = GLib.idle_add(self._render_releases, ge_releases, em_releases) diff --git a/fungus/__init__.py b/fungus/__init__.py index a603336..088687d 100644 --- a/fungus/__init__.py +++ b/fungus/__init__.py @@ -5,7 +5,9 @@ __all__ = [ "ConfigManager", "FungusApp", "Game", + "GameLauncher", "GameLibrary", + "LaunchHandle", "Main", "PathManager", "SandboxWarningDialog", @@ -33,7 +35,9 @@ def __getattr__(name): "FungusApp": "fungus.app", "ConfigManager": "fungus.config_manager", "Game": "fungus.game_model", + "GameLauncher": "fungus.game_launcher", "GameLibrary": "fungus.game_model", + "LaunchHandle": "fungus.game_launcher", "Main": "fungus.main_window", "PathManager": "fungus.path_manager", "SandboxWarningDialog": "fungus.dialogs", 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/game_launcher.py b/fungus/game_launcher.py new file mode 100644 index 0000000..3648244 --- /dev/null +++ b/fungus/game_launcher.py @@ -0,0 +1,653 @@ +#!/usr/bin/python3 +"""Core game-launch business logic (no Gtk/Glib/D-Bus). + +The GTK adapter lives in ``fungus.run_manager``. +""" + +from __future__ import annotations + +import os +import re +import signal +import subprocess +import sys +import time +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from threading import Thread, Event +from typing import ClassVar + +import psutil # type: ignore + +from fungus.constants import envar_dir, share_dir, umu_run +from fungus.game_model import Game, GameLibrary +from fungus.path_manager import PathManager +from fungus.config_manager import ConfigManager +from fungus.umu_manager import proton_to_steamrt_variant +from fungus.utils import has_proton_installed, is_executable_in_whitelist +from fungus.logger import get_logger + +log = get_logger(__name__) + + +# --------------------------------------------------------------------------- +# Return type for launch +# --------------------------------------------------------------------------- + + +@dataclass +class LaunchHandle: + """Handle for a launched process (for GLib watches).""" + + process: subprocess.Popen + pid: int + + +# --------------------------------------------------------------------------- +# GameLauncher — pure business logic +# --------------------------------------------------------------------------- + + +class GameLauncher: + """Game-launch business logic (no Gtk/Glib/D-Bus). + + The caller (GTK adapter) provides callbacks for UI interactions. + """ + + # Environment variables to pass through into the sandbox + SANDBOX_ENV_KEYS: tuple[str, ...] = ( + "DRI_PRIME", "__NV_PRIME_RENDER_OFFLOAD", + "__VK_LAYER_NV_OPTIMUS", "__GLX_VENDOR_LIBRARY_NAME", + "GAMEID", "PROTONFIXES_DISABLE", "WINEPREFIX", + ) + + # Predefined bwrap mount entries, grouped by type. + SYSTEM_RO_BINDS: ClassVar[list[tuple[str, ...]]] = [ + ("--ro-bind", "/usr", "/usr"), + ("--ro-bind", "/usr/lib", "/lib"), + ("--ro-bind", "/usr/lib64", "/lib64"), + ("--ro-bind", "/usr/bin", "/bin"), + ("--ro-bind", "/etc", "/etc"), + ("--ro-bind", "/sys", "/sys"), + ] + + SYSTEM_BINDS: ClassVar[list[tuple[str, ...]]] = [ + ("--bind", "/tmp", "/tmp"), + ("--proc", "/proc"), + ("--dev-bind", "/dev", "/dev"), + ] + + HOME_SHARED_BINDS: ClassVar[list[tuple[str, ...]]] = [ + ("--bind", str(Path.home() / ".local" / "share" / "umu"), + str(Path.home() / ".local" / "share" / "umu")), + ("--bind", str(Path.home() / ".local" / "share" / "Steam"), + str(Path.home() / ".local" / "share" / "Steam")), + ("--bind", str(Path.home() / ".local" / "share" / "fungus-launcher"), + str(Path.home() / ".local" / "share" / "fungus-launcher")), + ("--ro-bind", str(Path.home() / ".Xauthority"), + str(Path.home() / ".Xauthority")), + ] + + def __init__( + self, + game: Game, + igpu: bool = False, + *, + on_output_line: Callable[[str], None] | None = None, + on_error: Callable[[str], None] | None = None, + on_process_exit: Callable[[], None] | None = None, + on_sandbox_warning: Callable[[str, list[str]], None] | None = None, + on_steam_runtime_missing: Callable[[], None] | None = None, + on_proton_missing: Callable[[], None] | None = None, + on_proton_path_missing: Callable[[str], None] | None = None, + on_spawn_error: Callable[[str], None] | None = None, + on_splash_close: Callable[[], None] | None = None, + on_process_started: Callable[[], None] | None = None, + ): + self.game = game + self.igpu = igpu + self.process: subprocess.Popen | None = None + self.error_output: list[str] = [] + self._cleanup_event = Event() + self._on_output_line = on_output_line + self._on_error = on_error + self._on_process_exit = on_process_exit + self._on_sandbox_warning = on_sandbox_warning + self._on_steam_runtime_missing = on_steam_runtime_missing + self._on_proton_missing = on_proton_missing + self._on_proton_path_missing = on_proton_path_missing + self._on_spawn_error = on_spawn_error + self._on_splash_close = on_splash_close + self._on_process_started = on_process_started + self.load_config() + self._resolve_command_path() + signal.signal(signal.SIGUSR1, self.on_sigusr1) + signal.signal(signal.SIGTERM, self.on_sigterm) + self._watchdog_thread = Thread(target=self._watchdog_loop, daemon=True) + self._watchdog_thread.start() + + # ── Pure helpers ────────────────────────────────────────────────── + + @staticmethod + def _flatten_bwrap_args(entries: list[tuple[str, ...]]) -> list[str]: + """Flatten a list of (flag, *args) tuples into a bwrap argument list.""" + args: list[str] = [] + for entry in entries: + args.extend(entry) + return args + + # ── Environment / config ────────────────────────────────────────── + + def load_env_from_file(self, filename: str = envar_dir) -> dict[str, str]: + """Read key=value pairs from *filename* and merge them into os.environ. + + Returns a dict of the loaded variables. Silently returns an + empty dict when the file does not exist. + """ + env_from_file: dict[str, str] = {} + + try: + with open(filename, encoding="utf-8") as f: + for raw_line in f: + line = raw_line.strip() + if not line or "=" not in line: + continue + + key, value = line.split("=", 1) + key, value = key.strip(), value.strip() + + os.environ[key] = value + env_from_file[key] = value + + except FileNotFoundError: + pass + + return env_from_file + + def load_config(self) -> None: + """Load discrete-GPU and game-directories from config.""" + cfg = ConfigManager() + + self.discrete_gpu = cfg.get_bool("discrete-gpu", False) + self.game_directories = cfg.get("game-directories", "").strip() + + def _resolve_command_path(self) -> None: + """Resolve a simple command name (e.g. winecfg) to a full path. + + If *game.path* is already an absolute path that exists, it is left + untouched. Otherwise we look for it inside the Wine prefix's + ``drive_c/windows/system32`` and ``drive_c/windows`` directories, + trying both the bare name and ``<name>.exe``. + """ + path = self.game.path + if not path or (os.path.isabs(path) and os.path.isfile(path)): + return + + prefix = self.game.prefix + if not prefix: + return + + search_dirs = [ + os.path.join(prefix, "drive_c", "windows", "system32"), + os.path.join(prefix, "drive_c", "windows"), + ] + candidates = [path, f"{path}.exe"] + + for search_dir in search_dirs: + for name in candidates: + full = os.path.join(search_dir, name) + if os.path.isfile(full): + self.game.path = full + log.debug("cmd-resolve: %r -> %r", path, full) + return + + log.debug("cmd-resolve: no match for %r in prefix system dirs", path) + + # ── Sandbox command builder ─────────────────────────────────────── + + def build_bwrap_command( + self, + game: Game | None = None, + game_dirs: list[str] | None = None, + env_from_file: dict[str, str] | None = None, + ) -> tuple[list[str], dict[str, str], list[str]]: + """Construct the bwrap sandbox and inner command. + + Returns ``(bwrap_args, sandbox_env, inner_cmd)``. + """ + if game is None: + game = self.game + if game_dirs is None: + game_dirs = [] + if env_from_file is None: + env_from_file = {} + + bwrap_args: list[str] = [] + sandbox_env: dict[str, str] = {} + + # ── Sandbox namespaces ────────────────────────────────────── + bwrap_args.extend([ + "bwrap", + "--die-with-parent", + "--unshare-user", + "--unshare-cgroup", + "--unshare-pid", + "--unshare-uts", + "--unshare-net", + "--new-session", + ]) + + # ── Environment variables from env file (base layer) ──────── + if env_from_file: + sandbox_env.update(env_from_file) + + # ── Environment variables to pass through (override layer) ── + for key in self.SANDBOX_ENV_KEYS: + sandbox_env[key] = os.environ.get(key, "") + + # ── UMU-Launcher environment variables ────────────────────── + sandbox_env["GAMEID"] = game.protonfix or game.gameid or "" + sandbox_env["WINEPREFIX"] = game.prefix or "" + sandbox_env["PROTONPATH"] = game.runner + + for key, val in sandbox_env.items(): + bwrap_args.extend(["--setenv", key, val]) + + # ── Read-only system binds ────────────────────────────────── + bwrap_args.extend(self._flatten_bwrap_args(self.SYSTEM_RO_BINDS)) + + # ── GAME_DIRS bind mounts ─────────────────────────────────── + for dir_path in game_dirs: + bwrap_args.extend(["--bind", dir_path, dir_path]) + + # ── Writable / shared binds ───────────────────────────────── + xdg_runtime = os.environ.get("XDG_RUNTIME_DIR", "") + if xdg_runtime: + bwrap_args.extend(["--bind", xdg_runtime, xdg_runtime]) + bwrap_args.extend([ + "--bind", "/dev/null", + os.path.join(xdg_runtime, "ssh-agent.socket"), + ]) + + # ── System writable / special mounts ──────────────────────── + bwrap_args.extend(self._flatten_bwrap_args(self.SYSTEM_BINDS)) + + wineprefix = os.environ.get("WINEPREFIX", "") + if wineprefix: + bwrap_args.extend(["--bind", wineprefix, wineprefix]) + + # ── Home shared directories ───────────────────────────────── + bwrap_args.extend(self._flatten_bwrap_args(self.HOME_SHARED_BINDS)) + + # ── Config files (read-only) ──────────────────────────────── + config_dir = Path(PathManager.user_config("fungus-launcher")) + for cfg_file in ("games.json", "games.json.migrated", "config.ini"): + cfg_path = config_dir / cfg_file + if cfg_path.exists(): + bwrap_args.extend(["--ro-bind", str(cfg_path), str(cfg_path)]) + + # ── Inner command ─────────────────────────────────────────── + inner_cmd: list[str] = [umu_run, game.path] + if game.game_arguments: + inner_cmd.append(game.game_arguments) + + return bwrap_args, sandbox_env, inner_cmd + + # ── Validation ──────────────────────────────────────────────────── + + def _check_steam_runtime(self) -> bool: + """Check whether the correct Steam Runtime is available. + + Returns ``True`` if the runtime directory exists, ``False`` otherwise. + """ + proton_dir = self.game.runner or "" + steamrt_dir = os.path.expanduser( + f"~/.local/share/umu/{proton_to_steamrt_variant(proton_dir)}" + ) + return os.path.isdir(steamrt_dir) + + def _check_proton_path(self) -> bool: + """Check whether the selected Proton directory exists. + + Returns ``True`` if the directory exists, ``False`` otherwise. + """ + protonpath = self.game.runner + if not protonpath: + return True + protonpath_path = Path(share_dir) / "Steam/compatibilitytools.d" / protonpath + return protonpath_path.is_dir() + + def _check_whitelist(self, exec_path: str, valid_dirs: list[str]) -> bool: + """Check whether *exec_path* is within the sandbox whitelist. + + Returns ``True`` if the path is whitelisted or if no whitelist + is configured. + """ + return is_executable_in_whitelist(exec_path, valid_dirs) + + # ── Process lifecycle ───────────────────────────────────────────── + + def start(self) -> LaunchHandle: + """Validate environment, build bwrap command, and start the process. + + Returns a ``LaunchHandle`` for the GTK adapter to attach watches. + """ + # ── GPU / env vars ────────────────────────────────────────── + use_discrete = self.discrete_gpu and not self.igpu + if use_discrete: + os.environ["DRI_PRIME"] = "1" + os.environ["__NV_PRIME_RENDER_OFFLOAD"] = "1" + os.environ["__VK_LAYER_NV_OPTIMUS"] = "NVIDIA_only" + os.environ["__GLX_VENDOR_LIBRARY_NAME"] = "nvidia" + + # ── UMU-Launcher environment variables ────────────────────── + proton_dir = self.game.runner or "" + + os.environ["GAMEID"] = self.game.protonfix or self.game.gameid or "" + os.environ["WINEPREFIX"] = self.game.prefix or "" + if proton_dir: + os.environ["PROTONPATH"] = proton_dir + + self.start_time = time.time() + os.environ["UMU_RUNTIME_UPDATE"] = "0" + + if ( + "umu" not in os.environ.get("GAMEID", "") + and not (os.environ.get("GAMEID", "").isnumeric()) + ): + os.environ["PROTONFIXES_DISABLE"] = "1" + + # ── Validation ────────────────────────────────────────────── + if not self._check_steam_runtime(): + if self._on_splash_close: + self._on_splash_close() + if self._on_steam_runtime_missing: + self._on_steam_runtime_missing() + return LaunchHandle(subprocess.Popen([]), 0) # dummy + + if proton_dir and not self._check_proton_path(): + if not has_proton_installed(): + if self._on_splash_close: + self._on_splash_close() + if self._on_proton_missing: + self._on_proton_missing() + return LaunchHandle(subprocess.Popen([]), 0) # dummy + + if self._on_splash_close: + self._on_splash_close() + if self._on_proton_path_missing: + self._on_proton_path_missing(proton_dir) + return LaunchHandle(subprocess.Popen([]), 0) # dummy + + # ── Load env file ─────────────────────────────────────────── + self.env_from_file = self.load_env_from_file(envar_dir) + + # ── Build sandbox ─────────────────────────────────────────── + valid_dirs: list[str] = [] + if self.game_directories: + valid_dirs = [d.strip() for d in self.game_directories.split(",") if os.path.isdir(d.strip())] + + prefix = os.environ.get("WINEPREFIX", "") + if prefix and os.path.isdir(prefix): + valid_dirs.append(prefix) + + # Check whitelist + exec_path = self.game.path + log.debug("sandbox-check: exec_path=%r", exec_path) + if exec_path and valid_dirs and not self._check_whitelist(exec_path, valid_dirs): + if self._on_sandbox_warning: + self._on_sandbox_warning(exec_path, valid_dirs) + + bwrap_cmd, sandbox_env, inner_cmd = self.build_bwrap_command( + self.game, valid_dirs, self.env_from_file, + ) + + # ── Launch ────────────────────────────────────────────────── + run_env = os.environ.copy() + run_env.update(sandbox_env) + + full_cmd = bwrap_cmd + inner_cmd + + try: + self.process = subprocess.Popen( + full_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + bufsize=8192, + text=True, + env=run_env, + ) + except (FileNotFoundError, OSError) as exc: + error_msg = ( + f"Failed to start game runner: {exc}\n" + f"Command: {' '.join(full_cmd[:5])}..." + ) + if self._on_spawn_error: + self._on_spawn_error(error_msg) + return LaunchHandle(subprocess.Popen([]), 0) # dummy + + if self._on_process_started: + self._on_process_started() + + return LaunchHandle(self.process, self.process.pid) + + def stop(self) -> None: + """Gracefully terminate the running process tree.""" + if self.process and self.process.poll() is None: + self._kill_children() + + def cleanup(self) -> None: + """Kill children, save playtime, call on_process_exit.""" + # Stop the watchdog thread + self._cleanup_event.set() + + # Kill any remaining child processes (bwrap + descendants) + self._kill_children() + + # Save playtime + end_time = time.time() + runtime = int(end_time - getattr(self, "start_time", end_time)) + + game_id = os.environ.get("GAMEID") + + if game_id: + try: + library = GameLibrary() + game = library.load(game_id) + if game: + game.playtime = int(game.playtime or 0) + runtime + library.save(game) + except Exception: + pass + + if self._on_process_exit: + self._on_process_exit() + + # ── Watchdog ────────────────────────────────────────────────────── + + def _watchdog_loop(self) -> None: + """Background thread: kill orphaned bwrap processes.""" + while not self._cleanup_event.is_set(): + self._cleanup_event.wait(timeout=5.0) + if self._cleanup_event.is_set(): + break + + if self.process and self.process.poll() is None: + continue # game is still running + + if self.process and self.process.pid: + try: + bwrap_proc = psutil.Process(self.process.pid) + if bwrap_proc.is_running() and bwrap_proc.status() != psutil.STATUS_ZOMBIE: + log.warning("Killing orphaned bwrap (PID %d)", bwrap_proc.pid) + bwrap_proc.kill() + bwrap_proc.wait(timeout=2) + except Exception: + pass # already gone or other error + + # ── Process tree killing ────────────────────────────────────────── + + def _kill_children(self) -> None: + """Kill the bwrap process and all its descendants (SIGTERM → SIGKILL).""" + if self.process and self.process.poll() is None: + try: + parent = psutil.Process(self.process.pid) + children = parent.children(recursive=True) + + # Phase 1: SIGTERM + for child in children: + try: + child.send_signal(signal.SIGTERM) + except (psutil.NoSuchProcess, psutil.AccessDenied): + pass + try: + parent.send_signal(signal.SIGTERM) + except (psutil.NoSuchProcess, psutil.AccessDenied): + pass + + # Phase 2: SIGKILL stragglers + time.sleep(0.5) + still_alive = parent.children(recursive=True) + try: + still_alive.append(parent) + except psutil.NoSuchProcess: + pass + + for proc in still_alive: + try: + if proc.is_running() and proc.status() != psutil.STATUS_ZOMBIE: + proc.kill() + except (psutil.NoSuchProcess, psutil.AccessDenied): + pass + + try: + parent.wait(timeout=2) + except (psutil.TimeoutExpired, psutil.NoSuchProcess): + pass + + except psutil.NoSuchProcess: + pass + + # ── Output processing ───────────────────────────────────────────── + + def _on_io_line(self, raw: str, is_stderr: bool = False) -> None: + """Process a single output line (called from the GTK adapter via + GLib I/O watches). + + Parameters + ---------- + raw : str + The raw output line. + is_stderr : bool, default False + Whether this line came from stderr (affects error accumulation). + """ + if not raw: + return + + if isinstance(raw, bytes): + line = raw.decode("utf-8", errors="ignore") + else: + line = raw + + clean_line = self._remove_ansi(line).strip() + + if not clean_line: + return + + # Accumulate stderr for error reporting + if is_stderr: + self.error_output.append(clean_line) + + # Dispatch to callback + if self._on_output_line: + self._on_output_line(clean_line) + + # Check for game-running signals + if self._detect_game_running(clean_line): + if self._on_splash_close: + # The adapter handles scheduling via GLib.timeout_add_seconds + pass + + log.info("%s", line.rstrip()) + + @staticmethod + def _remove_ansi(text: str) -> str: + """Strip ANSI escape codes from *text*.""" + ansi_escape = re.compile( + r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])" + ) + return ansi_escape.sub("", text) + + @staticmethod + def _detect_game_running(clean_line: str) -> bool: + """Detect whether the game has started based on log output. + + Returns ``True`` if a game-running signal is detected. + """ + game_running_signals = [ + "fsync", "NTSync", + "Selected GPU", "Skipping fix execution", + "Executable a unix path", "status: 0", + "PosixPath", "SingleInstance", "mtree is OK", + ] + return any(signal in clean_line for signal in game_running_signals) + + # ── Signal handlers ─────────────────────────────────────────────── + + def on_sigusr1(self, signum: int, frame) -> None: + """Handle SIGUSR1: kill children, then terminate ourselves via SIGTERM.""" + self._kill_children() + os.kill(os.getpid(), signal.SIGTERM) + + def on_sigterm(self, signum: int, frame) -> None: + """Handle SIGTERM: perform full cleanup and exit.""" + self.cleanup() + + +# --------------------------------------------------------------------------- +# Unsandboxed winetricks runner +# --------------------------------------------------------------------------- + + +def run_winetricks(game: Game) -> None: + """Run winetricks GUI unsandboxed with the game's WINEPREFIX.""" + gameid = game.gameid + prefix = game.prefix or "" + runner = game.runner or "" + + run_env = os.environ.copy() + run_env["GAMEID"] = gameid + run_env["WINEPREFIX"] = prefix + run_env["PROTONPATH"] = runner + + winetricks_cmd = [umu_run, "winetricks", "--gui"] + + start_time = time.time() + proc = subprocess.run(winetricks_cmd, env=run_env, check=False) + runtime = int(time.time() - start_time) + + if gameid: + try: + library = GameLibrary() + g = library.load(gameid) + if g: + g.playtime = int(g.playtime or 0) + runtime + library.save(g) + except Exception: + pass + + sys.exit(proc.returncode) + + +# --------------------------------------------------------------------------- +# Convenience: load a game from the library +# --------------------------------------------------------------------------- + + +def load_game(gameid: str) -> Game | None: + """Load a ``Game`` object from the library by its gameid.""" + library = GameLibrary() + if library.exists(gameid): + return library.load(gameid) + return None 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 f6aece2..88ff23f 100644 --- a/fungus/meson.build +++ b/fungus/meson.build @@ -17,6 +17,8 @@ py.install_sources( 'config_manager.py', 'dark_theme.py', 'dialogs.py', + 'dispatcher.py', + 'game_launcher.py', 'game_model.py', 'logger.py', 'main_window.py', diff --git a/fungus/proton_manager.py b/fungus/proton_manager.py index 2d360d9..e726cfc 100644 --- a/fungus/proton_manager.py +++ b/fungus/proton_manager.py @@ -3,6 +3,7 @@ __all__ = [ "CACHE_TTL", + "DEFAULT_UPSTREAM_URLS", "MACHINE_ARCH", "RATE_LIMITED_MSG", "STEAM_COMPATIBILITY_PATH", @@ -10,7 +11,9 @@ __all__ = [ "RateLimited", "_cache_key", "_fetch_with_cache", + "clear_cache", "download_and_extract", + "fetch_all_releases", "fetch_releases", "get_arch_asset", "get_cache_dir", @@ -42,6 +45,11 @@ log = get_logger(__name__) STEAM_COMPATIBILITY_PATH = Path(PathManager.user_data("Steam/compatibilitytools.d")) MACHINE_ARCH = platform.machine().lower() # e.g. "x86_64", "aarch64" +DEFAULT_UPSTREAM_URLS = [ + "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases", + "https://api.github.com/repos/Etaash-mathamsetty/Proton/releases", +] + RATE_LIMITED_MSG = ( "GitHub API rate limit reached. Please try again later or use the refresh button." ) @@ -204,6 +212,48 @@ def fetch_releases(url): # --------------------------------------------------------------------------- +# Cache management +# --------------------------------------------------------------------------- + +def clear_cache(urls=None): + """Remove cached release data for given upstream URLs. + + Parameters + ---------- + urls : list[str], optional + URLs to clear cache for. Defaults to all known upstreams. + """ + if urls is None: + urls = DEFAULT_UPSTREAM_URLS + for url in urls: + cache_path = get_cache_dir() / _cache_key(url) + try: + cache_path.unlink(missing_ok=True) + log.debug("Cache removed: %s", url) + except OSError as exc: + log.warning("Cache removal failed: %s", exc) + + +# --------------------------------------------------------------------------- +# Fetch all upstreams +# --------------------------------------------------------------------------- + + +def fetch_all_releases(): + """Fetch releases from all known upstreams. + + Returns + ------- + dict[str, list[dict]] + Mapping from upstream URL to its list of release dicts. + """ + results = {} + for url in DEFAULT_UPSTREAM_URLS: + results[url] = _fetch_with_cache(url) + return results + + +# --------------------------------------------------------------------------- # Asset selection # --------------------------------------------------------------------------- diff --git a/fungus/run_manager.py b/fungus/run_manager.py index 00083bf..2424187 100644 --- a/fungus/run_manager.py +++ b/fungus/run_manager.py @@ -1,834 +1,236 @@ #!/usr/bin/python3 +"""GTK adapter for game launching. -import dbus # type: ignore -import gi # type: ignore -import os -import re -import signal -import subprocess -import psutil # type: ignore -import sys -import time -from pathlib import Path -from threading import Thread, Event -from typing import ClassVar +All Gtk/Glib/D-Bus coupling lives here. For pure business logic, see +``fungus.game_launcher.GameLauncher``. +""" -from fungus.logger import get_logger -from fungus.splash_window import SplashWindow +from __future__ import annotations -log = get_logger(__name__) +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.config_manager import ConfigManager -from fungus.constants import ( - envar_dir, - share_dir, - umu_run, -) -from fungus.game_model import Game, GameLibrary -from fungus.path_manager import PathManager -from fungus.utils import has_proton_installed, is_executable_in_whitelist -from fungus.dialogs import SandboxWarningDialog -from fungus.umu_manager import proton_to_steamrt_variant - -compatibility_dir = os.path.expanduser("~/.local/share/Steam/compatibilitytools.d") -os.makedirs(compatibility_dir, exist_ok=True) - - -class FungusRun: - # Environment variables to pass through into the sandbox - SANDBOX_ENV_KEYS: tuple[str, ...] = ( - "DRI_PRIME", "__NV_PRIME_RENDER_OFFLOAD", - "__VK_LAYER_NV_OPTIMUS", "__GLX_VENDOR_LIBRARY_NAME", - "GAMEID", "PROTONFIXES_DISABLE", "WINEPREFIX", - ) - - # Predefined bwrap mount entries, grouped by type. - # Each entry is a tuple: (flag, *args) — the number of args depends - # on the flag (e.g. "--bind" takes 2, "--proc" takes 1). - # To change a mount's access mode, simply swap the flag - # (e.g. "--bind" ↔ "--ro-bind"). - SYSTEM_RO_BINDS: ClassVar[list[tuple[str, ...]]] = [ - ("--ro-bind", "/usr", "/usr"), - ("--ro-bind", "/usr/lib", "/lib"), - ("--ro-bind", "/usr/lib64", "/lib64"), - ("--ro-bind", "/usr/bin", "/bin"), - ("--ro-bind", "/etc", "/etc"), - ("--ro-bind", "/sys", "/sys"), - ] - """Read-only system directories mapped into the sandbox.""" - - SYSTEM_BINDS: ClassVar[list[tuple[str, ...]]] = [ - ("--bind", "/tmp", "/tmp"), - ("--proc", "/proc"), - ("--dev-bind", "/dev", "/dev"), - ] - """Writable or special-purpose system mounts (tmp, proc, dev).""" - - HOME_SHARED_BINDS: ClassVar[list[tuple[str, ...]]] = [ - ("--bind", str(Path.home() / ".local" / "share" / "umu"), - str(Path.home() / ".local" / "share" / "umu")), - ("--bind", str(Path.home() / ".local" / "share" / "Steam"), - str(Path.home() / ".local" / "share" / "Steam")), - ("--bind", str(Path.home() / ".local" / "share" / "fungus-launcher"), - str(Path.home() / ".local" / "share" / "fungus-launcher")), - ("--ro-bind", str(Path.home() / ".Xauthority"), - str(Path.home() / ".Xauthority")), - ] - """User home directories shared with the sandbox (UMU runtime, Steam, launcher data, X auth).""" - - @staticmethod - def _flatten_bwrap_args(entries: list[tuple[str, ...]]) -> list[str]: - """Flatten a list of (flag, *args) tuples into a bwrap argument list. - - Parameters - ---------- - entries : list[tuple[str, ...]] - Each tuple is ``(flag, *args)`` where *flag* is a bwrap mount - directive. The number of positional args depends on the flag - (e.g. ``"--bind"`` takes 2, ``"--proc"`` takes 1). - - Returns - ------- - list[str] - A flat list suitable for ``bwrap_args.extend(...)``, e.g. - ``["--ro-bind", "/usr", "/usr", "--proc", "/proc", ...]``. - """ - args: list[str] = [] - for entry in entries: - args.extend(entry) - return args - - def __init__(self, game: Game, igpu: bool = False): - """Initialize with a Game and register signal handlers. - - Parameters - ---------- - game : Game - The game to launch. - igpu : bool - If True, force use of the integrated GPU regardless of the - global discrete-GPU setting. This is a per-invocation - override only. - """ - self.game = game - self.igpu = igpu - self.process = None - self.splash_window: SplashWindow | None = None - self.error_output: list[str] = [] - self._cleanup_event = Event() # signals cleanup thread to stop - - self.load_config() - self._resolve_command_path() - signal.signal(signal.SIGUSR1, self.on_sigusr1) - signal.signal(signal.SIGTERM, self.on_sigterm) - - def _resolve_command_path(self) -> None: - """Resolve a simple command name (e.g. winecfg) to a full path. - - If *game.path* is already an absolute path that exists, it is left - untouched. Otherwise we look for it inside the Wine prefix's - ``drive_c/windows/system32`` and ``drive_c/windows`` directories, - trying both the bare name and ``<name>.exe``. - """ - path = self.game.path - if not path or (os.path.isabs(path) and os.path.isfile(path)): - return - - prefix = self.game.prefix - if not prefix: - return - - search_dirs = [ - os.path.join(prefix, "drive_c", "windows", "system32"), - os.path.join(prefix, "drive_c", "windows"), - ] - candidates = [path, f"{path}.exe"] - - for search_dir in search_dirs: - for name in candidates: - full = os.path.join(search_dir, name) - if os.path.isfile(full): - self.game.path = full - log.debug("cmd-resolve: %r -> %r", path, full) - return - - # If nothing found, leave the path as-is — the sandbox check will - # handle it (either allow via prefix-system-path or warn). - log.debug("cmd-resolve: no match for %r in prefix system dirs", path) - - def start_process(self): - """Prepare the environment and launch the game process. - - Sets GPU/environment variables, validates the Steam Runtime - and Proton paths, then delegates to ``execute_final_command``. - - If ``--igpu`` was passed, the global discrete-GPU setting is - overridden and the integrated GPU is used instead. - """ - use_discrete = self.discrete_gpu and not self.igpu - if use_discrete: - os.environ["DRI_PRIME"] = "1" - os.environ["__NV_PRIME_RENDER_OFFLOAD"] = "1" - os.environ["__VK_LAYER_NV_OPTIMUS"] = "NVIDIA_only" - os.environ["__GLX_VENDOR_LIBRARY_NAME"] = "nvidia" - - # Resolve the effective runner once — used for runtime check and env vars - proton_dir = self.game.runner or "" - - # Set environment variables for UMU-Launcher - os.environ["GAMEID"] = self.game.protonfix or self.game.gameid or "" - os.environ["WINEPREFIX"] = self.game.prefix or "" - if proton_dir: - os.environ["PROTONPATH"] = proton_dir - - self.start_time = time.time() - - os.environ["UMU_RUNTIME_UPDATE"] = "0" - - if ( - "umu" not in os.environ.get("GAMEID", "") - and not (os.environ.get("GAMEID", "").isnumeric()) - ): - os.environ["PROTONFIXES_DISABLE"] = "1" - - # Validate that the correct Steam Runtime is available for this Proton - steamrt_dir = os.path.expanduser( - f"~/.local/share/umu/{proton_to_steamrt_variant(proton_dir)}" - ) - if not os.path.isdir(steamrt_dir): - self.close_splash_window() - self.show_error_dialog_steam_runtime() - - # Validate that the selected Proton directory exists - protonpath = proton_dir - if protonpath: - protonpath_path = Path(share_dir) / "Steam/compatibilitytools.d" / protonpath - if not protonpath_path.is_dir(): - self.close_splash_window() - if not has_proton_installed(): - self.show_error_dialog_no_proton() - else: - self.show_error_dialog(protonpath) - - self.env_from_file = self.load_env_from_file(envar_dir) - if self.env_from_file: - log.debug("=== GLOBAL ENVIRONMENT VARIABLES ===") - for key in sorted(self.env_from_file): - log.debug("%s=%s", key, self.env_from_file[key]) - - log.debug("=== ENVIRONMENT VARIABLES ===") - for key in sorted(self.SANDBOX_ENV_KEYS): - log.debug("%s=%s", key, os.environ.get(key, '')) - - log.debug("=== GAME INFORMATION ===") - log.debug("Game: %s", self.game.title or self.game.gameid) - log.debug("Path: %s", self.game.path) - log.debug("Runner: %s", self.game.runner) - log.debug("Prefix: %s", self.game.prefix) - - # Start the cleanup watchdog thread (monitors for orphaned bwrap) - self._watchdog_thread = Thread(target=self._watchdog_loop, daemon=True) - self._watchdog_thread.start() - - self.execute_final_command() - - def build_bwrap_command( - self, - game: Game, - game_dirs: list[str], - env_from_file: dict[str, str] | None = None, - ) -> tuple[list[str], dict[str, str], list[str]]: - """Construct the bwrap sandbox and inner command. - - Returns a tuple of ``(bwrap_args, sandbox_env, inner_cmd)`` where - *bwrap_args* is the full bwrap invocation, *sandbox_env* contains - the environment variables to pass inside the sandbox, and - *inner_cmd* is the command to execute (as a list of arguments). - """ - bwrap_args: list[str] = [] - sandbox_env: dict[str, str] = {} - - # ── Sandbox namespaces ────────────────────────────────────────── - # NOTE: We deliberately omit --as-pid-1. Without it, bwrap installs - # a proper reaper (PID 1) inside the namespace that reaps zombies - # and exits when the command exits. With --as-pid-1, bwrap becomes - # PID 1 itself and can linger after the inner command finishes. - bwrap_args.extend([ - "bwrap", - "--die-with-parent", - "--unshare-user", - "--unshare-cgroup", - "--unshare-pid", - "--unshare-uts", - "--unshare-net", - "--new-session", - ]) - - # ── Environment variables from env file (base layer) ──────────── - if env_from_file: - sandbox_env.update(env_from_file) - - # ── Environment variables to pass through (override layer) ────── - for key in self.SANDBOX_ENV_KEYS: - sandbox_env[key] = os.environ.get(key, "") - - # ── UMU-Launcher environment variables ────────────────────────── - sandbox_env["GAMEID"] = game.protonfix or game.gameid or "" - sandbox_env["WINEPREFIX"] = game.prefix or "" - sandbox_env["PROTONPATH"] = game.runner - - for key, val in sandbox_env.items(): - bwrap_args.extend(["--setenv", key, val]) - - # ── Read-only system binds ────────────────────────────────────── - bwrap_args.extend(self._flatten_bwrap_args(self.SYSTEM_RO_BINDS)) - - # ── GAME_DIRS bind mounts ─────────────────────────────────────── - for dir_path in game_dirs: - bwrap_args.extend(["--bind", dir_path, dir_path]) - - # ── Writable / shared binds ───────────────────────────────────── - xdg_runtime = os.environ.get("XDG_RUNTIME_DIR", "") - if xdg_runtime: - bwrap_args.extend(["--bind", xdg_runtime, xdg_runtime]) - # Mask the SSH agent socket so the sandbox cannot reach it - bwrap_args.extend([ - "--bind", "/dev/null", - os.path.join(xdg_runtime, "ssh-agent.socket"), - ]) - - # ── System writable / special mounts ──────────────────────────── - bwrap_args.extend(self._flatten_bwrap_args(self.SYSTEM_BINDS)) - - wineprefix = os.environ.get("WINEPREFIX", "") - if wineprefix: - bwrap_args.extend(["--bind", wineprefix, wineprefix]) - - # ── Home shared directories ───────────────────────────────────── - bwrap_args.extend(self._flatten_bwrap_args(self.HOME_SHARED_BINDS)) - - # ── Config files (read-only) ──────────────────────────────────── - config_dir = Path(PathManager.user_config("fungus-launcher")) - for cfg_file in ("games.json", "games.json.migrated", "config.ini"): - cfg_path = config_dir / cfg_file - if cfg_path.exists(): - bwrap_args.extend(["--ro-bind", str(cfg_path), str(cfg_path)]) - - # ── Inner command ─────────────────────────────────────────────── - inner_cmd: list[str] = [umu_run, game.path] - if game.game_arguments: - inner_cmd.append(game.game_arguments) - - return bwrap_args, sandbox_env, inner_cmd - - def execute_final_command(self): - """Build and execute the sandboxed bwrap command. - - Inhibits system sleep, validates the game executable against - the whitelist, constructs the bwrap sandbox, and launches it - with GLib I/O watches on stdout/stderr. - """ - # Inhibit sleep while a game is running - try: - bus = dbus.SessionBus() - portal = bus.get_object( - "org.freedesktop.portal.Desktop", - "/org/freedesktop/portal/desktop", - ) - iface = dbus.Interface(portal, "org.freedesktop.portal.Inhibit") - iface.Inhibit("", 8, {"reason": "Game is running"}) - except Exception: - pass - # Build GAME_DIRS from config, append the current prefix - valid_dirs: list[str] = [] - if self.game_directories: - valid_dirs = [d.strip() for d in self.game_directories.split(",") if os.path.isdir(d.strip())] - - prefix = os.environ.get("WINEPREFIX", "") - if prefix and os.path.isdir(prefix): - valid_dirs.append(prefix) - - # Check whether the game executable's directory is within the whitelist - exec_path = self.game.path - log.debug("sandbox-check: exec_path=%r", exec_path) - if exec_path and valid_dirs and not is_executable_in_whitelist(exec_path, valid_dirs): - GLib.idle_add( - self._show_sandbox_warning, exec_path, valid_dirs - ) - - bwrap_cmd, sandbox_env, inner_cmd = self.build_bwrap_command( - self.game, valid_dirs, self.env_from_file, - ) +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.debug("=== FINAL BWRAP COMMAND ===") - log.debug("%s", ' '.join(bwrap_cmd)) - log.debug("=== INNER COMMAND ===") - log.debug("%s", ' '.join(inner_cmd)) - - log.debug("=== FINAL SANDBOX ENV ===") - for key in sorted(sandbox_env): - log.debug("%s=%s", key, os.environ.get(key, '')) - - # Merge sandbox env into a copy of the current environment - run_env = os.environ.copy() - run_env.update(sandbox_env) - - full_cmd = bwrap_cmd + inner_cmd - - try: - self.process = subprocess.Popen( - full_cmd, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - bufsize=8192, - text=True, - env=run_env, - ) - except (FileNotFoundError, OSError) as exc: - error_msg = ( - f"Failed to start game runner: {exc}\n" - f"Command: {' '.join(full_cmd[:5])}..." - ) - GLib.idle_add(self._show_spawn_error, error_msg) - return - - self.stdout_watch_id = GLib.io_add_watch( - self.process.stdout, - GLib.PRIORITY_LOW, - GLib.IO_IN, - self.on_output, - ) - self.stderr_watch_id = GLib.io_add_watch( - self.process.stderr, - GLib.PRIORITY_LOW, - GLib.IO_IN, - self.on_output, - ) +log = get_logger(__name__) - GLib.child_watch_add( - GLib.PRIORITY_DEFAULT, - self.process.pid, - self.on_process_exit, - ) +# Backward-compatibility alias for tests that import FungusRun directly +FungusRun = GameLauncher +# --------------------------------------------------------------------------- +# GTK-specific error dialog helpers +# --------------------------------------------------------------------------- - def show_error_dialog_steam_runtime(self): - """Show error when UMU Steam Runtime is not available.""" - from fungus.dialogs import create_error_dialog - 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_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_spawn_error(self, error_msg: str) -> None: - """Show an error dialog when the process could not be spawned.""" - if self.splash_window: - self.splash_window.destroy() - self.splash_window = None - from fungus.dialogs import create_error_dialog +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, + ) - 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, - ) - def _show_process_error(self, exit_code: int) -> bool: - """Show process error in the splash window with accumulated output.""" - if not self.splash_window: - self.show_splash_window() +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, + ) - if self.splash_window: - self.splash_window.show_error(exit_code, self.error_output) - return False +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, + ) - def show_error_dialog_no_proton(self): - """Show error when no proton versions are installed at all.""" - from fungus.dialogs import create_error_dialog - create_error_dialog( - title="Fungus Launcher", - primary="No Proton version is installed.", - secondary="Please install one via Settings → Proton Manager.", - quit_app=True, - ) +# --------------------------------------------------------------------------- +# handle_command — main entry point +# --------------------------------------------------------------------------- - def show_error_dialog(self, protonpath=None, network_error=False): - """Show a generic error dialog for missing Proton or network errors.""" - from fungus.dialogs import create_error_dialog - - if network_error: - primary = "Internet connection error." - secondary = None - else: - primary = f"{protonpath} was not found." - secondary = "Please install it or use another Proton version." - - create_error_dialog( - title="Fungus Launcher", - primary=primary, - secondary=secondary, - quit_app=True, - ) - def load_env_from_file(self, filename=envar_dir): - """Read key=value pairs from *filename* and merge them into os.environ. +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 - Returns a dict of the loaded variables. Silently returns an - empty dict when the file does not exist. - """ - env_from_file = {} + if cmd_override: + game.path = cmd_override + game.game_arguments = "" - try: - with open(filename, encoding="utf-8") as f: - for raw_line in f: - line = raw_line.strip() - if not line or "=" not in line: - continue + # ── Show splash window ──────────────────────────────────────── + title = game.title or game.gameid or "" - key, value = line.split("=", 1) - key, value = key.strip(), value.strip() + # ── Build callbacks (forward refs resolved below) ───────────── + splash_container: list[SplashWindow | None] = [None] # mutable container for forward reference - os.environ[key] = value - env_from_file[key] = value + def on_output_line(line: str) -> None: + s = splash_container[0] + if s is not None: + GLib.idle_add(s.append_output, line) - except FileNotFoundError: - pass + def on_error(msg: str) -> None: + log.error("GameLauncher error: %s", msg) - return env_from_file - - def load_config(self): - """Load discrete-GPU and game-directories from config.""" - cfg = ConfigManager() - - self.discrete_gpu = cfg.get_bool("discrete-gpu", False) - self.game_directories = cfg.get("game-directories", "").strip() - - def _watchdog_loop(self): - """Background thread that monitors our specific bwrap process. - - Runs every 5 seconds. If the launcher subprocess has exited but - our bwrap process (tracked by PID) is still alive, it is killed. - Only targets our own bwrap — never indiscriminately kills bwrap. - """ - while not self._cleanup_event.is_set(): - self._cleanup_event.wait(timeout=5.0) - if self._cleanup_event.is_set(): - break - - # Check if our main process is still alive - if self.process and self.process.poll() is None: - continue # game is still running, no action needed - - # Process has exited — check if our specific bwrap is still alive - if self.process and self.process.pid: - try: - bwrap_proc = psutil.Process(self.process.pid) - if bwrap_proc.is_running() and bwrap_proc.status() != psutil.STATUS_ZOMBIE: - log.warning("Killing orphaned bwrap (PID %d)", bwrap_proc.pid) - bwrap_proc.kill() - bwrap_proc.wait(timeout=2) - except psutil.NoSuchProcess: - pass # already gone - except psutil.TimeoutExpired: - pass # give up, it'll be cleaned up by the system - - def _show_sandbox_warning(self, exec_path: str, valid_dirs: list[str]) -> bool: - """Show the sandbox whitelist warning dialog.""" - SandboxWarningDialog(exec_path, valid_dirs) - return False # do not repeat - - def _kill_children(self): - """Kill the bwrap process and all its descendants. - - Uses a two-phase approach: SIGTERM first, then SIGKILL after - a brief timeout, to give the process tree a chance to clean up. - """ - if self.process and self.process.poll() is None: - try: - parent = psutil.Process(self.process.pid) - children = parent.children(recursive=True) - - # Phase 1: SIGTERM to all children, then parent - for child in children: - try: - child.send_signal(signal.SIGTERM) - except (psutil.NoSuchProcess, psutil.AccessDenied): - pass - try: - parent.send_signal(signal.SIGTERM) - except (psutil.NoSuchProcess, psutil.AccessDenied): - pass - - # Phase 2: Wait briefly, then SIGKILL stragglers - time.sleep(0.5) - still_alive = parent.children(recursive=True) - try: - still_alive.append(parent) - except psutil.NoSuchProcess: - pass - - for proc in still_alive: - try: - if proc.is_running() and proc.status() != psutil.STATUS_ZOMBIE: - proc.kill() - except (psutil.NoSuchProcess, psutil.AccessDenied): - pass - - # Final wait to let zombies be reaped - try: - parent.wait(timeout=2) - except (psutil.TimeoutExpired, psutil.NoSuchProcess): - pass - - except psutil.NoSuchProcess: - pass - - def show_splash_window(self) -> None: - """Create and display the splash window with window title and output view.""" - title = self.game.title or self.game.gameid or "" - - def on_close() -> None: - Gtk.main_quit() - sys.exit(0) - - self.splash_window = SplashWindow(title, on_close) - self.splash_window.show() - - def _on_splash_close(self, _widget): - """Close the splash window and quit the application.""" - if self.splash_window: - self.splash_window.close() - self.splash_window = None - - def _append_output(self, line: str) -> None: - """Delegate to the splash window.""" - if self.splash_window: - self.splash_window.append_output(line) - - def on_output(self, source, condition): - """GLib I/O watch callback — reads lines from stdout/stderr. - - Strips ANSI escape codes, accumulates stderr for error - reporting, and dispatches each line to the splash window - and output heuristics. - """ - def remove_ansi_escape(text): - ansi_escape = re.compile( - r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])" - ) - return ansi_escape.sub("", text) - - raw = source.readline() - - if raw: - if isinstance(raw, bytes): - line = raw.decode("utf-8", errors="ignore") - else: - line = raw - - clean_line = remove_ansi_escape(line).strip() - - # Accumulate stderr lines for error reporting on non-zero exit - if self.process and source is self.process.stderr and clean_line: - self.error_output.append(clean_line) - - # Show output in splash window (io_add_watch already runs in main thread) - self._show_output_in_splash(clean_line) - - self.check_game_output(clean_line) - - log.info("%s", line.rstrip()) - - return True - - def _show_output_in_splash(self, line: str) -> None: - """Delegate to the splash window.""" - if self.splash_window: - self.splash_window.append_output(line) - - def check_game_output(self, clean_line): - """Detect when the game has started and close the splash window. - - Heuristic: certain log lines indicate the game runtime is active - and we can safely dismiss the splash. - """ - game_running_signals = [ - "fsync", "NTSync", - "Selected GPU", "Skipping fix execution", - "Executable a unix path", "status: 0", - "PosixPath", "SingleInstance", "mtree is OK", - ] - if any(signal in clean_line for signal in game_running_signals): - GLib.timeout_add_seconds(0, self.close_splash_window) - - def close_splash_window(self): - """Hide the splash window.""" - if self.splash_window: - self.splash_window.hide() - - def on_sigusr1(self, signum, frame): - """Handle SIGUSR1: kill children, then terminate ourselves via SIGTERM.""" - self._kill_children() - os.kill(os.getpid(), signal.SIGTERM) - - def on_sigterm(self, signum, frame): - """Handle SIGTERM: perform full cleanup and exit.""" - self.do_process_exit() - - def on_process_exit(self, pid, condition): - """GLib child watch callback — fires when bwrap exits. - - Checks the exit status and shows an error dialog if the - process terminated with a non-zero exit code. - """ - if os.WIFEXITED(condition): - exit_code = os.WEXITSTATUS(condition) - if exit_code != 0: - GLib.idle_add( - self._show_process_error, exit_code - ) - return False # skip normal cleanup - - self.do_process_exit() - return False - - def do_process_exit(self): - """Shared cleanup: kill children, save playtime, close UI, quit.""" - # Stop the watchdog thread - self._cleanup_event.set() - - # Kill any remaining child processes (bwrap + descendants) - self._kill_children() - - # Save playtime - end_time = time.time() - runtime = int(end_time - getattr(self, "start_time", end_time)) - - game_id = os.environ.get("GAMEID") - - if game_id: - try: - library = GameLibrary() - game = library.load(game_id) - if game: - game.playtime = int(game.playtime or 0) + runtime - library.save(game) - except Exception: - pass - - GLib.idle_add(self.close_splash_window) + def on_process_exit() -> None: + s = splash_container[0] + if s is not None: + GLib.idle_add(s.close) 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: + 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_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, + ) -def run_winetricks(game: Game) -> None: - """Run winetricks GUI unsandboxed with the game's WINEPREFIX. - - This is a simplified execution path that skips bwrap entirely. - Environment variables (GAMEID, WINEPREFIX, PROTONPATH) are set - from the game entry, and ``umu-run winetricks`` is invoked - directly (umu-run provides the Steam Runtime). - """ - gameid = game.gameid - prefix = game.prefix or "" - runner = game.runner or "" - - # ── Prepare environment ────────────────────────────────────────── - run_env = os.environ.copy() - run_env["GAMEID"] = gameid - run_env["WINEPREFIX"] = prefix - run_env["PROTONPATH"] = runner - - # ── Build command: umu-run winetricks ──────────────────────────── - winetricks_cmd = [umu_run, "winetricks", "--gui"] - - log.debug("=== WINETRICKS (unsandboxed) ===") - log.debug("GAMEID=%s", gameid) - log.debug("WINEPREFIX=%s", prefix) - if runner: - log.debug("PROTONPATH=%s", runner) - log.debug("Command: %s", ' '.join(winetricks_cmd)) - - # ── Launch and wait ────────────────────────────────────────────── - start_time = time.time() - proc = subprocess.run(winetricks_cmd, env=run_env, check=False) - runtime = int(time.time() - start_time) - - # ── Save playtime ──────────────────────────────────────────────── - if gameid: - try: - library = GameLibrary() - g = library.load(gameid) - if g: - g.playtime = int(g.playtime or 0) + runtime - library.save(g) - except Exception: - pass - - sys.exit(proc.returncode) - - -def handle_command(game: Game, cmd_override: str | None = None, igpu: bool = False): - """Entry point: launch winetricks or the game via FungusRun. - - Parameters - ---------- - game : Game - The game to launch. - cmd_override : str, optional - If given, override the game executable path. - igpu : bool - If True, force integrated GPU for this invocation. - """ - # ── Special unsandboxed winetricks path ────────────────────────── - if cmd_override == "winetricks": - run_winetricks(game) - return - - if cmd_override: - game.path = cmd_override - game.game_arguments = "" + handle: LaunchHandle = launcher.start() + + # If start() returned a dummy handle, validation failed — the + # appropriate error dialog is already shown via callbacks. + if handle.process and handle.process.stdout 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), + ) - run = FungusRun(game, igpu=igpu) - run.show_splash_window() + GLib.child_watch_add( + GLib.PRIORITY_DEFAULT, + handle.pid, + _on_child_exit, + ) + # ── Start process in a thread and enter the event loop ───────── def run_process(): - run.start_process() + # Wait for the process to exit (the watchdog handles orphans) + if handle.process: + handle.process.wait() - process_thread = Thread(target=run_process) + process_thread = Thread(target=run_process, daemon=True) + process_thread.start() - def start_thread(): - process_thread.start() - - GLib.idle_add(start_thread) Gtk.main() process_thread.join() sys.exit(0) -def load_game(gameid): - """Load a ``Game`` object from the library by its gameid.""" - library = GameLibrary() - if library.exists(gameid): - return library.load(gameid) - return None +def _on_child_exit(pid: int, condition: int) -> bool: + """GLib child watch callback — fires when the bwrap process exits.""" + if os.WIFEXITED(condition): + exit_code = os.WEXITSTATUS(condition) + if exit_code != 0: + # The error is handled by the splash window's show_error + # which is triggered via the on_process_exit callback + pass + + # Cleanup is handled by on_process_exit callback + return False + +# --------------------------------------------------------------------------- +# Convenience: load a game from the library +# --------------------------------------------------------------------------- +def load_game(gameid: str): + return _load_game(gameid) 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() diff --git a/tests/test_run_manager.py b/tests/test_run_manager.py index 99d4b5b..f324b06 100644 --- a/tests/test_run_manager.py +++ b/tests/test_run_manager.py @@ -80,7 +80,7 @@ def fungus_run(tmp_path, game, mock_gtk): mock_cfg.get_bool.return_value = False mock_cfg.get.return_value = "" - with patch("fungus.run_manager.ConfigManager", return_value=mock_cfg): + with patch("fungus.game_launcher.ConfigManager", return_value=mock_cfg): run = FungusRun(game, igpu=False) # Replace the game object with one that has an absolute path so @@ -185,7 +185,7 @@ class TestResolveCommandPath: mock_cfg.get_bool.return_value = False mock_cfg.get.return_value = "" - with patch("fungus.run_manager.ConfigManager", return_value=mock_cfg): + with patch("fungus.game_launcher.ConfigManager", return_value=mock_cfg): run = FungusRun(game) run._resolve_command_path() @@ -214,7 +214,7 @@ class TestResolveCommandPath: mock_cfg.get_bool.return_value = False mock_cfg.get.return_value = "" - with patch("fungus.run_manager.ConfigManager", return_value=mock_cfg): + with patch("fungus.game_launcher.ConfigManager", return_value=mock_cfg): run = FungusRun(game) run._resolve_command_path() @@ -405,7 +405,7 @@ class TestLoadConfig: mock_cfg.get_bool.return_value = True mock_cfg.get.return_value = "" - with patch("fungus.run_manager.ConfigManager", return_value=mock_cfg): + with patch("fungus.game_launcher.ConfigManager", return_value=mock_cfg): run = FungusRun(game) assert run.discrete_gpu is True @@ -418,7 +418,7 @@ class TestLoadConfig: mock_cfg.get_bool.return_value = False mock_cfg.get.return_value = "/home/user/Games" - with patch("fungus.run_manager.ConfigManager", return_value=mock_cfg): + with patch("fungus.game_launcher.ConfigManager", return_value=mock_cfg): run = FungusRun(game) assert run.game_directories == "/home/user/Games" |
