about summary refs log tree commit diff stats
path: root/fungus/run_manager.py
blob: e87e073f3b5f948dccef6a665cd3ce9e941c4a24 (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
#!/usr/bin/python3
"""GTK adapter for game launching.

All Gtk/Glib/D-Bus coupling lives here.  For pure business logic, see
``fungus.game_launcher.GameLauncher``.
"""

from __future__ import annotations

import os
import sys
from threading import Thread

import gi  # type: ignore

gi.require_version("Gtk", "3.0")

from gi.repository import Gtk, GLib  # type: ignore

from fungus.game_launcher import (
    GameLauncher,
    LaunchHandle,
    load_game as _load_game,
    run_winetricks as _run_winetricks,
)
from fungus.splash_window import SplashWindow
from fungus.dialogs import (
    SandboxWarningDialog,
    create_error_dialog,
)
from fungus.logger import get_logger

log = get_logger(__name__)

# Backward-compatibility alias for tests that import FungusRun directly
FungusRun = GameLauncher


# ---------------------------------------------------------------------------
# GTK-specific error dialog helpers
# ---------------------------------------------------------------------------


def _show_error_dialog_steam_runtime() -> None:
    create_error_dialog(
        title="Fungus Launcher",
        primary="The UMU Steam Runtime directory was not found.",
        secondary=(
            "Games using UMU-Launcher will not be able to run. "
            "Please open Settings → UMU-Launcher and update the runtime."
        ),
        quit_app=True,
    )


def _show_error_dialog_no_proton() -> None:
    create_error_dialog(
        title="Fungus Launcher",
        primary="No Proton version is installed.",
        secondary="Please install one via Settings → Proton Manager.",
        quit_app=True,
    )


def _show_error_dialog_proton_path(protonpath: str) -> None:
    create_error_dialog(
        title="Fungus Launcher",
        primary=f"{protonpath} was not found.",
        secondary="Please install it or use another Proton version.",
        quit_app=True,
    )


def _show_spawn_error(error_msg: str) -> None:
    create_error_dialog(
        title="Fungus Launcher",
        primary="The game runner could not be started.",
        secondary="Check the terminal output for details.",
        error_text=error_msg,
        quit_app=True,
    )


# ---------------------------------------------------------------------------
# handle_command — main entry point
# ---------------------------------------------------------------------------


def handle_command(
    game,
    cmd_override: str | None = None,
    igpu: bool = False,
) -> None:
    """Entry point: launch winetricks or the game."""
    # ── Unsandboxed winetricks path ───────────────────────────────
    if cmd_override == "winetricks":
        _run_winetricks(game)
        return

    if cmd_override:
        game.path = cmd_override
        game.game_arguments = ""

    # ── Show splash window ────────────────────────────────────────
    title = game.title or game.gameid or ""

    # ── Build callbacks (forward refs resolved below) ─────────────
    splash_container: list[SplashWindow | None] = [None]  # mutable container for forward reference

    def on_output_line(line: str, is_stderr: bool) -> None:
        color = "#e06c75" if is_stderr else None  # soft red for stderr
        s = splash_container[0]
        if s is not None:
            GLib.idle_add(
                lambda: s.append_output(f"{line}", color=color)
            )

    def on_error(msg: str) -> None:
        log.error("GameLauncher error: %s", msg)

    def on_process_exit() -> None:
        log.debug("on_process_exit: destroying splash and quitting GTK")
        s = splash_container[0]
        if s is not None:
            GLib.idle_add(s._destroy)
        GLib.idle_add(Gtk.main_quit)

    def on_process_fail(exit_code: int) -> None:
        """Handle a non-zero process exit — show error in the splash."""
        log.debug("on_process_fail: exit_code=%d", exit_code)
        s = splash_container[0]
        if s is not None:
            GLib.idle_add(s.show_error, exit_code)
        else:
            log.warning("Splash unavailable for error display (exit_code=%d)", exit_code)
            # Splash was already destroyed — quit GTK so the app doesn't hang.
            GLib.idle_add(Gtk.main_quit)

    def on_sandbox_warning(exec_path: str, valid_dirs: list[str]) -> None:
        GLib.idle_add(SandboxWarningDialog, exec_path, valid_dirs)

    def on_steam_runtime_missing() -> None:
        GLib.idle_add(_show_error_dialog_steam_runtime)

    def on_proton_missing() -> None:
        GLib.idle_add(_show_error_dialog_no_proton)

    def on_proton_path_missing(protonpath: str) -> None:
        GLib.idle_add(_show_error_dialog_proton_path, protonpath)

    def on_spawn_error(error_msg: str) -> None:
        GLib.idle_add(_show_spawn_error, error_msg)

    def _on_splash_close() -> None:
        """Schedule splash window close on the GTK main thread.

        Called from the I/O watch thread when a game-running signal
        (e.g. "fsync") is detected in the output.
        """
        log.debug("_on_splash_close: scheduling splash close")
        s = splash_container[0]
        if s is not None and hasattr(s, 'close'):
            GLib.idle_add(s.close)

    def on_process_started() -> None:
        pass  # splash is already shown

    # ── Create splash and wire it ─────────────────────────────────
    splash = SplashWindow(title, _on_splash_close)
    splash.show()
    splash_container[0] = splash

    # ── Create launcher and start ─────────────────────────────────
    launcher = GameLauncher(
        game,
        igpu=igpu,
        on_output_line=on_output_line,
        on_error=on_error,
        on_process_exit=on_process_exit,
        on_process_fail=on_process_fail,
        on_sandbox_warning=on_sandbox_warning,
        on_steam_runtime_missing=on_steam_runtime_missing,
        on_proton_missing=on_proton_missing,
        on_proton_path_missing=on_proton_path_missing,
        on_spawn_error=on_spawn_error,
        on_splash_close=_on_splash_close,
        on_process_started=on_process_started,
    )

    handle: LaunchHandle = launcher.start()

    # If start() returned a handle with process=None, validation failed —
    # the appropriate error dialog is already shown via callbacks.
    if handle.process is not None:
        # ── Attach GLib I/O watches ───────────────────────────────
        def make_io_handler(is_stderr: bool):
            """Create an I/O line handler for the given stream."""
            def io_handler(source, condition):
                raw = source.readline()
                if raw:
                    launcher._on_io_line(raw, is_stderr=is_stderr)
                return True
            return io_handler

        GLib.io_add_watch(
            handle.process.stdout,
            GLib.PRIORITY_LOW,
            GLib.IO_IN,
            make_io_handler(False),
        )
        GLib.io_add_watch(
            handle.process.stderr,
            GLib.PRIORITY_LOW,
            GLib.IO_IN,
            make_io_handler(True),
        )

        def _on_child_exit(pid: int, condition: int) -> bool:
            """GLib child watch callback — fires when the bwrap process exits.

            Extracts the exit code from *condition* and dispatches
            cleanup appropriately: success (0) → ``on_process_exit``,
            failure (non-zero) → ``on_process_fail``.
            """
            if os.WIFEXITED(condition):
                exit_code = os.WEXITSTATUS(condition)
            elif os.WIFSIGNALED(condition):
                exit_code = -os.WTERMSIG(condition)
            else:
                exit_code = condition

            log.debug(
                "_on_child_exit: pid=%d condition=%d → exit_code=%d",
                pid, condition, exit_code,
            )
            launcher.cleanup(exit_code)
            return False

        GLib.child_watch_add(
            GLib.PRIORITY_DEFAULT,
            handle.pid,
            _on_child_exit,
        )

    # ── Start process in a thread and enter the event loop ─────────
    # The child watch handles process lifecycle entirely.  The thread
    # is kept as a no-op placeholder; it must NOT call wait() because
    # that would reap the child and prevent GLib's child watch from
    # firing (glib docs: waitid ECHILD when child already reaped).
    def run_process():
        pass

    process_thread = Thread(target=run_process, daemon=True)
    process_thread.start()

    Gtk.main()

    process_thread.join()
    sys.exit(0)


# ---------------------------------------------------------------------------
# Convenience: load a game from the library
# ---------------------------------------------------------------------------


def load_game(gameid: str):
    return _load_game(gameid)