#!/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 logging 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 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`` is ``None`` when launch was skipped due to validation failure (missing Steam Runtime, missing Proton, spawn error). In those cases the GTK adapter has already been notified via callbacks. """ process: subprocess.Popen | None 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", "WINEDLLOVERRIDES", "UMU_LOG", "PROTON_LOG" ) # 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, bool], 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_process_fail: Callable[[int], 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._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_process_fail = on_process_fail 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() # ── Sleep inhibition ──────────────────────────────────────────── def _build_inhibit_prefix(self, gameid: str) -> list[str]: """Return [systemd-inhibit, …] if available, else [].""" systemd_inhibit = PathManager.find_binary("systemd-inhibit") if not systemd_inhibit: log.debug("systemd-inhibit not found; sleep inhibition unavailable") return [] return [ systemd_inhibit, "--what=sleep:idle", f"--why={gameid} is running", "--mode=block", ] # ── 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_global_env(self) -> dict[str, str]: """Read global environment variables from config.ini. Returns a dict suitable for merging into sandbox_env. """ env: dict[str, str] = {} cfg = ConfigManager() for raw_line in cfg.get_envars(): line = raw_line.strip() if not line or "=" not in line: continue key, value = line.split("=", 1) env[key.strip()] = value.strip() return env 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 ``.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_per_game_env(self) -> dict[str, str]: """Parse the game's environment list into a dict. Returns an empty dict when the game has no per-game env vars. """ env: dict[str, str] = {} for raw_line in self.game.environment or []: line = raw_line.strip() if not line or "=" not in line: continue key, value = line.split("=", 1) env[key.strip()] = value.strip() return env def build_bwrap_command( self, game: Game | None = None, game_dirs: list[str] | None = None, global_env: dict[str, str] | None = None, per_game_env: 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 global_env is None: global_env = {} if per_game_env is None: per_game_env = {} 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 global_env: sandbox_env.update(global_env) # ── Per-game environment (override layer) ────────────────── sandbox_env.update(per_game_env) # ── Environment variables to pass through (highest layer) ── for key in self.SANDBOX_ENV_KEYS: if key not in sandbox_env: 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] # inner_cmd: list[str] = ["/bin/bash", "-c", f"{umu_run} \"{game.path}\" 2>&1 ; exit 100"] 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 logging.root.level <= logging.DEBUG: os.environ["UMU_LOG"] = "debug" os.environ["PROTON_LOG"] = "1" 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(None, 0) 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(None, 0) if self._on_splash_close: self._on_splash_close() if self._on_proton_path_missing: self._on_proton_path_missing(proton_dir) return LaunchHandle(None, 0) # ── Load global env ───────────────────────────────────────── self.global_env = self.load_global_env() # ── Build per-game environment ────────────────────────────── per_game_env = self._build_per_game_env() # ── 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.global_env, per_game_env, ) log.info(f"final bwrap command: {bwrap_cmd}") log.info(f"sandbox environment: {sandbox_env}") # ── Launch ────────────────────────────────────────────────── run_env = os.environ.copy() run_env.update(sandbox_env) full_cmd = self._build_inhibit_prefix(self.game.gameid) + bwrap_cmd + inner_cmd try: # we invoke popen() setting work directory as a dirname() of our executable # this seems to be a common practice for launchers self.process = subprocess.Popen( full_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=8192, text=True, env=run_env, cwd=os.path.dirname(exec_path) ) 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(None, 0) 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, exit_code: int = 0) -> None: """Kill children, save playtime, and dispatch the appropriate callback. Parameters ---------- exit_code : int The process exit status. Zero means success; non-zero triggers the failure callback instead of ``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 exit_code == 0: if self._on_process_exit: self._on_process_exit() else: log.warning("Process exited with code %d", exit_code) if self._on_process_fail: self._on_process_fail(exit_code) # ── Watchdog ────────────────────────────────────────────────────── def _watchdog_loop(self) -> None: """Background thread: kill orphaned bwrap processes. Respects ``_is_cleanup`` to avoid interfering with the child-watch cleanup path. """ 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 not self.process: return if 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 # log.debug("_on_io_line: [%s] %s", "err" if is_stderr else "out", clean_line) # Dispatch to callback if self._on_output_line: self._on_output_line(clean_line, is_stderr) # Check for game-running signals — signal the adapter to close. if self._detect_game_running(clean_line): if self._on_splash_close: log.debug("invoking splash-close callback") self._on_splash_close() 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", ] for pattern in game_running_signals: if pattern in clean_line: log.debug( "game-running signal detected: %r in %r", pattern, clean_line, ) return True return False # ── 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