about summary refs log tree commit diff stats
path: root/fungus/game_launcher.py
blob: 685b516d02487dbcadc98603349b571055777664 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
#!/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 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`` 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()

    # ── 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]
        # 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"

        # TODO make this customizable per-game
        os.environ["WINEDLLOVERRIDES"] = "winmm=n,b;xgameruntime=n,b"

        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 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,
        )

        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 = 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