diff options
| author | fox <fox@fakecake.org> | 2026-07-03 15:18:54 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-07-03 15:18:54 +0300 |
| commit | ce298d6bdb315d2b5db3e03b0a40a2ec1331ed4b (patch) | |
| tree | c0b550e27b4a89b1c50bdd30add037f6b4234a9a | |
| parent | a164de0e13d80f6fe7d79ba8d8ac9411abea98a3 (diff) | |
| parent | f659b7f0819ae9bdc9fc626e321aca33ffbd9173 (diff) | |
| download | fungus-launcher-ce298d6bdb315d2b5db3e03b0a40a2ec1331ed4b.tar.gz fungus-launcher-ce298d6bdb315d2b5db3e03b0a40a2ec1331ed4b.tar.xz | |
Merge branch 'dev' into 'master'
only create wineprefix/dir on adding a game if it doesn't exist See merge request git/fungus-launcher!32
| -rw-r--r-- | fungus-launcher.py | 20 | ||||
| -rw-r--r-- | fungus-proton-manager.py | 49 | ||||
| -rw-r--r-- | fungus-run.py | 30 | ||||
| -rw-r--r-- | fungus/add_game_dialog.py | 17 | ||||
| -rw-r--r-- | fungus/constants.py | 5 | ||||
| -rw-r--r-- | fungus/logger.py | 69 | ||||
| -rw-r--r-- | fungus/main_window.py | 47 | ||||
| -rw-r--r-- | fungus/proton_manager.py | 43 | ||||
| -rw-r--r-- | fungus/run_manager.py | 292 | ||||
| -rw-r--r-- | fungus/settings_dialog.py | 55 | ||||
| -rw-r--r-- | fungus/umu_manager.py | 160 | ||||
| -rw-r--r-- | fungus/utils.py | 6 | ||||
| -rw-r--r-- | scripts/check_handlers.py | 13 | ||||
| -rw-r--r-- | tests/test_proton_steamrt_mapping.py | 82 | ||||
| -rw-r--r-- | tests/test_steamrt_timestamp.py | 79 |
15 files changed, 709 insertions, 258 deletions
diff --git a/fungus-launcher.py b/fungus-launcher.py index 20faf80..4b325d4 100644 --- a/fungus-launcher.py +++ b/fungus-launcher.py @@ -1,5 +1,6 @@ #!/usr/bin/python3 +import argparse import os import sys @@ -14,11 +15,26 @@ else: dev_site_packages = os.path.join(base_dir, PYTHON_SITE_PACKAGES) sys.path.insert(0, dev_site_packages) -from fungus.app import FungusApp +from fungus.logger import set_level +import logging + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Fungus Launcher — a game library manager for Linux/Wine.", + ) + parser.add_argument("-v", "--verbose", action="store_true", + help="Enable debug logging output") + args = parser.parse_args() + + if args.verbose: + set_level(logging.DEBUG) + + from fungus.app import FungusApp -def main(): app = FungusApp() app.run(sys.argv) + if __name__ == "__main__": main() diff --git a/fungus-proton-manager.py b/fungus-proton-manager.py index 090d747..8fb3b8f 100644 --- a/fungus-proton-manager.py +++ b/fungus-proton-manager.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """Fungus Proton Manager — GTK UI for downloading / removing Proton versions.""" +import argparse import os import threading @@ -11,7 +12,26 @@ gi.require_version("Gtk", "3.0") from gi.repository import Gtk, GLib # type: ignore from fungus.dark_theme import apply_dark_theme +from fungus.logger import get_logger, set_level from fungus.path_manager import PathManager +import logging + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Fungus Proton Manager — download / remove Proton versions.", + ) + parser.add_argument("-v", "--verbose", action="store_true", + help="Enable debug logging output") + args = parser.parse_args() + + if args.verbose: + set_level(logging.DEBUG) + + apply_dark_theme() + win = ProtonDownloader() + win.connect("destroy", Gtk.main_quit) + Gtk.main() from fungus.proton_manager import ( RATE_LIMITED_MSG, _cache_key, @@ -23,6 +43,8 @@ from fungus.proton_manager import ( remove_path, ) +log = get_logger(__name__) + fungus_png = PathManager.get_icon("fungus-launcher.png") @@ -154,9 +176,9 @@ class ProtonDownloader(Gtk.Dialog): cache_path = get_cache_dir() / _cache_key(url) try: cache_path.unlink(missing_ok=True) - print(f"[ProtonManager] Cache removed: {url}") + log.debug("Cache removed: %s", url) except OSError as exc: - print(f"[ProtonManager] Cache removal failed: {exc}") + log.warning("Cache removal failed: %s", exc) def _on_refresh_clicked(self, widget): """Clear cache and re-fetch releases.""" @@ -195,7 +217,7 @@ class ProtonDownloader(Gtk.Dialog): def _fetch_releases_async(self): """Fetch releases from GitHub in a background thread, then update UI.""" - print("[ProtonManager] Starting async fetch...") + log.debug("Starting async fetch...") try: ge_releases = _fetch_with_cache( "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases", @@ -203,16 +225,13 @@ class ProtonDownloader(Gtk.Dialog): em_releases = _fetch_with_cache( "https://api.github.com/repos/Etaash-mathamsetty/Proton/releases", ) - print( - f"[ProtonManager] GE-Proton: {len(ge_releases)}, " - f"Proton-EM: {len(em_releases)}" - ) + 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) - print(f"[ProtonManager] GLib.idle_add returned: {result}") + log.debug("GLib.idle_add returned: %s", result) except Exception as e: # RateLimited is caught here along with any other exception - print(f"[ProtonManager] Exception: {e}") + log.error("Exception: %s", e) GLib.idle_add(self._render_error, str(e)) # ── UI rendering callbacks ──────────────────────────────────────── @@ -369,7 +388,7 @@ class ProtonDownloader(Gtk.Dialog): self.progress_bar.set_visible(False) self.progress_label.set_visible(False) else: - print(f"[ProtonManager] No suitable asset found for {release['tag_name']}") + log.warning("No suitable asset found for %s", release['tag_name']) widget.set_label("Download") widget.set_sensitive(True) self.enable_all_buttons() @@ -385,15 +404,5 @@ class ProtonDownloader(Gtk.Dialog): widget.set_sensitive(True) -# ── Main ────────────────────────────────────────────────────────────── - - -def main(): - apply_dark_theme() - win = ProtonDownloader() - win.connect("destroy", Gtk.main_quit) - Gtk.main() - - if __name__ == "__main__": main() diff --git a/fungus-run.py b/fungus-run.py index 5373a7a..c5753d7 100644 --- a/fungus-run.py +++ b/fungus-run.py @@ -1,5 +1,6 @@ #!/usr/bin/python3 +import argparse import os import sys @@ -9,7 +10,34 @@ dev_site_packages = os.path.join(base_dir, "lib", "python3.*", "site-packages") if os.path.exists(dev_site_packages): sys.path.insert(0, dev_site_packages) -from fungus.run_manager import main +from fungus.logger import set_level +import logging + + +def main() -> None: + parser = argparse.ArgumentParser(description="Launch a game via Fungus.") + parser.add_argument("-v", "--verbose", action="store_true", + help="Enable debug logging output") + parser.add_argument("--game") + parser.add_argument("--cmd", help="Override the game executable path") + parser.add_argument("--igpu", action="store_true", + help="Force integrated GPU") + args = parser.parse_args() + + if args.verbose: + set_level(logging.DEBUG) + + from fungus.run_manager import handle_command, load_game_from_json + + if not args.game: + parser.error("no game provided. Use --game <gameid>.") + + game = load_game_from_json(args.game) + if not game: + parser.error(f'game "{args.game}" not found in games.json.') + + handle_command(game, cmd_override=args.cmd, igpu=args.igpu) + if __name__ == "__main__": main() diff --git a/fungus/add_game_dialog.py b/fungus/add_game_dialog.py index 2cc2c41..c0f816d 100644 --- a/fungus/add_game_dialog.py +++ b/fungus/add_game_dialog.py @@ -18,6 +18,9 @@ from gi.repository import Gtk, Gdk, GdkPixbuf, GLib # type: ignore from PIL import Image from fungus.config_manager import ConfigManager +from fungus.logger import get_logger + +log = get_logger(__name__) from fungus.constants import ( app_dir, desktop_dir, @@ -559,10 +562,10 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): if result.returncode != 0: if "NoIconsAvailableError" in result.stderr or "PEFormatError" in result.stderr: - print("The file does not contain icons.") + log.debug("The file does not contain icons.") self.button_shortcut_icon.set_image(self.set_image_shortcut_icon()) else: - print(f"Error extracting icon: {result.stderr}") + log.error("Error extracting icon: %s", result.stderr) else: img = Image.open(self.icon_extracted) img.save(self.icon_converted) @@ -570,7 +573,7 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): os.remove(self.icon_extracted) except Exception as e: - print(f"An error occurred: {e}") + log.error("An error occurred: %s", e) def is_valid_image(file_path): try: @@ -683,7 +686,7 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): largest_resolution = (width, height) largest_image = file_path except OSError: - print(f"Unable to open {file_path}") + log.debug("Unable to open %s", file_path) return largest_image @@ -841,10 +844,10 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): if result.returncode != 0: if "NoIconsAvailableError" in result.stderr or "PEFormatError" in result.stderr: - print("The file does not contain icons.") + log.debug("The file does not contain icons.") self.button_shortcut_icon.set_image(self.set_image_shortcut_icon()) else: - print(f"Error extracting icon: {result.stderr}") + log.error("Error extracting icon: %s", result.stderr) else: img = Image.open(self.icon_extracted) img.save(self.icon_converted) @@ -864,7 +867,7 @@ class AddGame(EntryTooltipMixin, Gtk.Dialog): self.button_shortcut_icon.set_image(image) except Exception as e: - print(f"An error occurred: {e}") + log.error("An error occurred: %s", e) self.entry_path.set_text(path) diff --git a/fungus/constants.py b/fungus/constants.py index 5f5a296..333fc0e 100644 --- a/fungus/constants.py +++ b/fungus/constants.py @@ -5,15 +5,18 @@ import subprocess from pathlib import Path +from fungus.logger import get_logger from fungus.path_manager import PathManager +log = get_logger(__name__) + fungus_version = "@VERSION@-@RELEASE@" def get_desktop_dir(): try: return subprocess.check_output(['xdg-user-dir', 'DESKTOP'], text=True).strip() except (FileNotFoundError, subprocess.CalledProcessError): - print("xdg-user-dir not found or failed; falling back to ~/Desktop") + log.warning("xdg-user-dir not found or failed; falling back to ~/Desktop") return str(Path.home() / 'Desktop') # ── User config / data paths ──────────────────────────────────────────── diff --git a/fungus/logger.py b/fungus/logger.py new file mode 100644 index 0000000..41955cf --- /dev/null +++ b/fungus/logger.py @@ -0,0 +1,69 @@ +#!/usr/bin/python3 +"""Centralised logging configuration for Fungus Launcher. + +Sets up a root logger with a single console handler that writes to +stderr (so stdout remains clean for pipes). All submodules should +obtain their logger via ``get_logger(name)`` rather than calling +``logging.getLogger`` directly — this ensures the handler is +installed exactly once at first call. + +Usage:: + + from fungus.logger import get_logger, set_level + log = get_logger(__name__) + log.info("something happened") + log.debug("verbose details") + log.error("something went wrong: %s", exc) + + # Enable debug output from the CLI:: + + set_level(logging.DEBUG) +""" + +import logging +import sys + +_handler: logging.Handler | None = None + + +def set_level(level: int) -> None: + """Set the minimum logging level for all loggers. + + Installs the handler if it has not yet been created, then sets + both the root logger and the handler to *level*. + """ + global _handler + + if not _handler: + _handler = logging.StreamHandler(sys.stderr) + _handler.setFormatter( + logging.Formatter("[%(name)s] %(levelname)s %(message)s") + ) + logging.root.addHandler(_handler) + + logging.root.setLevel(level) + _handler.setLevel(level) + + +def get_logger(name: str | None = None) -> logging.Logger: + """Return a logger named *name* (or the root logger). + + The first call installs a ``StreamHandler`` writing to + ``sys.stderr`` with a simple ``[name] level message`` format. + Subsequent calls reuse the same handler. + """ + global _handler + + logger = logging.getLogger(name) + + if not _handler: + _handler = logging.StreamHandler(sys.stderr) + _handler.setFormatter( + logging.Formatter("[%(name)s] %(levelname)s %(message)s") + ) + logger.addHandler(_handler) + + # Leave the logger at NOTSET so it inherits from the root logger. + # The handler's own level (INFO by default) controls the minimum + # severity; passing -v/--verbose raises it to DEBUG. + return logger diff --git a/fungus/main_window.py b/fungus/main_window.py index 58050e1..179e94e 100644 --- a/fungus/main_window.py +++ b/fungus/main_window.py @@ -1,6 +1,7 @@ #!/usr/bin/python3 """Main window — game list, sidebar, search, play/kill/edit/delete, context menus.""" +import logging import os import shutil import subprocess @@ -12,6 +13,7 @@ gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk, GdkPixbuf, GLib # type: ignore from fungus.config_manager import ConfigManager +from fungus.logger import get_logger from fungus.constants import ( app_dir, backup_dir, @@ -43,6 +45,8 @@ from fungus.umu_manager import ( is_umu_installed, ) +log = get_logger(__name__) + class Main(Gtk.ApplicationWindow): def __init__(self, app): @@ -50,7 +54,7 @@ class Main(Gtk.ApplicationWindow): super().__init__(application=app, title="Fungus Launcher") self.set_icon_from_file(fungus_png) self.connect("delete-event", self.on_close) - print(f"Fungus Launcher {fungus_version}") + log.info("Fungus Launcher %s", fungus_version) self.start_maximized = False self.current_prefix = None @@ -790,6 +794,8 @@ class Main(Gtk.ApplicationWindow): cwd = game_directory if game_directory and os.path.isdir(game_directory) else None cmd = [sys.executable, fungus_run, "--game", game.gameid] + if logging.root.level <= logging.DEBUG: + cmd.insert(2, "--verbose") if igpu: cmd.append("--igpu") @@ -840,25 +846,26 @@ class Main(Gtk.ApplicationWindow): runner = add_game_dialog.combobox_runner.get_active_text() if prefix: - os.makedirs(prefix, exist_ok=True) - # Initialize the Wine prefix via UMU - gameid = protonfix if protonfix else title_formatted - if gameid and runner: - env = os.environ.copy() - env["GAMEID"] = gameid - env["WINEPREFIX"] = prefix - env["PROTONPATH"] = runner - try: - subprocess.run( - [umu_run, "wineprefixcreate", "/usr/bin/true"], - env=env, - check=True, - capture_output=True, - ) - except subprocess.CalledProcessError as e: - print(f"Prefix initialization failed for '{title}': {e.stderr.decode()}") - else: - print(f"Skipping prefix init for '{title}' (GAMEID or runner missing)") + if not os.path.isdir(prefix): + os.makedirs(prefix, exist_ok=True) + # Initialize the Wine prefix via UMU + gameid = protonfix if protonfix else title_formatted + if gameid and runner: + env = os.environ.copy() + env["GAMEID"] = gameid + env["WINEPREFIX"] = prefix + env["PROTONPATH"] = runner + try: + subprocess.run( + [umu_run, "wineprefixcreate", "/usr/bin/true"], + env=env, + check=True, + capture_output=True, + ) + except subprocess.CalledProcessError as e: + log.error("Prefix initialization failed for '%s': %s", title, e.stderr.decode()) + else: + log.warning("Skipping prefix init for '%s' (GAMEID or runner missing)", title) if os.path.exists(games_json): existing = load_games_json(games_json) diff --git a/fungus/proton_manager.py b/fungus/proton_manager.py index bd74b6e..2d360d9 100644 --- a/fungus/proton_manager.py +++ b/fungus/proton_manager.py @@ -30,8 +30,11 @@ from pathlib import Path import requests +from fungus.logger import get_logger from fungus.path_manager import PathManager +log = get_logger(__name__) + # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- @@ -97,23 +100,23 @@ def _fetch_with_cache(url, cache_dir=None): with open(cache_path) as f: entry = json.load(f) if now - entry["time"] < CACHE_TTL: - print(f"[ProtonManager] Cache hit: {url}") + log.debug("Cache hit: %s", url) return entry["data"] - print(f"[ProtonManager] Cache expired: {url}") + log.debug("Cache expired: %s", url) except (json.JSONDecodeError, KeyError) as exc: - print(f"[ProtonManager] Corrupt cache, ignoring: {exc}") + log.warning("Corrupt cache, ignoring: %s", exc) # Fetch fresh data. - print(f"[ProtonManager] Fetching: {url}") + log.debug("Fetching: %s", url) releases = fetch_releases(url) # Save to cache. try: with open(cache_path, "w") as f: json.dump({"time": now, "data": releases}, f) - print(f"[ProtonManager] Cached: {url} ({len(releases)} releases)") + log.debug("Cached: %s (%d releases)", url, len(releases)) except OSError as exc: - print(f"[ProtonManager] Cache write failed: {exc}") + log.warning("Cache write failed: %s", exc) return releases @@ -152,7 +155,7 @@ def fetch_releases(url): else: break - print(f"[ProtonManager] Fetched {len(releases)} raw releases from {url}") + log.info("Fetched %d raw releases from %s", len(releases), url) filtered = [] for release in releases: @@ -163,26 +166,26 @@ def fetch_releases(url): if "GloriousEggroll" in url: if not tag_name.startswith("GE-Proton"): - print(f"[ProtonManager] Skipping {tag_name}: doesn't start with GE-Proton") + log.debug("Skipping %s: doesn't start with GE-Proton", tag_name) continue try: # Two formats: "GE-Proton-9.11-1" or "GE-Proton11-1" after = tag_name[len("GE-Proton"):] nums = re.findall(r"\d+", after) if len(nums) < 2: - print(f"[ProtonManager] Skipping {tag_name}: cannot parse version") + log.debug("Skipping %s: cannot parse version", tag_name) continue major, minor = int(nums[0]), int(nums[1]) if (major, minor) < (9, 1): - print(f"[ProtonManager] Skipping {tag_name}: version ({major}.{minor}) < 9.1") + log.debug("Skipping %s: version (%d.%d) < 9.1", tag_name, major, minor) continue except Exception as exc: - print(f"[ProtonManager] Skipping {tag_name}: version parse error: {exc}") + log.debug("Skipping %s: version parse error: %s", tag_name, exc) continue elif "Etaash-mathamsetty" in url: if not tag_name.startswith("EM-"): - print(f"[ProtonManager] Skipping {tag_name}: doesn't start with EM-") + log.debug("Skipping %s: doesn't start with EM-", tag_name) continue assets = release.get("assets", []) @@ -191,12 +194,12 @@ def fetch_releases(url): for asset in assets ) if not has_valid_asset: - print(f"[ProtonManager] Skipping {tag_name}: no tar.gz/tar.xz asset") + log.debug("Skipping %s: no tar.gz/tar.xz asset", tag_name) continue filtered.append(release) - print(f"[ProtonManager] Filtered down to {len(filtered)} releases") + log.info("Filtered down to %d releases", len(filtered)) return filtered @@ -228,7 +231,7 @@ def get_arch_asset(assets): else: continue if stem.endswith(MACHINE_ARCH): - print(f"[ProtonManager] Selected asset for arch {MACHINE_ARCH}: {name}") + log.debug("Selected asset for arch %s: %s", MACHINE_ARCH, name) return asset # Second pass (x86_64 only): the default build has no arch suffix. @@ -244,15 +247,15 @@ def get_arch_asset(assets): else: continue if not stem.endswith(MACHINE_ARCH) and not stem.endswith("aarch64"): - print(f"[ProtonManager] Selected default (x86_64) asset: {name}") + log.debug("Selected default (x86_64) asset: %s", name) return asset # Fallback: return the first tar archive. for asset in assets: if asset["name"].endswith((".tar.gz", ".tar.xz")): - print( - f"[ProtonManager] No arch-specific asset found for {MACHINE_ARCH}, " - f"falling back to: {asset['name']}" + log.warning( + "No arch-specific asset found for %s, falling back to: %s", + MACHINE_ARCH, asset["name"], ) return asset return None @@ -414,7 +417,7 @@ def download_and_extract( progress_callback(100) except Exception as e: - print(f"Error during extraction: {e}") + log.error("Error during extraction: %s", e) if message_callback: message_callback("Error during extraction") if button_update_callback: diff --git a/fungus/run_manager.py b/fungus/run_manager.py index 258d636..4c490c0 100644 --- a/fungus/run_manager.py +++ b/fungus/run_manager.py @@ -1,11 +1,9 @@ #!/usr/bin/python3 -import argparse import dbus # type: ignore import gi # type: ignore import os import re -import shlex import signal import subprocess import psutil # type: ignore @@ -13,11 +11,16 @@ import sys import time from pathlib import Path from threading import Thread, Event +from typing import ClassVar + +from fungus.logger import get_logger + +log = get_logger(__name__) gi.require_version("Gtk", "3.0") -from gi.repository import Gtk, GLib, GdkPixbuf # type: ignore +from gi.repository import Gtk, GLib # type: ignore from fungus.config_manager import ConfigManager from fungus.constants import ( envar_dir, @@ -30,9 +33,7 @@ from fungus.game_model import Game, load_games_json, save_games_json from fungus.path_manager import PathManager from fungus.utils import has_proton_installed, is_executable_in_whitelist from fungus.dialogs import SandboxWarningDialog, SteamRuntimeWarningDialog - -# Path to the UMU Steam Runtime (used by umu-run) -UMU_STEAMRT_DIR = os.path.expanduser("~/.local/share/umu/steamrt3") +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) @@ -46,6 +47,62 @@ class FungusRun: "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. @@ -97,12 +154,12 @@ class FungusRun: full = os.path.join(search_dir, name) if os.path.isfile(full): self.game.path = full - print(f"[cmd-resolve] {path!r} -> {full!r}") + 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). - print(f"[cmd-resolve] no match for {path!r} in prefix system dirs") + 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. @@ -120,11 +177,14 @@ class FungusRun: os.environ["__VK_LAYER_NV_OPTIMUS"] = "NVIDIA_only" os.environ["__GLX_VENDOR_LIBRARY_NAME"] = "nvidia" - # Set environment variables from game properties + # 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 self.game.runner: - os.environ["PROTONPATH"] = self.game.runner + if proton_dir: + os.environ["PROTONPATH"] = proton_dir self.start_time = time.time() @@ -136,13 +196,16 @@ class FungusRun: ): os.environ["PROTONFIXES_DISABLE"] = "1" - # Validate that the UMU Steam Runtime is available - if not os.path.isdir(UMU_STEAMRT_DIR): + # 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 = os.environ.get("PROTONPATH") + protonpath = proton_dir if protonpath: protonpath_path = Path(share_dir) / "Steam/compatibilitytools.d" / protonpath if not protonpath_path.is_dir(): @@ -154,19 +217,19 @@ class FungusRun: self.env_from_file = self.load_env_from_file(envar_dir) if self.env_from_file: - print("\n=== GLOBAL ENVIRONMENT VARIABLES ===") + log.debug("=== GLOBAL ENVIRONMENT VARIABLES ===") for key in sorted(self.env_from_file): - print(f"{key}={self.env_from_file[key]}") + log.debug("%s=%s", key, self.env_from_file[key]) - print("\n=== ENVIRONMENT VARIABLES ===") + log.debug("=== ENVIRONMENT VARIABLES ===") for key in sorted(self.SANDBOX_ENV_KEYS): - print(f"{key}={os.environ.get(key, '')}") + log.debug("%s=%s", key, os.environ.get(key, '')) - print("\n=== GAME INFORMATION ===") - print(f"Game: {self.game.title or self.game.gameid}") - print(f"Path: {self.game.path}") - print(f"Runner: {self.game.runner or 'default'}") - print(f"Prefix: {self.game.prefix}\n") + 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) @@ -179,35 +242,17 @@ class FungusRun: game: Game, game_dirs: list[str], env_from_file: dict[str, str] | None = None, - ) -> tuple[list[str], dict[str, str]]: - """Construct the bwrap command and its environment variables. + ) -> tuple[list[str], dict[str, str], list[str]]: + """Construct the bwrap sandbox and inner command. - Returns a tuple of (bwrap_args_list, env_dict) where env_dict - contains only the variables that should be set inside the sandbox. + 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). """ - home = Path.home() bwrap_args: list[str] = [] sandbox_env: dict[str, str] = {} - # ── Construct inner command from game properties ──────────────── - inner_cmd_parts: list[str] = [] - if game.protonfix: - inner_cmd_parts.append(f"GAMEID={game.protonfix}") - else: - inner_cmd_parts.append(f"GAMEID={game.gameid}") - if game.runner: - inner_cmd_parts.append(f"WINEPREFIX={shlex.quote(game.prefix)}") - inner_cmd_parts.append(f"PROTONPATH='{game.runner}'") - else: - inner_cmd_parts.append(f"WINEPREFIX={shlex.quote(game.prefix)}") - if game.launch_arguments: - inner_cmd_parts.append(game.launch_arguments) - inner_cmd_parts.append(f"'{umu_run}'") - inner_cmd_parts.append(shlex.quote(game.path)) - if game.game_arguments: - inner_cmd_parts.append(game.game_arguments) - inner_cmd = " ".join(inner_cmd_parts) - # ── Sandbox namespaces ────────────────────────────────────────── # NOTE: We deliberately omit --as-pid-1. Without it, bwrap installs # a proper reaper (PID 1) inside the namespace that reaps zombies @@ -232,18 +277,16 @@ class FungusRun: 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([ - "--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", - ]) + bwrap_args.extend(self._flatten_bwrap_args(self.SYSTEM_RO_BINDS)) # ── GAME_DIRS bind mounts ─────────────────────────────────────── for dir_path in game_dirs: @@ -253,27 +296,21 @@ class FungusRun: 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"), + ]) - bwrap_args.extend([ - "--bind", "/tmp", "/tmp", - "--proc", "/proc", - "--dev-bind", "/dev", "/dev", - ]) + # ── 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]) - bwrap_args.extend([ - "--bind", str(home / ".local" / "share" / "umu"), - str(home / ".local" / "share" / "umu"), - "--bind", str(home / ".local" / "share" / "Steam"), - str(home / ".local" / "share" / "Steam"), - "--bind", str(home / ".local" / "share" / "fungus-launcher"), - str(home / ".local" / "share" / "fungus-launcher"), - "--ro-bind", str(home / ".Xauthority"), - str(home / ".Xauthority"), - ]) + # ── 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")) @@ -282,10 +319,12 @@ class FungusRun: if cfg_path.exists(): bwrap_args.extend(["--ro-bind", str(cfg_path), str(cfg_path)]) - # ── Final command ─────────────────────────────────────────────── - bwrap_args.extend(["/bin/bash", "-c", inner_cmd]) + # ── 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 + return bwrap_args, sandbox_env, inner_cmd def execute_final_command(self): """Build and execute the sandboxed bwrap command. @@ -317,28 +356,34 @@ class FungusRun: # Check whether the game executable's directory is within the whitelist exec_path = self.game.path - print(f"[sandbox-check] exec_path: {exec_path!r}") + 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 = self.build_bwrap_command(self.game, valid_dirs, self.env_from_file) + bwrap_cmd, sandbox_env, inner_cmd = self.build_bwrap_command( + self.game, valid_dirs, self.env_from_file, + ) - print("\n=== FINAL BWRAP COMMAND ===") - print(f"{bwrap_cmd}\n") + log.debug("=== FINAL BWRAP COMMAND ===") + log.debug("%s", ' '.join(bwrap_cmd)) + log.debug("=== INNER COMMAND ===") + log.debug("%s", ' '.join(inner_cmd)) - print("\n=== FINAL SANDBOX ENV ===") + log.debug("=== FINAL SANDBOX ENV ===") for key in sorted(sandbox_env): - print(f"{key}={os.environ.get(key, '')}") + 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( - bwrap_cmd, + full_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=8192, @@ -348,7 +393,7 @@ class FungusRun: except (FileNotFoundError, OSError) as exc: error_msg = ( f"Failed to start game runner: {exc}\n" - f"Command: {' '.join(bwrap_cmd[:5])}..." + f"Command: {' '.join(full_cmd[:5])}..." ) GLib.idle_add(self._show_spawn_error, error_msg) return @@ -454,10 +499,10 @@ class FungusRun: if not self.splash_window: self.show_splash_window() - # Update label with exit code - self.label.set_text( - "Process exited with code %d" % exit_code - ) + # Update window title with exit code + if self.splash_window: + current_title = self.splash_window.get_title() or "" + self.splash_window.set_title(f"{current_title} — exited with code {exit_code}") # Show accumulated stderr in the text view if self.error_output: @@ -602,11 +647,10 @@ class FungusRun: return env_from_file def load_config(self): - """Load discrete-GPU, default-runner, and game-directories from config.""" + """Load discrete-GPU and game-directories from config.""" cfg = ConfigManager() self.discrete_gpu = cfg.get_bool("discrete-gpu", False) - self.default_runner = cfg.get("default-runner", "") self.game_directories = cfg.get("game-directories", "").strip() def _watchdog_loop(self): @@ -630,7 +674,7 @@ class FungusRun: try: bwrap_proc = psutil.Process(self.process.pid) if bwrap_proc.is_running() and bwrap_proc.status() != psutil.STATUS_ZOMBIE: - print(f"[watchdog] Killing orphaned bwrap (PID {bwrap_proc.pid})") + log.warning("Killing orphaned bwrap (PID %d)", bwrap_proc.pid) bwrap_proc.kill() bwrap_proc.wait(timeout=2) except psutil.NoSuchProcess: @@ -690,10 +734,11 @@ class FungusRun: pass def show_splash_window(self): - """Create and display the splash window with logo, title, and output view.""" - self.splash_window = Gtk.Window(title="Fungus Launcher") - self.splash_window.set_decorated(False) - self.splash_window.set_resizable(False) + """Create and display the splash window with window title and output view.""" + title = self.game.title or self.game.gameid or "" + self.splash_window = Gtk.Window(title=title) + self.splash_window.set_decorated(True) + self.splash_window.set_resizable(True) self.splash_window.set_default_size(840, 400) self.splash_window.set_icon_from_file(fungus_png) @@ -707,21 +752,6 @@ class FungusRun: grid.set_row_spacing(10) frame.add(grid) - # Logo - image_path = fungus_png - pixbuf = GdkPixbuf.Pixbuf.new_from_file(image_path) - pixbuf = pixbuf.scale_simple(75, 75, GdkPixbuf.InterpType.BILINEAR) - image = Gtk.Image.new_from_pixbuf(pixbuf) - image.set_margin_top(20) - image.set_margin_bottom(5) - grid.attach(image, 0, 0, 1, 1) - - # Game title - self.label = Gtk.Label(label=self.game.title or self.game.gameid or "") - self.label.set_halign(Gtk.Align.CENTER) - self.label.set_margin_bottom(5) - grid.attach(self.label, 0, 1, 1, 1) - # Live output text view (hidden until output arrives) self.output_buffer = Gtk.TextBuffer() self.text_view = Gtk.TextView(buffer=self.output_buffer) @@ -742,14 +772,14 @@ class FungusRun: self.scrolled_output.set_vexpand(True) self.scrolled_output.set_visible(False) self.scrolled_output.add(self.text_view) - grid.attach(self.scrolled_output, 0, 2, 1, 1) + grid.attach(self.scrolled_output, 0, 1, 1, 1) # Close button (hidden until error) self.close_button = Gtk.Button(label="Close") self.close_button.set_sensitive(False) self.close_button.set_size_request(150, -1) self.close_button.connect("clicked", self._on_splash_close) - grid.attach(self.close_button, 0, 3, 1, 1) + grid.attach(self.close_button, 0, 2, 1, 1) self.splash_window.add(frame) self.splash_window.show_all() @@ -802,7 +832,7 @@ class FungusRun: self.check_game_output(clean_line) - print(line, end="") + log.info("%s", line.rstrip()) return True @@ -904,18 +934,17 @@ def run_winetricks(game: Game) -> None: run_env = os.environ.copy() run_env["GAMEID"] = gameid run_env["WINEPREFIX"] = prefix - if runner: - run_env["PROTONPATH"] = runner + run_env["PROTONPATH"] = runner # ── Build command: umu-run winetricks ──────────────────────────── winetricks_cmd = [umu_run, "winetricks", "--gui"] - print(f"\n=== WINETRICKS (unsandboxed) ===") - print(f"GAMEID={gameid}") - print(f"WINEPREFIX={prefix}") + log.debug("=== WINETRICKS (unsandboxed) ===") + log.debug("GAMEID=%s", gameid) + log.debug("WINEPREFIX=%s", prefix) if runner: - print(f"PROTONPATH={runner}") - print(f"Command: {' '.join(winetricks_cmd)}\n") + log.debug("PROTONPATH=%s", runner) + log.debug("Command: %s", ' '.join(winetricks_cmd)) # ── Launch and wait ────────────────────────────────────────────── start_time = time.time() @@ -984,33 +1013,4 @@ def load_game_from_json(gameid): return None -def main(): - """CLI entry point — parse args, load game, and launch it.""" - from fungus.dark_theme import apply_dark_theme - - apply_dark_theme() - - parser = argparse.ArgumentParser(description=None) - parser.add_argument("--game") - parser.add_argument("--cmd", help="Override the game executable path") - parser.add_argument("--igpu", action="store_true", - help="Force integrated GPU (overrides global discrete-GPU setting)") - - args = parser.parse_args() - - if not args.game: - print( - "Error: no game provided. Use --game <gameid>.", - file=sys.stderr, - ) - sys.exit(1) - - game = load_game_from_json(args.game) - if not game: - print( - f'Error: game "{args.game}" not found in games.json.', - file=sys.stderr, - ) - sys.exit(1) - handle_command(game, cmd_override=args.cmd, igpu=args.igpu) diff --git a/fungus/settings_dialog.py b/fungus/settings_dialog.py index 15a1df0..f04bb08 100644 --- a/fungus/settings_dialog.py +++ b/fungus/settings_dialog.py @@ -23,6 +23,9 @@ from fungus.umu_manager import ( check_and_install_if_needed, get_installed_umu_version, get_latest_umu_version, + get_steamrt_last_check, + proton_to_steamrt_variant, + save_steamrt_last_check, update_steam_runtime, ) @@ -150,6 +153,13 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): self.label_umu_runtime_status.set_max_width_chars(20) self.label_umu_runtime_status.set_ellipsize(Pango.EllipsizeMode.END) + self.label_umu_runtime_variant = Gtk.Label(label="Expected: steamrt3") + self.label_umu_runtime_variant.set_halign(Gtk.Align.START) + self.label_umu_runtime_variant.set_margin_start(10) + self.label_umu_runtime_variant.set_max_width_chars(20) + self.label_umu_runtime_variant.set_ellipsize(Pango.EllipsizeMode.END) + self.label_umu_runtime_variant.set_sensitive(False) # greyed out until runner selected + self.button_umu_runtime = Gtk.Button(label="Update Runtime") self.button_umu_runtime.set_image( Gtk.Image.new_from_icon_name("system-run-symbolic", Gtk.IconSize.BUTTON)) @@ -302,10 +312,18 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): grid_umu.attach(self.progress_umu, 0, 4, 2, 1) # Steam Runtime section + self.label_umu_runtime_last = Gtk.Label(label="Last checked: -") + self.label_umu_runtime_last.set_halign(Gtk.Align.START) + self.label_umu_runtime_last.set_margin_start(10) + self.label_umu_runtime_last.set_max_width_chars(30) + self.label_umu_runtime_last.set_ellipsize(Pango.EllipsizeMode.END) + grid_umu.attach(self.label_umu_runtime, 0, 5, 1, 1) - grid_umu.attach(self.label_umu_runtime_status, 0, 6, 1, 1) - grid_umu.attach(self.button_umu_runtime, 0, 7, 1, 1) - grid_umu.attach(self.progress_umu_runtime, 0, 8, 2, 1) + grid_umu.attach(self.label_umu_runtime_variant, 0, 6, 1, 1) + grid_umu.attach(self.label_umu_runtime_status, 0, 7, 1, 1) + grid_umu.attach(self.label_umu_runtime_last, 0, 8, 1, 1) + grid_umu.attach(self.button_umu_runtime, 0, 9, 1, 1) + grid_umu.attach(self.progress_umu_runtime, 0, 10, 2, 1) grid_miscellaneous.attach(self.checkbox_discrete_gpu, 0, 2, 1, 1) grid_miscellaneous.attach(self.checkbox_show_hidden, 0, 3, 1, 1) @@ -368,7 +386,9 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): self.box.add(box_bottom) self.populate_combobox_with_runners() + self.combobox_runner.connect("changed", self._on_runner_changed) self.load_config() + self._update_runtime_variant() self.show_all() self.progress_umu.set_visible(False) @@ -485,6 +505,21 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): from fungus.utils import populate_combobox_with_runners as _pop _pop(self.combobox_runner) + def _on_runner_changed(self, combobox): + """Handle runner selection change: update runtime variant display.""" + self._update_runtime_variant() + + def _update_runtime_variant(self): + """Update the runtime variant label based on the selected Proton runner.""" + runner = self.combobox_runner.get_active_text() + if runner: + variant = proton_to_steamrt_variant(runner) + self.label_umu_runtime_variant.set_text(f"Expected: {variant}") + self.label_umu_runtime_variant.set_sensitive(True) + else: + self.label_umu_runtime_variant.set_text("Expected: steamrt3") + self.label_umu_runtime_variant.set_sensitive(False) + def on_entry_changed(self, widget, entry): """Remove the 'required' CSS class once the entry has text.""" if entry.get_text(): @@ -695,7 +730,12 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): GLib.idle_add(self.progress_umu_runtime.set_fraction, percent / 100.0) GLib.idle_add(update_progress, "Updating…") - success, message = update_steam_runtime(runner, progress_callback=progress_cb) + def on_success(): + save_steamrt_last_check() + + success, message = update_steam_runtime( + runner, progress_callback=progress_cb, on_success=on_success + ) GLib.idle_add(self._on_runtime_done, success, message) threading.Thread(target=runtime_thread, daemon=True).start() @@ -797,6 +837,13 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): else: self.label_umu_installed.set_text("Not installed") + # Load Steam Runtime last-check time + last_check = get_steamrt_last_check() + if last_check: + self.label_umu_runtime_last.set_text(f"Last checked: {last_check}") + else: + self.label_umu_runtime_last.set_text("Last checked: -") + def load_liststore_from_file(self, filename=envar_dir): """Read environment variable lines from *filename* and populate the liststore.""" self.liststore.clear() diff --git a/fungus/umu_manager.py b/fungus/umu_manager.py index 68bfc4e..46feccc 100644 --- a/fungus/umu_manager.py +++ b/fungus/umu_manager.py @@ -6,13 +6,19 @@ locally installed version, and download/install the binary. """ import os +import re import subprocess import tarfile import tempfile from pathlib import Path +from collections.abc import Callable import requests +from fungus.logger import get_logger + +log = get_logger(__name__) + UMU_TAR_URL_TEMPLATE = ( "https://github.com/Open-Wine-Components/umu-launcher/releases/download/{}/umu-launcher-{}-zipapp.tar" ) @@ -22,6 +28,7 @@ xdg_data_home = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share")) UMU_INSTALL_DIR = os.path.join(xdg_data_home, "fungus-launcher") UMU_VERSION_FILE = os.path.join(UMU_INSTALL_DIR, "version.txt") UMU_BIN_PATH = os.path.join(UMU_INSTALL_DIR, "umu-run") +STEAMRT_CHECK_FILE = os.path.join(UMU_INSTALL_DIR, "steamrt.txt") # Path to the umu-run binary (may differ from UMU_BIN_PATH depending on deployment) def get_umu_run_path() -> str: @@ -30,25 +37,70 @@ def get_umu_run_path() -> str: return str(umu_run) +def extract_proton_version(proton_dir: str | None) -> str | None: + """Extract the major Proton version number from a directory name. + + Handles common naming conventions: + "Proton-11.0-1" → "11" + "Proton-10.0-1" → "10" + "GE-Proton11-1" → "11" + "GE-Proton10-1" → "10" + "GE-Proton9-11" → "9" + "EM-1.0" → "1" + + Returns ``None`` if the version cannot be parsed. + """ + name = proton_dir + if not name: + return None + + # Strip known prefixes + for prefix in ("GE-Proton", "Proton-", "EM-"): + if name.startswith(prefix): + name = name[len(prefix):] + break + + # Extract leading digits + match = re.match(r"(\d+)", name) + return match.group(1) if match else None + + +def proton_to_steamrt_variant(proton_dir: str | None) -> str: + """Return the expected Steam Runtime variant for a Proton directory name. + + Proton major version >= 11 uses steamrt4; everything else uses steamrt3. + Falls back to ``"steamrt3"`` when the version cannot be parsed. + """ + version = extract_proton_version(proton_dir) + if version is None: + return "steamrt3" + if int(version) >= 11: + return "steamrt4" + return "steamrt3" + """Return the path to the umu-run binary.""" + from fungus.constants import umu_run + return str(umu_run) + + def get_latest_umu_version() -> str | None: """Query the GitHub releases API for the latest UMU-Launcher tag. Returns the tag string (e.g. ``"1.21.4"``) or ``None`` on failure. """ try: - print(f"[UMU] Fetching latest version from {UMU_VERSION_API}") + log.debug("Fetching latest version from %s", UMU_VERSION_API) r = requests.get(UMU_VERSION_API, timeout=5) - print(f"[UMU] Response status: {r.status_code}") + log.debug("Response status: %d", r.status_code) if r.status_code == 200: releases = r.json() if releases: tag = releases[0]["tag_name"] - print(f"[UMU] Latest version: {tag}") + log.debug("Latest version: %s", tag) return tag - print("[UMU] No releases found") - print(f"[UMU] Unexpected status: {r.status_code}, body: {r.text[:200]}") + log.warning("No releases found") + log.warning("Unexpected status: %d, body: %s", r.status_code, r.text[:200]) except Exception as e: - print(f"[UMU] Error fetching version: {e}") + log.error("Error fetching version: %s", e) return None @@ -68,6 +120,40 @@ def is_umu_installed() -> bool: return os.path.isfile(UMU_BIN_PATH) and os.access(UMU_BIN_PATH, os.X_OK) +def get_steamrt_last_check() -> str | None: + """Read the last Steam Runtime update-check timestamp. + + Returns a human-readable string (e.g. ``"2025-07-01 14:30"``) or ``None`` + if the file does not exist or is empty. + """ + if os.path.exists(STEAMRT_CHECK_FILE): + try: + with open(STEAMRT_CHECK_FILE, encoding="utf-8") as f: + value = f.read().strip() + return value if value else None + except OSError: + return None + return None + + +def save_steamrt_last_check() -> bool: + """Write the current timestamp to the SteamRT last-check file. + + Returns ``True`` on success, ``False`` on failure. + """ + from datetime import datetime + + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M") + try: + os.makedirs(UMU_INSTALL_DIR, exist_ok=True) + with open(STEAMRT_CHECK_FILE, "w", encoding="utf-8") as f: + f.write(timestamp) + return True + except OSError as e: + log.error("Failed to save last-check timestamp: %s", e) + return False + + def download_umu_run(version: str, progress_callback=None) -> bool: """Download and install the UMU-Launcher binary from a tar archive. @@ -81,31 +167,31 @@ def download_umu_run(version: str, progress_callback=None) -> bool: Returns: ``True`` on success, ``False`` on failure. """ - print(f"[UMU] Installing version {version}") - print(f"[UMU] Install dir: {UMU_INSTALL_DIR}") - print(f"[UMU] Binary path: {UMU_BIN_PATH}") + log.info("Installing version %s", version) + log.debug("Install dir: %s", UMU_INSTALL_DIR) + log.debug("Binary path: %s", UMU_BIN_PATH) try: os.makedirs(UMU_INSTALL_DIR, exist_ok=True) - print(f"[UMU] Directory ready: {os.path.isdir(UMU_INSTALL_DIR)}") + log.debug("Directory ready: %s", os.path.isdir(UMU_INSTALL_DIR)) except OSError as e: - print(f"[UMU] Failed to create directory: {e}") + log.error("Failed to create directory: %s", e) return False url = UMU_TAR_URL_TEMPLATE.format(version, version) - print(f"[UMU] Download URL: {url}") + log.debug("Download URL: %s", url) try: r = requests.get(url, timeout=15, stream=True) - print(f"[UMU] Download response status: {r.status_code}") + log.debug("Download response status: %d", r.status_code) if r.status_code != 200: - print(f"[UMU] Response body: {r.text[:500]}") + log.warning("Response body: %s", r.text[:500]) return False except Exception as e: - print(f"[UMU] Download request failed: {e}") + log.error("Download request failed: %s", e) return False total = int(r.headers.get("content-length", 0)) - print(f"[UMU] Content-Length: {total}") + log.debug("Content-Length: %d", total) # Download tar to a temp file, then extract umu-run tmp_path = None @@ -119,13 +205,13 @@ def download_umu_run(version: str, progress_callback=None) -> bool: if progress_callback and total: progress_callback(int(downloaded / total * 100)) - print(f"[UMU] Downloaded {downloaded} bytes to temp file") + log.debug("Downloaded %d bytes to temp file", downloaded) # Extract umu-run from the tar archive with tarfile.open(tmp_path, "r:") as tar: member = tar.extractfile("umu/umu-run") if member is None: - print("[UMU] Could not find umu/umu-run in archive") + log.error("Could not find umu/umu-run in archive") os.remove(tmp_path) return False @@ -133,10 +219,10 @@ def download_umu_run(version: str, progress_callback=None) -> bool: f.write(member.read()) os.remove(tmp_path) - print(f"[UMU] Extracted umu-run from archive") + log.info("Extracted umu-run from archive") except Exception as e: - print(f"[UMU] Error during extraction: {e}") + log.error("Error during extraction: %s", e) # Clean up if tmp_path is not None: try: @@ -152,17 +238,17 @@ def download_umu_run(version: str, progress_callback=None) -> bool: try: os.chmod(UMU_BIN_PATH, 0o755) except OSError as e: - print(f"[UMU] Failed to set executable permission: {e}") + log.error("Failed to set executable permission: %s", e) return False try: with open(UMU_VERSION_FILE, "w", encoding="utf-8") as f: f.write(version) except OSError as e: - print(f"[UMU] Failed to write version file: {e}") + log.error("Failed to write version file: %s", e) return False - print(f"[UMU] Installed successfully, version written to {UMU_VERSION_FILE}") + log.info("Installed successfully, version written to %s", UMU_VERSION_FILE) return True @@ -180,25 +266,25 @@ def check_and_install_if_needed(progress_callback=None) -> tuple[bool, str]: ``"up_to_date"``, ``"updated"``, ``"installed"``, ``"failed"``. """ installed = is_umu_installed() - print(f"[UMU] Already installed: {installed}") + log.debug("Already installed: %s", installed) if installed: installed_version = get_installed_umu_version() latest = get_latest_umu_version() - print(f"[UMU] Installed version: {installed_version}") - print(f"[UMU] Latest version: {latest}") + log.debug("Installed version: %s", installed_version) + log.debug("Latest version: %s", latest) if latest is None: return (False, "failed") if installed_version == latest: - print("[UMU] Already up to date") + log.info("Already up to date") return (True, "up_to_date") - print(f"[UMU] Outdated: {installed_version} < {latest}, updating...") + log.info("Outdated: %s < %s, updating...", installed_version, latest) if download_umu_run(latest, progress_callback): return (True, "updated") return (False, "failed") latest = get_latest_umu_version() - print(f"[UMU] Latest version result: {latest}") + log.debug("Latest version result: %s", latest) if latest is None: return (False, "failed") @@ -210,12 +296,13 @@ def check_and_install_if_needed(progress_callback=None) -> tuple[bool, str]: def update_steam_runtime( protonpath: str, progress_callback=None, + on_success: Callable[[], None] | None = None, ) -> tuple[bool, str]: """Trigger the UMU Steam Runtime download/update for a given Proton path. Runs ``umu-run wineprefixcreate /usr/bin/true`` with the appropriate - ``PROTONPATH`` environment variable, which causes umu-run to download - and install the Steam Runtime (steamrt3) if missing. + ``PROTONPATH`` and ``PROTONVERSION`` environment variables, which causes + umu-run to download and install the correct Steam Runtime variant if missing. Args: protonpath: The Proton directory name (e.g. ``"Proton-9.0"``). @@ -235,6 +322,9 @@ def update_steam_runtime( env = os.environ.copy() env["GAMEID"] = "umu-update-handshake" env["PROTONPATH"] = str(proton_path) + proton_version = extract_proton_version(protonpath) + if proton_version: + env["PROTONVERSION"] = proton_version try: proc = subprocess.Popen( @@ -253,11 +343,13 @@ def update_steam_runtime( for raw_line in proc.stdout: line = raw_line.strip() if line: - print(f"[Runtime] {line}") + log.info("%s", line) if "Downloading" in line or "Extracting" in line: if progress_callback: progress_callback(50) elif "up to date" in line.lower(): + if on_success: + on_success() return (True, "Already up to date") proc.wait() @@ -265,9 +357,11 @@ def update_steam_runtime( if proc.returncode == 0: if progress_callback: progress_callback(100) + if on_success: + on_success() return (True, "Update OK") return (False, f"Update failed (exit code {proc.returncode})") except Exception as e: - print(f"[Runtime] Error: {e}") + log.error("Error: %s", e) return (False, str(e)) diff --git a/fungus/utils.py b/fungus/utils.py index 11813ec..e9ae9dc 100644 --- a/fungus/utils.py +++ b/fungus/utils.py @@ -14,6 +14,10 @@ import gi gi.require_version('Pango', '1.0') from gi.repository import Pango # type: ignore +from fungus.logger import get_logger + +log = get_logger(__name__) + # Re-export pure utilities so existing imports from fungus.utils continue # to work without breaking. from fungus.utils_pure import ( # noqa: F401 @@ -68,7 +72,7 @@ def populate_combobox_with_runners(combobox): combobox.append_text(version) except Exception as e: - print(f"Error accessing the directory: {e}") + log.error("Error accessing the directory: %s", e) if versions: combobox.set_active(0) diff --git a/scripts/check_handlers.py b/scripts/check_handlers.py index 24b550b..f888f19 100644 --- a/scripts/check_handlers.py +++ b/scripts/check_handlers.py @@ -13,10 +13,17 @@ Exit code 0 = clean, 1 = issues found. """ import ast +import logging import re import sys from pathlib import Path +logging.basicConfig( + format="[%(name)s] %(levelname)s %(message)s", + level=logging.INFO, + stream=sys.stderr, +) + # --------------------------------------------------------------------------- # AST-based class / method extraction (with inheritance resolution) @@ -206,11 +213,11 @@ def main(): all_errors.extend(errors) if all_errors: - print("\n".join(all_errors)) - print(f"\n--- {len(all_errors)} issue(s) found ---") + logging.error("\n".join(all_errors)) + logging.error("--- %d issue(s) found ---", len(all_errors)) sys.exit(1) else: - print("All connect() handlers and widget references validated successfully.") + logging.info("All connect() handlers and widget references validated successfully.") sys.exit(0) diff --git a/tests/test_proton_steamrt_mapping.py b/tests/test_proton_steamrt_mapping.py new file mode 100644 index 0000000..ec9f12f --- /dev/null +++ b/tests/test_proton_steamrt_mapping.py @@ -0,0 +1,82 @@ +"""Tests for proton-to-SteamRuntime version mapping helpers.""" + +from fungus.umu_manager import extract_proton_version, proton_to_steamrt_variant + + +class TestExtractProtonVersion: + """Tests for the extract_proton_version helper.""" + + def test_proton_official_11(self): + assert extract_proton_version("Proton-11.0-1") == "11" + + def test_proton_official_10(self): + assert extract_proton_version("Proton-10.0-1") == "10" + + def test_proton_official_9(self): + assert extract_proton_version("Proton-9.0-1") == "9" + + def test_ge_proton_11(self): + assert extract_proton_version("GE-Proton11-1") == "11" + + def test_ge_proton_10(self): + assert extract_proton_version("GE-Proton10-1") == "10" + + def test_ge_proton_9(self): + assert extract_proton_version("GE-Proton9-11") == "9" + + def test_em_proton(self): + assert extract_proton_version("EM-1.0") == "1" + + def test_empty_string(self): + assert extract_proton_version("") is None + + def test_none(self): + assert extract_proton_version(None) is None + + def test_unknown_prefix(self): + # Unknown prefixes are not stripped, so parsing fails + assert extract_proton_version("Unknown-5.0") is None + + def test_no_version_number(self): + assert extract_proton_version("Proton-") is None + + def test_ge_proton_no_number(self): + assert extract_proton_version("GE-Proton") is None + + +class TestProtonToSteamrtVariant: + """Tests for the proton_to_steamrt_variant helper.""" + + def test_proton_11(self): + assert proton_to_steamrt_variant("Proton-11.0-1") == "steamrt4" + + def test_proton_10(self): + assert proton_to_steamrt_variant("Proton-10.0-1") == "steamrt3" + + def test_proton_9(self): + assert proton_to_steamrt_variant("Proton-9.0-1") == "steamrt3" + + def test_ge_proton_11(self): + assert proton_to_steamrt_variant("GE-Proton11-1") == "steamrt4" + + def test_ge_proton_10(self): + assert proton_to_steamrt_variant("GE-Proton10-1") == "steamrt3" + + def test_ge_proton_9(self): + assert proton_to_steamrt_variant("GE-Proton9-11") == "steamrt3" + + def test_em_proton(self): + assert proton_to_steamrt_variant("EM-1.0") == "steamrt3" + + def test_empty_fallback(self): + assert proton_to_steamrt_variant("") == "steamrt3" + + def test_none_fallback(self): + assert proton_to_steamrt_variant(None) == "steamrt3" + + def test_unknown_prefix_fallback(self): + # Unknown prefix → no version extracted → falls back to steamrt3 + assert proton_to_steamrt_variant("Unknown-5.0") == "steamrt3" + + def test_no_version_fallback(self): + assert proton_to_steamrt_variant("Proton-") == "steamrt3" diff --git a/tests/test_steamrt_timestamp.py b/tests/test_steamrt_timestamp.py new file mode 100644 index 0000000..6437bb2 --- /dev/null +++ b/tests/test_steamrt_timestamp.py @@ -0,0 +1,79 @@ +"""Tests for fungus.umu_manager — Steam Runtime timestamp helpers.""" + + +import pytest + + +@pytest.fixture() +def tmp_steamrt_file(tmp_data_dir): + """Provide a temporary steamrt.txt path in the user data directory.""" + steamrt_dir = tmp_data_dir / "fungus-launcher" + steamrt_dir.mkdir(parents=True, exist_ok=True) + return steamrt_dir / "steamrt.txt" + + +@pytest.fixture() +def patched_steamrt_file(tmp_steamrt_file): + """Patch STEAMRT_CHECK_FILE to point to a temporary file.""" + from fungus import umu_manager as um + + original = um.STEAMRT_CHECK_FILE + um.STEAMRT_CHECK_FILE = str(tmp_steamrt_file) + + yield tmp_steamrt_file + + um.STEAMRT_CHECK_FILE = original + + +class TestGetSteamrtLastCheck: + def test_returns_none_when_file_missing(self, patched_steamrt_file): + # Ensure file does not exist + patched_steamrt_file.unlink(missing_ok=True) + from fungus.umu_manager import get_steamrt_last_check + + assert get_steamrt_last_check() is None + + def test_returns_timestamp_when_file_exists(self, patched_steamrt_file): + patched_steamrt_file.write_text("2025-07-01 14:30") + from fungus.umu_manager import get_steamrt_last_check + + assert get_steamrt_last_check() == "2025-07-01 14:30" + + def test_returns_none_when_file_empty(self, patched_steamrt_file): + patched_steamrt_file.write_text("") + from fungus.umu_manager import get_steamrt_last_check + + assert get_steamrt_last_check() is None + + def test_strips_whitespace(self, patched_steamrt_file): + patched_steamrt_file.write_text(" 2025-06-15 09:00 \n") + from fungus.umu_manager import get_steamrt_last_check + + assert get_steamrt_last_check() == "2025-06-15 09:00" + + +class TestSaveSteamrtLastCheck: + def test_writes_timestamp(self, patched_steamrt_file): + from fungus.umu_manager import save_steamrt_last_check + + result = save_steamrt_last_check() + assert result is True + content = patched_steamrt_file.read_text().strip() + # Should match YYYY-MM-DD HH:MM pattern + assert len(content) == 16 + assert content[4] == "-" + assert content[7] == "-" + assert content[10] == " " + assert content[13] == ":" + + def test_returns_false_on_write_failure(self, patched_steamrt_file): + from fungus import umu_manager as um + from fungus.umu_manager import save_steamrt_last_check as _save + + # Point to a non-writable location + um.STEAMRT_CHECK_FILE = "/root/steamrt.txt" + result = _save() + assert result is False + + # Restore + um.STEAMRT_CHECK_FILE = str(patched_steamrt_file) |
