diff options
| author | fox <fox@fakecake.org> | 2026-07-04 19:20:16 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-07-04 19:20:16 +0300 |
| commit | 06f8ee598e6af9a18dff3be275e8474492b54e8b (patch) | |
| tree | d19961a34d7eeb0cb06b3ee1965d6f0e4f0ccf2b | |
| parent | 1bbbcdf2e71c7414803e17f2a7215a5d124f1eee (diff) | |
| parent | 3b8d30d74695d596b42911bdd65c0474f4a843db (diff) | |
| download | fungus-launcher-06f8ee598e6af9a18dff3be275e8474492b54e8b.tar.gz fungus-launcher-06f8ee598e6af9a18dff3be275e8474492b54e8b.tar.xz | |
Merge branch 'dev' into 'master'
Dev See merge request git/fungus-launcher!40
| -rw-r--r-- | fungus/game_launcher.py | 60 | ||||
| -rw-r--r-- | fungus/run_manager.py | 70 | ||||
| -rw-r--r-- | fungus/splash_window.py | 82 |
3 files changed, 161 insertions, 51 deletions
diff --git a/fungus/game_launcher.py b/fungus/game_launcher.py index 3648244..fb0806d 100644 --- a/fungus/game_launcher.py +++ b/fungus/game_launcher.py @@ -94,7 +94,7 @@ class GameLauncher: game: Game, igpu: bool = False, *, - on_output_line: Callable[[str], None] | None = None, + 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, @@ -102,13 +102,13 @@ class GameLauncher: 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.error_output: list[str] = [] self._cleanup_event = Event() self._on_output_line = on_output_line self._on_error = on_error @@ -118,6 +118,7 @@ class GameLauncher: 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() @@ -289,6 +290,7 @@ class GameLauncher: # ── 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) @@ -437,8 +439,16 @@ class GameLauncher: if self.process and self.process.poll() is None: self._kill_children() - def cleanup(self) -> None: - """Kill children, save playtime, call on_process_exit.""" + 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() @@ -461,13 +471,22 @@ class GameLauncher: except Exception: pass - if self._on_process_exit: - self._on_process_exit() + 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.""" + """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(): @@ -490,7 +509,9 @@ class GameLauncher: def _kill_children(self) -> None: """Kill the bwrap process and all its descendants (SIGTERM → SIGKILL).""" - if self.process and self.process.poll() is None: + if not self.process: + return + if self.process.poll() is None: try: parent = psutil.Process(self.process.pid) children = parent.children(recursive=True) @@ -555,19 +576,19 @@ class GameLauncher: if not clean_line: return - # Accumulate stderr for error reporting - if is_stderr: - self.error_output.append(clean_line) + 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) + self._on_output_line(clean_line, is_stderr) - # Check for game-running signals + # Check for game-running signals — signal the adapter to close. if self._detect_game_running(clean_line): if self._on_splash_close: - # The adapter handles scheduling via GLib.timeout_add_seconds - pass + log.debug("invoking splash-close callback") + self._on_splash_close() log.info("%s", line.rstrip()) @@ -591,7 +612,14 @@ class GameLauncher: "Executable a unix path", "status: 0", "PosixPath", "SingleInstance", "mtree is OK", ] - return any(signal in clean_line for signal in game_running_signals) + 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 ─────────────────────────────────────────────── diff --git a/fungus/run_manager.py b/fungus/run_manager.py index 2424187..03df048 100644 --- a/fungus/run_manager.py +++ b/fungus/run_manager.py @@ -107,20 +107,35 @@ def handle_command( # ── Build callbacks (forward refs resolved below) ───────────── splash_container: list[SplashWindow | None] = [None] # mutable container for forward reference - def on_output_line(line: str) -> None: + 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(s.append_output, line) + 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.close) + 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) @@ -137,6 +152,12 @@ def handle_command( 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) @@ -156,6 +177,7 @@ def handle_command( 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, @@ -193,6 +215,27 @@ def handle_command( 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, @@ -200,10 +243,12 @@ def handle_command( ) # ── 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(): - # Wait for the process to exit (the watchdog handles orphans) - if handle.process: - handle.process.wait() + pass process_thread = Thread(target=run_process, daemon=True) process_thread.start() @@ -214,19 +259,6 @@ def handle_command( sys.exit(0) -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 # --------------------------------------------------------------------------- diff --git a/fungus/splash_window.py b/fungus/splash_window.py index 7edbbc6..a65e19a 100644 --- a/fungus/splash_window.py +++ b/fungus/splash_window.py @@ -12,7 +12,7 @@ from collections.abc import Callable import gi gi.require_version("Gtk", "3.0") -from gi.repository import Gtk # type: ignore +from gi.repository import Gtk, GLib # type: ignore from fungus.constants import fungus_png @@ -89,51 +89,69 @@ class SplashWindow: grid.attach(self._close_button, 0, 2, 1, 1) self._window.add(frame) + + # Handle window manager close (X button) + self._window.connect("delete_event", self._on_delete_event) self._window.show_all() # ── Public API ──────────────────────────────────────────────────────── - def append_output(self, line: str) -> None: + def append_output( + self, line: str, *, color: str | None = None, bold: bool = False, + ) -> None: """Append a line of output to the text view. Parameters ---------- line : str Text line to append. + color : str, optional + Pango color name (e.g. ``"red"``, ``"#888888"``). + bold : bool, default False + Whether to render the line in bold. """ if self._buffer is None or self._text_view is None: return + # Wrap in Pango markup if styling is requested. + if color or bold: + attrs: list[str] = [] + if color: + attrs.append(f"foreground=\"{color}\"") + if bold: + attrs.append("weight=bold") + markup = f"<span {' '.join(attrs)}>{line}</span>" + else: + markup = line + end = self._buffer.get_end_iter() - self._buffer.insert(end, line + "\n") + self._buffer.insert_markup(end, markup + "\n", -1) self._text_view.scroll_to_iter(end, 0.0, True, 0.0, 1.0) # Reveal output view on first output if self._scrolled is not None: self._scrolled.set_visible(True) - def show_error(self, exit_code: int, stderr_lines: list[str]) -> None: - """Show error information in the splash window. + def show_error(self, exit_code: int) -> None: + """Re-show the splash after a failed process exit. + + The live stream already displayed stderr, so we just update the + title and reveal the Close button. Parameters ---------- exit_code : int Non-zero process exit code. - stderr_lines : list[str] - Accumulated stderr output. """ assert self._window is not None + # Reveal the window if it was hidden when the game started + self._window.show_all() + # Update window title with exit code current_title = self._window.get_title() or "" self._window.set_title(f"{current_title} — exited with code {exit_code}") - # Show accumulated stderr in the text view - if stderr_lines and self._buffer is not None: - error_text = "\n".join(stderr_lines) - self.append_output(f"\n--- stderr ({len(stderr_lines)} lines) ---") - self.append_output(error_text) - # Reveal output view and close button if self._scrolled is not None: self._scrolled.set_visible(True) @@ -142,10 +160,26 @@ class SplashWindow: self._close_button.set_sensitive(True) def close(self) -> None: - """Destroy the splash window and invoke the close callback.""" + """Hide the splash window. + + Called when the game has started — the window is kept alive so + output can continue to be written and it can be shown again if + the game exits with an error. + """ + if self._window is not None: + self._window.hide() + + def _destroy(self) -> None: + """Destroy the splash window and invoke the close callback. + + Called during final cleanup (process exit). The callback is + cleared after the first invocation to prevent an infinite loop. + """ if self._window is not None: self._window.destroy() # type: ignore[union-attr] + # Clear the callback so repeated _destroy() calls are no-ops. self._on_close() + self._on_close = lambda: None def show(self) -> None: """Show the splash window (no-op if already visible).""" @@ -164,6 +198,22 @@ class SplashWindow: # ── Internal ────────────────────────────────────────────────────────── - def _on_close_clicked(self, _widget: Gtk.Widget) -> None: - """Handle the Close button click.""" + def _on_delete_event(self, _widget: Gtk.Widget, _event: object) -> bool: + """Handle window manager close (X button). + + Returns ``True`` to prevent further destruction (we handle it + ourselves). Quits GTK in error mode, hides the splash + otherwise. + """ + if self._close_button is not None and self._close_button.get_visible(): + GLib.idle_add(Gtk.main_quit) self.close() + return True # prevent default destruction + + def _on_close_clicked(self, _widget: Gtk.Widget) -> None: + """Handle the Close button click. + + When the Close button is visible (error mode), quit GTK — the + game process is already dead and there is nothing left to do. + """ + self._on_delete_event(None, None) |
