diff options
| author | fox <fox@fakecake.org> | 2026-07-02 17:34:26 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-07-02 17:34:26 +0300 |
| commit | 66b57b1db58439caaa155ff98be4a3c8ca72b037 (patch) | |
| tree | 3cb7c2a8116701a5a19dfb44dadcc16704c0bade | |
| parent | a989b735bb4d00fb5f5c20fafdd5967b54d85959 (diff) | |
| parent | b8856837708279e98bc3a873b2cfa8a4416e5523 (diff) | |
| download | fungus-launcher-66b57b1db58439caaa155ff98be4a3c8ca72b037.tar.gz fungus-launcher-66b57b1db58439caaa155ff98be4a3c8ca72b037.tar.xz | |
Merge branch 'dev' into 'master'
legacy line See merge request git/fungus-launcher!29
| -rw-r--r-- | AGENTS.md | 3 | ||||
| -rw-r--r-- | fungus-proton-manager.py | 532 | ||||
| -rw-r--r-- | fungus/__init__.py | 5 | ||||
| -rw-r--r-- | fungus/app.py | 3 | ||||
| -rw-r--r-- | fungus/meson.build | 1 | ||||
| -rw-r--r-- | fungus/proton_manager.py | 427 | ||||
| -rw-r--r-- | fungus/run_manager.py | 3 | ||||
| -rw-r--r-- | fungus/settings_dialog.py | 2 | ||||
| -rw-r--r-- | fungus/utils.py | 75 |
9 files changed, 545 insertions, 506 deletions
diff --git a/AGENTS.md b/AGENTS.md index 7fc8300..4795e58 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1 +1,2 @@ -- after making any changes to Python code, invoke `ruff check .` and `pyright .`. +- after making any changes to Python code, invoke `ruff check .` and `pyright .`; +- when adding or removing .py files consider updating `meson.build` in the directory if required; diff --git a/fungus-proton-manager.py b/fungus-proton-manager.py index ebb7f53..090d747 100644 --- a/fungus-proton-manager.py +++ b/fungus-proton-manager.py @@ -1,71 +1,41 @@ #!/usr/bin/env python3 +"""Fungus Proton Manager — GTK UI for downloading / removing Proton versions.""" import os -import re -import json -import hashlib import threading -import time -import requests -import gi # type: ignore -import tarfile -import shutil -import platform -from pathlib import Path + +import gi # type: ignore gi.require_version("Gtk", "3.0") -from gi.repository import Gtk, GLib # type: ignore +from gi.repository import Gtk, GLib # type: ignore + from fungus.dark_theme import apply_dark_theme from fungus.path_manager import PathManager +from fungus.proton_manager import ( + RATE_LIMITED_MSG, + _cache_key, + _fetch_with_cache, + download_and_extract, + get_arch_asset, + get_cache_dir, + get_installed_path, + remove_path, +) -fungus_png = PathManager.get_icon('fungus-launcher.png') -STEAM_COMPATIBILITY_PATH = Path(PathManager.user_data("Steam/compatibilitytools.d")) - -# Determine the machine's native architecture for asset filtering. -MACHINE_ARCH = platform.machine().lower() # e.g. "x86_64", "aarch64" +fungus_png = PathManager.get_icon("fungus-launcher.png") -config_file_dir = PathManager.user_config('fungus-launcher/config.ini') -fungus_launcher_dir = PathManager.user_config('fungus-launcher') - -class ConfigManager: - def __init__(self): - self.default_config = {} - self.config = {} - self.load_config() - - def load_config(self): - if os.path.isfile(config_file_dir): - with open(config_file_dir) as f: - for line in f.read().splitlines(): - if '=' in line: - key, value = line.split('=', 1) - self.config[key.strip()] = value.strip().strip('"') - - updated = False - for key, default_value in self.default_config.items(): - if key not in self.config: - self.config[key] = default_value - updated = True - - if updated or not os.path.isfile(config_file_dir): - self.save_config() - - def save_config(self): - if not os.path.exists(fungus_launcher_dir): - os.makedirs(fungus_launcher_dir) - - with open(config_file_dir, 'w') as f: - for key, value in self.config.items(): - f.write(f'{key}={value}\n') class ProtonDownloader(Gtk.Dialog): + """GTK dialog for browsing, downloading, and removing Proton releases.""" + def __init__(self): super().__init__(title="Fungus Proton Manager (fork)") self.set_resizable(False) self.set_modal(True) self.set_icon_from_file(fungus_png) + # ── Layout ────────────────────────────────────────────────────── frame = Gtk.Frame() frame.set_margin_start(10) frame.set_margin_end(10) @@ -99,7 +69,7 @@ class ProtonDownloader(Gtk.Dialog): self.notebook.set_hexpand(True) frame.add(self.notebook) - # Tab 1: GE-Proton + # ── Tab 1: GE-Proton ──────────────────────────────────────────── self.grid_ge = Gtk.Grid() self.grid_ge.set_hexpand(True) self.grid_ge.set_row_spacing(5) @@ -125,7 +95,7 @@ class ProtonDownloader(Gtk.Dialog): tab_box_ge.show_all() self.notebook.append_page(scroll_ge, tab_box_ge) - # Tab 2: Proton-EM + # ── Tab 2: Proton-EM ──────────────────────────────────────────── self.grid_em = Gtk.Grid() self.grid_em.set_hexpand(True) self.grid_em.set_row_spacing(5) @@ -151,20 +121,15 @@ class ProtonDownloader(Gtk.Dialog): tab_box_em.show_all() self.notebook.append_page(scroll_em, tab_box_em) - self.load_config() self.show_all() self.progress_bar.set_visible(False) self.progress_label.set_visible(False) - # Fetch releases in a background thread to avoid blocking the UI. - threading.Thread(target=self._fetch_releases_async, daemon=True).start() - - # Show the bottom progress bar during the initial fetch. - GLib.idle_add(self._show_loading_state) - - # Add a refresh button to the action area. + # ── Refresh button ────────────────────────────────────────────── action_area = self.get_action_area() - self._refresh_button = Gtk.Button.new_from_icon_name("view-refresh-symbolic", Gtk.IconSize.BUTTON) + self._refresh_button = Gtk.Button.new_from_icon_name( + "view-refresh-symbolic", Gtk.IconSize.BUTTON + ) self._refresh_button.set_tooltip_text("Refresh releases list") self._refresh_button.connect("clicked", self._on_refresh_clicked) self._refresh_button.set_sensitive(False) @@ -173,6 +138,12 @@ class ProtonDownloader(Gtk.Dialog): action_area.pack_start(self._refresh_button, False, False, 0) self._refresh_button.show() + # ── Start background fetch ────────────────────────────────────── + threading.Thread(target=self._fetch_releases_async, daemon=True).start() + GLib.idle_add(self._show_loading_state) + + # ── Cache management ────────────────────────────────────────────── + def _clear_cache(self): """Remove cached release data for both upstreams.""" urls = [ @@ -180,7 +151,7 @@ class ProtonDownloader(Gtk.Dialog): "https://api.github.com/repos/Etaash-mathamsetty/Proton/releases", ] for url in urls: - cache_path = self._cache_dir / self._cache_key(url) + cache_path = get_cache_dir() / _cache_key(url) try: cache_path.unlink(missing_ok=True) print(f"[ProtonManager] Cache removed: {url}") @@ -193,79 +164,14 @@ class ProtonDownloader(Gtk.Dialog): self._clear_cache() self._show_loading_state() self._refresh_button.set_sensitive(False) - threading.Thread(target=self._fetch_releases_async, daemon=True).start() - - @property - def _cache_dir(self): - """Return the cache directory for proton release data.""" - cache = Path(fungus_launcher_dir) / "cache" - cache.mkdir(parents=True, exist_ok=True) - return cache - - CACHE_TTL = 3600 # 1 hour - - class RateLimitError(Exception): - """Raised when GitHub API returns a rate-limit response.""" - pass - - class RateLimited(Exception): - """Raised when all sources are rate-limited and no cache is available.""" - pass - - def _cache_key(self, url): - """Generate a safe cache filename from a URL.""" - h = hashlib.sha256(url.encode()).hexdigest()[:16] - return f"proton-releases-{h}.json" - - def _fetch_with_cache(self, url): - """Fetch releases from a URL, using cached data if still valid. - - Falls back to cache on network errors so the UI never stays blank. - """ - cache_path = self._cache_dir / self._cache_key(url) - now = time.time() + threading.Thread( + target=self._fetch_releases_async, daemon=True + ).start() - # Try to load valid cached data first. - if cache_path.exists(): - try: - with open(cache_path) as f: - entry = json.load(f) - if now - entry["time"] < self.CACHE_TTL: - print(f"[ProtonManager] Cache hit: {url}") - return entry["data"] - print(f"[ProtonManager] Cache expired: {url}") - except (json.JSONDecodeError, KeyError) as exc: - print(f"[ProtonManager] Corrupt cache, ignoring: {exc}") - - # Fetch fresh data. - print(f"[ProtonManager] Fetching: {url}") - try: - releases = self._fetch_releases_from_url(url) - except self.RateLimitError as exc: - print(f"[ProtonManager] Rate limited: {exc}") - # Fall back to cached data if available. - if cache_path.exists(): - try: - with open(cache_path) as f: - entry = json.load(f) - print(f"[ProtonManager] Using stale cache due to rate limit") - return entry["data"] - except (json.JSONDecodeError, KeyError): - pass - raise self.RateLimited() - - # 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)") - except OSError as exc: - print(f"[ProtonManager] Cache write failed: {exc}") - - return releases + # ── Loading / progress helpers ──────────────────────────────────── def _show_loading_state(self): - """Show the bottom progress bar with pulsing animation during the initial fetch.""" + """Show the bottom progress bar with pulsing animation during fetch.""" self.progress_label.set_text("Loading...") self.progress_label.set_visible(True) self.progress_bar.set_visible(True) @@ -285,66 +191,61 @@ class ProtonDownloader(Gtk.Dialog): return True return False + # ── Background fetch ────────────────────────────────────────────── + def _fetch_releases_async(self): - """Fetch releases from GitHub in a background thread, then update the UI.""" + """Fetch releases from GitHub in a background thread, then update UI.""" print("[ProtonManager] Starting async fetch...") try: - ge_releases = self._fetch_with_cache( + ge_releases = _fetch_with_cache( "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases", ) - em_releases = self._fetch_with_cache( + em_releases = _fetch_with_cache( "https://api.github.com/repos/Etaash-mathamsetty/Proton/releases", ) - print(f"[ProtonManager] GE-Proton: {len(ge_releases)}, Proton-EM: {len(em_releases)}") + print( + f"[ProtonManager] GE-Proton: {len(ge_releases)}, " + f"Proton-EM: {len(em_releases)}" + ) - # Schedule UI updates on the main thread. result = GLib.idle_add(self._render_releases, ge_releases, em_releases) print(f"[ProtonManager] GLib.idle_add returned: {result}") - except self.RateLimited: - print("[ProtonManager] Rate limited on all sources, no cache available") - GLib.idle_add(self._render_rate_limited) except Exception as e: - print(f"[ProtonManager] Exception in fetch thread: {e}") - import traceback - traceback.print_exc() + # RateLimited is caught here along with any other exception + print(f"[ProtonManager] Exception: {e}") GLib.idle_add(self._render_error, str(e)) - def _render_releases(self, ge_releases, em_releases): - """Populate the grids with release buttons (called on the main thread).""" - print(f"[ProtonManager] _render_releases called: GE={len(ge_releases)}, EM={len(em_releases)}") - print(f"[ProtonManager] Grids: grid_ge children={len(self.grid_ge.get_children())}, grid_em children={len(self.grid_em.get_children())}") + # ── UI rendering callbacks ──────────────────────────────────────── - # Remove loading labels and hide the bottom progress bar. + def _render_releases(self, ge_releases, em_releases): + """Populate the grids with release buttons (main thread).""" + # Remove loading labels and hide progress. if self._loading_label_ge.get_parent(): - print("[ProtonManager] Removing GE loading label") self.grid_ge.remove(self._loading_label_ge) if self._loading_label_em.get_parent(): - print("[ProtonManager] Removing EM loading label") self.grid_em.remove(self._loading_label_em) self._hide_loading_state() self._refresh_button.set_sensitive(True) if not ge_releases and not em_releases: - print("[ProtonManager] No releases to show") self._show_no_releases() return False for release in ge_releases: - print(f"[ProtonManager] Adding GE release: {release['tag_name']}") self.add_release_to_grid(release, self.grid_ge) for release in em_releases: - print(f"[ProtonManager] Adding EM release: {release['tag_name']}") self.add_release_to_grid(release, self.grid_em) - print(f"[ProtonManager] After render: grid_ge children={len(self.grid_ge.get_children())}, grid_em children={len(self.grid_em.get_children())}") - return False # do not repeat + return False def _render_error(self, error_msg): - """Show an error label in both grids (called on the main thread).""" + """Show an error label in both grids (main thread).""" self._hide_loading_state() self._refresh_button.set_sensitive(True) - for grid, label in [(self.grid_ge, self._loading_label_ge), - (self.grid_em, self._loading_label_em)]: + for grid, label in [ + (self.grid_ge, self._loading_label_ge), + (self.grid_em, self._loading_label_em), + ]: if label.get_parent(): grid.remove(label) err_label = Gtk.Label(label=f"Error: {error_msg}") @@ -352,27 +253,28 @@ class ProtonDownloader(Gtk.Dialog): err_label.set_valign(Gtk.Align.CENTER) grid.attach(err_label, 0, 0, 2, 1) err_label.show() - return False # do not repeat + return False def _render_rate_limited(self): - """Show a rate-limit message in both grids (called on the main thread).""" + """Show a rate-limit message in both grids (main thread).""" self._hide_loading_state() self._refresh_button.set_sensitive(True) - msg = "GitHub API rate limit reached. Please try again later or use the refresh button." - for grid, label in [(self.grid_ge, self._loading_label_ge), - (self.grid_em, self._loading_label_em)]: + for grid, label in [ + (self.grid_ge, self._loading_label_ge), + (self.grid_em, self._loading_label_em), + ]: if label.get_parent(): grid.remove(label) - rate_label = Gtk.Label(label=msg) + rate_label = Gtk.Label(label=RATE_LIMITED_MSG) rate_label.set_halign(Gtk.Align.CENTER) rate_label.set_valign(Gtk.Align.CENTER) rate_label.set_margin_top(20) grid.attach(rate_label, 0, 0, 2, 1) rate_label.show() - return False # do not repeat + return False def _show_no_releases(self): - """Show a 'no releases found' message when filtering yields nothing.""" + """Show a 'no releases found' message.""" no_release_msg = Gtk.Label(label="No releases found.") no_release_msg.set_halign(Gtk.Align.CENTER) no_release_msg.set_valign(Gtk.Align.CENTER) @@ -380,145 +282,15 @@ class ProtonDownloader(Gtk.Dialog): self.grid_em.attach(no_release_msg, 0, 0, 2, 1) no_release_msg.show() - def get_releases(self): - """Synchronous version kept for backwards compatibility.""" - self._fetch_releases_from_url( - "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases", - ) - self._fetch_releases_from_url( - "https://api.github.com/repos/Etaash-mathamsetty/Proton/releases", - ) - - def _get_arch_asset(self, assets): - """Find the best asset for the machine's architecture. - - GE-Proton naming conventions: - - Default (x86_64) build: ``GE-Proton11-1.tar.gz`` (no arch suffix) - - Explicit x86_64 build: ``GE-Proton11-1-x86_64.tar.gz`` - - aarch64 build: ``GE-Proton11-1-aarch64.tar.gz`` - - On x86_64 machines we want the default or ``-x86_64`` variant. - On aarch64 machines we want the ``-aarch64`` variant. - """ - # First pass: look for an exact arch match (e.g. ``-aarch64.tar.gz``). - for asset in assets: - name = asset["name"] - if not name.endswith((".tar.gz", ".tar.xz")): - continue - for ext in (".tar.xz", ".tar.gz"): - if name.endswith(ext): - stem = name[: -len(ext)] - break - else: - continue - if stem.endswith(MACHINE_ARCH): - print(f"[ProtonManager] Selected asset for arch {MACHINE_ARCH}: {name}") - return asset - - # Second pass (x86_64 only): the default build has no arch suffix. - if MACHINE_ARCH == "x86_64": - for asset in assets: - name = asset["name"] - if not name.endswith((".tar.gz", ".tar.xz")): - continue - # Avoid picking up ``-aarch64.tar.gz`` by checking stem. - for ext in (".tar.xz", ".tar.gz"): - if name.endswith(ext): - stem = name[: -len(ext)] - break - else: - continue - if not stem.endswith(MACHINE_ARCH) and not stem.endswith("aarch64"): - print(f"[ProtonManager] Selected default (x86_64) asset: {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}, falling back to: {asset['name']}") - return asset - return None - - def _fetch_releases_from_url(self, url): - """Fetch and filter releases from a GitHub API URL. Returns a list of release dicts.""" - page = 1 - releases = [] - seen_tags = set() - - while True: - response = requests.get( - url, params={"page": page, "per_page": 100}, timeout=15, - ) - if response.status_code == 200: - page_releases = response.json() - if not page_releases: - break - releases.extend(page_releases) - page += 1 - elif response.status_code == 403: - body = response.json() - if isinstance(body, dict) and "rate limit" in body.get("message", "").lower(): - raise self.RateLimitError("GitHub API rate limit exceeded") - break - else: - break - - print(f"[ProtonManager] Fetched {len(releases)} raw releases from {url}") - - filtered = [] - for release in releases: - tag_name = release["tag_name"] - if tag_name in seen_tags: - continue - seen_tags.add(tag_name) - - if "GloriousEggroll" in url: - if not tag_name.startswith("GE-Proton"): - print(f"[ProtonManager] Skipping {tag_name}: doesn't start with GE-Proton") - continue - try: - # Two formats: "GE-Proton-9.11-1" or "GE-Proton11-1" - # Extract the first two numbers after "GE-Proton" - 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") - 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") - continue - except Exception as exc: - print(f"[ProtonManager] Skipping {tag_name}: version parse error: {exc}") - continue - - elif "Etaash-mathamsetty" in url: - if not tag_name.startswith("EM-"): - print(f"[ProtonManager] Skipping {tag_name}: doesn't start with EM-") - continue - - assets = release.get("assets", []) - has_valid_asset = any( - asset["name"].endswith((".tar.gz", ".tar.xz")) - for asset in assets - ) - if not has_valid_asset: - print(f"[ProtonManager] Skipping {tag_name}: no tar.gz/tar.xz asset") - continue - - filtered.append(release) - - print(f"[ProtonManager] Filtered down to {len(filtered)} releases") - return filtered + # ── Release rendering ───────────────────────────────────────────── def add_release_to_grid(self, release, grid): tag_name = release["tag_name"] - display_tag_name = f"proton-{tag_name}" if tag_name.startswith("EM-") else tag_name - - print(f"[ProtonManager] add_release_to_grid: tag={tag_name}, display={display_tag_name}, grid_children={len(grid.get_children())}") + display_tag_name = ( + f"proton-{tag_name}" if tag_name.startswith("EM-") else tag_name + ) row_index = len(grid.get_children()) // 2 - print(f"[ProtonManager] row_index={row_index}") label = Gtk.Label(label=display_tag_name, xalign=0) label.set_halign(Gtk.Align.START) @@ -526,7 +298,7 @@ class ProtonDownloader(Gtk.Dialog): grid.attach(label, 0, row_index, 1, 1) label.show() - version_path = self.get_installed_path(display_tag_name) + version_path = get_installed_path(display_tag_name) is_installed = os.path.exists(version_path) button = Gtk.Button(label="Remove" if is_installed else "Download") @@ -535,30 +307,14 @@ class ProtonDownloader(Gtk.Dialog): grid.attach(button, 1, row_index, 1, 1) button.show() - def get_installed_path(self, tag_name): - tag_lower = tag_name.lower() - - if STEAM_COMPATIBILITY_PATH.exists(): - for folder in STEAM_COMPATIBILITY_PATH.iterdir(): - folder_name_lower = folder.name.lower() - if folder_name_lower.endswith(tag_lower): - return folder - if tag_lower.startswith("proton-"): - if folder_name_lower.endswith(tag_lower[len("proton-"):]): - return folder - - return STEAM_COMPATIBILITY_PATH / tag_name - - def update_button(self, button, new_label): - button.set_label(new_label) - button.set_sensitive(True) + # ── Button handlers ─────────────────────────────────────────────── def on_button_clicked(self, widget, release): tag_name = release["tag_name"] if tag_name.startswith("EM-"): tag_name = f"proton-{tag_name}" - version_path = self.get_installed_path(tag_name) + version_path = get_installed_path(tag_name) if os.path.exists(version_path): self.on_remove_clicked(widget, release) @@ -579,123 +335,58 @@ class ProtonDownloader(Gtk.Dialog): if isinstance(child, Gtk.Button): child.set_sensitive(True) + def _gtk_events_pending(self): + """Pump pending GTK events; always returns True to keep pumping.""" + while Gtk.events_pending(): + Gtk.main_iteration_do(False) + def on_download_clicked(self, widget, release): self.disable_all_buttons() - asset = self._get_arch_asset(release["assets"]) + asset = get_arch_asset(release["assets"]) if asset: - self.download_and_extract( + display_tag_name = ( + f"proton-{release['tag_name']}" + if release["tag_name"].startswith("EM-") + else release["tag_name"] + ) + widget.set_label("Downloading...") + self.progress_label.set_text(f"Downloading {display_tag_name}...") + self.progress_label.set_visible(True) + self.progress_bar.set_visible(True) + self.progress_bar.set_fraction(0) + widget.set_sensitive(False) + + download_and_extract( asset["browser_download_url"], asset["name"], release["tag_name"], - widget + progress_callback=lambda p: self.progress_bar.set_fraction(p / 100), + message_callback=self.progress_label.set_text, + pending_callback=self._gtk_events_pending, + button_update_callback=widget.set_label, + button_enable_callback=self.enable_all_buttons, ) + self.progress_bar.set_visible(False) + self.progress_label.set_visible(False) else: print(f"[ProtonManager] No suitable asset found for {release['tag_name']}") - self.update_button(widget, "Download") + widget.set_label("Download") + widget.set_sensitive(True) self.enable_all_buttons() - def download_and_extract(self, url, filename, tag_name, button): - button.set_label("Downloading...") - display_tag_name = f"proton-{tag_name}" if tag_name.startswith("EM-") else tag_name - self.progress_label.set_text("Downloading %s..." % display_tag_name) - self.progress_label.set_visible(True) - self.progress_bar.set_visible(True) - self.progress_bar.set_fraction(0) - button.set_sensitive(False) - - while Gtk.events_pending(): - Gtk.main_iteration_do(False) - - if not os.path.exists(STEAM_COMPATIBILITY_PATH): - os.makedirs(STEAM_COMPATIBILITY_PATH) - - response = requests.get(url, stream=True) - total_size = int(response.headers.get("content-length", 0)) - downloaded_size = 0 - - tar_file_path = os.path.join(os.getcwd(), filename) - with open(tar_file_path, "wb") as file: - for data in response.iter_content(1024): - file.write(data) - downloaded_size += len(data) - progress = downloaded_size / total_size if total_size > 0 else 0 - self.progress_bar.set_fraction(progress) - self.progress_bar.set_text(f"{int(progress * 100)}%") - - while Gtk.events_pending(): - Gtk.main_iteration_do(False) - file.flush() - os.fsync(file.fileno()) - - self.extract_tar_and_update_button(tar_file_path, tag_name, button) - - def extract_tar_and_update_button(self, tar_file_path, tag_name, button): - button.set_label("Extracting...") - display_tag_name = f"proton-{tag_name}" if tag_name.startswith("EM-") else tag_name - self.progress_label.set_text("Extracting %s..." % display_tag_name) - self.progress_bar.set_fraction(0) - self.progress_bar.set_text("0%") - - while Gtk.events_pending(): - Gtk.main_iteration_do(False) - - mode = 'r:xz' if tar_file_path.endswith('.tar.xz') else 'r:gz' - - try: - with tarfile.open(tar_file_path, mode) as tar: - total_members = len(tar.getmembers()) - extracted_members = 0 - - temp_dir = os.path.join(STEAM_COMPATIBILITY_PATH, f"temp_{tag_name}") - os.makedirs(temp_dir, exist_ok=True) - - for member in tar.getmembers(): - tar.extract(member, path=temp_dir, filter="fully_trusted") - extracted_members += 1 - progress = extracted_members / total_members - self.progress_bar.set_fraction(progress) - self.progress_bar.set_text(f"{int(progress * 100)}%") - - while Gtk.events_pending(): - Gtk.main_iteration_do(False) - - extracted_dir = None - for item in os.listdir(temp_dir): - item_path = os.path.join(temp_dir, item) - if os.path.isdir(item_path): - extracted_dir = item_path - break - - if extracted_dir: - final_dir = os.path.join(STEAM_COMPATIBILITY_PATH, os.path.basename(extracted_dir)) - if os.path.exists(final_dir): - shutil.rmtree(final_dir) - shutil.move(extracted_dir, STEAM_COMPATIBILITY_PATH) - - shutil.rmtree(temp_dir) + def on_remove_clicked(self, widget, release): + tag_name = release["tag_name"] + if tag_name.startswith("EM-"): + tag_name = f"proton-{tag_name}" - os.remove(tar_file_path) + version_path = get_installed_path(tag_name) + remove_path(version_path) + widget.set_label("Download") + widget.set_sensitive(True) - self.update_button(button, "Remove") - self.progress_bar.set_visible(False) - self.progress_label.set_visible(False) - except Exception as e: - print(f"Error during extraction: {e}") - self.progress_label.set_text("Error during extraction") - self.update_button(button, "Download") - finally: - self.enable_all_buttons() - button.set_sensitive(True) +# ── Main ────────────────────────────────────────────────────────────── - def on_remove_clicked(self, widget, release): - version_path = self.get_installed_path(release["tag_name"]) - if version_path and os.path.exists(version_path): - try: - shutil.rmtree(version_path) - self.update_button(widget, "Download") - except Exception: - pass def main(): apply_dark_theme() @@ -703,5 +394,6 @@ def main(): win.connect("destroy", Gtk.main_quit) Gtk.main() + if __name__ == "__main__": main() diff --git a/fungus/__init__.py b/fungus/__init__.py index 214843a..0c09fbd 100644 --- a/fungus/__init__.py +++ b/fungus/__init__.py @@ -21,13 +21,12 @@ __all__ = [ "icons_dir", "load_games_json", "save_games_json", - "update_game_field", - "update_games_and_config", + "update_game_field" ] __version__ = "0.1.0" -from fungus.app import FungusApp, update_games_and_config +from fungus.app import FungusApp from fungus.config_manager import ConfigManager from fungus.constants import ( fungus_version, diff --git a/fungus/app.py b/fungus/app.py index 3752710..91883bc 100644 --- a/fungus/app.py +++ b/fungus/app.py @@ -8,7 +8,6 @@ gi.require_version('Gdk', '3.0') from gi.repository import Gtk, Gio # type: ignore from fungus.dark_theme import apply_dark_theme -from fungus.utils import update_games_and_config class FungusApp(Gtk.Application): @@ -19,8 +18,6 @@ class FungusApp(Gtk.Application): ) self.window = None - update_games_and_config() - def do_startup(self): Gtk.Application.do_startup(self) os.environ["GTK_USE_PORTAL"] = "1" diff --git a/fungus/meson.build b/fungus/meson.build index aca84e8..9d3deb0 100644 --- a/fungus/meson.build +++ b/fungus/meson.build @@ -21,6 +21,7 @@ py.install_sources( 'main_window.py', 'path_manager.py', 'run_manager.py', + 'proton_manager.py', 'settings_dialog.py', 'umu_manager.py', 'utils.py', diff --git a/fungus/proton_manager.py b/fungus/proton_manager.py new file mode 100644 index 0000000..bd74b6e --- /dev/null +++ b/fungus/proton_manager.py @@ -0,0 +1,427 @@ +#!/usr/bin/env python3 +"""Core (non-UI) logic for managing Proton / GE-Proton / Proton-EM releases.""" + +__all__ = [ + "CACHE_TTL", + "MACHINE_ARCH", + "RATE_LIMITED_MSG", + "STEAM_COMPATIBILITY_PATH", + "RateLimitError", + "RateLimited", + "_cache_key", + "_fetch_with_cache", + "download_and_extract", + "fetch_releases", + "get_arch_asset", + "get_cache_dir", + "get_installed_path", + "remove_path", +] + +import hashlib +import json +import os +import platform +import re +import shutil +import tarfile +import time +from pathlib import Path + +import requests + +from fungus.path_manager import PathManager + +# --------------------------------------------------------------------------- +# Constants +# --------------------------------------------------------------------------- + +STEAM_COMPATIBILITY_PATH = Path(PathManager.user_data("Steam/compatibilitytools.d")) +MACHINE_ARCH = platform.machine().lower() # e.g. "x86_64", "aarch64" + +RATE_LIMITED_MSG = ( + "GitHub API rate limit reached. Please try again later or use the refresh button." +) + +# --------------------------------------------------------------------------- +# Exceptions +# --------------------------------------------------------------------------- + + +class RateLimitError(Exception): + """Raised when GitHub API returns a rate-limit response.""" + + pass + + +class RateLimited(Exception): + """Raised when all sources are rate-limited and no cache is available.""" + + pass + + +# --------------------------------------------------------------------------- +# Cache helpers +# --------------------------------------------------------------------------- + +CACHE_TTL = 3600 # 1 hour + + +def get_cache_dir(): + """Return the cache directory for proton release data.""" + cache = Path(PathManager.user_config("fungus-launcher")) / "cache" + cache.mkdir(parents=True, exist_ok=True) + return cache + + +def _cache_key(url): + """Generate a safe cache filename from a URL.""" + h = hashlib.sha256(url.encode()).hexdigest()[:16] + return f"proton-releases-{h}.json" + + +def _fetch_with_cache(url, cache_dir=None): + """Fetch releases from a URL, using cached data if still valid. + + Falls back to cache on network errors so callers never stay blank. + """ + if cache_dir is None: + cache_dir = get_cache_dir() + + cache_path = cache_dir / _cache_key(url) + now = time.time() + + # Try to load valid cached data first. + if cache_path.exists(): + try: + with open(cache_path) as f: + entry = json.load(f) + if now - entry["time"] < CACHE_TTL: + print(f"[ProtonManager] Cache hit: {url}") + return entry["data"] + print(f"[ProtonManager] Cache expired: {url}") + except (json.JSONDecodeError, KeyError) as exc: + print(f"[ProtonManager] Corrupt cache, ignoring: {exc}") + + # Fetch fresh data. + print(f"[ProtonManager] Fetching: {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)") + except OSError as exc: + print(f"[ProtonManager] Cache write failed: {exc}") + + return releases + + +# --------------------------------------------------------------------------- +# Release fetching & filtering +# --------------------------------------------------------------------------- + + +def fetch_releases(url): + """Fetch and filter releases from a GitHub API URL. + + Returns a list of release dicts. + """ + page = 1 + releases = [] + seen_tags = set() + + while True: + response = requests.get( + url, params={"page": page, "per_page": 100}, timeout=15, + ) + if response.status_code == 200: + page_releases = response.json() + if not page_releases: + break + releases.extend(page_releases) + page += 1 + elif response.status_code == 403: + body = response.json() + if isinstance(body, dict) and "rate limit" in body.get( + "message", "" + ).lower(): + raise RateLimitError("GitHub API rate limit exceeded") + break + else: + break + + print(f"[ProtonManager] Fetched {len(releases)} raw releases from {url}") + + filtered = [] + for release in releases: + tag_name = release["tag_name"] + if tag_name in seen_tags: + continue + seen_tags.add(tag_name) + + if "GloriousEggroll" in url: + if not tag_name.startswith("GE-Proton"): + print(f"[ProtonManager] Skipping {tag_name}: doesn't start with GE-Proton") + 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") + 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") + continue + except Exception as exc: + print(f"[ProtonManager] Skipping {tag_name}: version parse error: {exc}") + continue + + elif "Etaash-mathamsetty" in url: + if not tag_name.startswith("EM-"): + print(f"[ProtonManager] Skipping {tag_name}: doesn't start with EM-") + continue + + assets = release.get("assets", []) + has_valid_asset = any( + asset["name"].endswith((".tar.gz", ".tar.xz")) + for asset in assets + ) + if not has_valid_asset: + print(f"[ProtonManager] Skipping {tag_name}: no tar.gz/tar.xz asset") + continue + + filtered.append(release) + + print(f"[ProtonManager] Filtered down to {len(filtered)} releases") + return filtered + + +# --------------------------------------------------------------------------- +# Asset selection +# --------------------------------------------------------------------------- + + +def get_arch_asset(assets): + """Find the best asset for the machine's architecture. + + GE-Proton naming conventions: + - Default (x86_64) build: ``GE-Proton11-1.tar.gz`` (no arch suffix) + - Explicit x86_64 build: ``GE-Proton11-1-x86_64.tar.gz`` + - aarch64 build: ``GE-Proton11-1-aarch64.tar.gz`` + + On x86_64 machines we want the default or ``-x86_64`` variant. + On aarch64 machines we want the ``-aarch64`` variant. + """ + # First pass: look for an exact arch match. + for asset in assets: + name = asset["name"] + if not name.endswith((".tar.gz", ".tar.xz")): + continue + for ext in (".tar.xz", ".tar.gz"): + if name.endswith(ext): + stem = name[: -len(ext)] + break + else: + continue + if stem.endswith(MACHINE_ARCH): + print(f"[ProtonManager] Selected asset for arch {MACHINE_ARCH}: {name}") + return asset + + # Second pass (x86_64 only): the default build has no arch suffix. + if MACHINE_ARCH == "x86_64": + for asset in assets: + name = asset["name"] + if not name.endswith((".tar.gz", ".tar.xz")): + continue + for ext in (".tar.xz", ".tar.gz"): + if name.endswith(ext): + stem = name[: -len(ext)] + break + else: + continue + if not stem.endswith(MACHINE_ARCH) and not stem.endswith("aarch64"): + print(f"[ProtonManager] Selected default (x86_64) asset: {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']}" + ) + return asset + return None + + +# --------------------------------------------------------------------------- +# Install / removal +# --------------------------------------------------------------------------- + + +def get_installed_path(tag_name): + """Return the path where a Proton version is installed, or the expected path.""" + tag_lower = tag_name.lower() + + if STEAM_COMPATIBILITY_PATH.exists(): + for folder in STEAM_COMPATIBILITY_PATH.iterdir(): + folder_name_lower = folder.name.lower() + if folder_name_lower.endswith(tag_lower): + return folder + if tag_lower.startswith("proton-"): + if folder_name_lower.endswith(tag_lower[len("proton-"):]): + return folder + + return STEAM_COMPATIBILITY_PATH / tag_name + + +def remove_path(path): + """Remove a directory tree (used for uninstalling Proton versions).""" + if path and os.path.exists(path): + shutil.rmtree(path) + + +# --------------------------------------------------------------------------- +# Download & extraction +# --------------------------------------------------------------------------- + + +def download_and_extract( + url, + filename, + tag_name, + progress_callback=None, + progress_value_callback=None, + message_callback=None, + pending_callback=None, + button_update_callback=None, + button_enable_callback=None, +): + """Download and extract a Proton release archive. + + Parameters + ---------- + url : str + Direct download URL for the archive. + filename : str + Archive filename (used for the local temp file). + tag_name : str + Release tag name (used for display). + progress_callback : callable(int), optional + Called with 0-100 progress percentage during download/extraction. + progress_value_callback : callable(float), optional + Called with a 0.0-1.0 fraction during download/extraction. + message_callback : callable(str), optional + Called with status messages (e.g. "Downloading …"). + pending_callback : callable, optional + Called to pump GTK events while processing. + button_update_callback : callable(str), optional + Called with a new button label. + button_enable_callback : callable, optional + Called to re-enable all buttons. + """ + display_tag_name = f"proton-{tag_name}" if tag_name.startswith("EM-") else tag_name + + if message_callback: + message_callback(f"Downloading {display_tag_name}...") + if progress_callback: + progress_callback(0) + if progress_value_callback: + progress_value_callback(0.0) + + if not os.path.exists(STEAM_COMPATIBILITY_PATH): + os.makedirs(STEAM_COMPATIBILITY_PATH) + + response = requests.get(url, stream=True) + total_size = int(response.headers.get("content-length", 0)) + downloaded_size = 0 + + tar_file_path = os.path.join(os.getcwd(), filename) + with open(tar_file_path, "wb") as file: + for data in response.iter_content(1024): + file.write(data) + downloaded_size += len(data) + progress = downloaded_size / total_size if total_size > 0 else 0 + if progress_callback: + progress_callback(int(progress * 100)) + if progress_value_callback: + progress_value_callback(progress) + if pending_callback: + pending_callback() + file.flush() + os.fsync(file.fileno()) + + # Extraction + if message_callback: + message_callback(f"Extracting {display_tag_name}...") + if progress_callback: + progress_callback(0) + if progress_value_callback: + progress_value_callback(0.0) + if button_update_callback: + button_update_callback("Extracting...") + + while pending_callback and pending_callback(): + pass + + mode = "r:xz" if tar_file_path.endswith(".tar.xz") else "r:gz" + + try: + with tarfile.open(tar_file_path, mode) as tar: + total_members = len(tar.getmembers()) + extracted_members = 0 + + temp_dir = os.path.join(STEAM_COMPATIBILITY_PATH, f"temp_{tag_name}") + os.makedirs(temp_dir, exist_ok=True) + + for member in tar.getmembers(): + tar.extract(member, path=temp_dir, filter="fully_trusted") + extracted_members += 1 + progress = extracted_members / total_members + if progress_callback: + progress_callback(int(progress * 100)) + if progress_value_callback: + progress_value_callback(progress) + if pending_callback: + pending_callback() + + extracted_dir = None + for item in os.listdir(temp_dir): + item_path = os.path.join(temp_dir, item) + if os.path.isdir(item_path): + extracted_dir = item_path + break + + if extracted_dir: + final_dir = os.path.join( + STEAM_COMPATIBILITY_PATH, os.path.basename(extracted_dir) + ) + if os.path.exists(final_dir): + shutil.rmtree(final_dir) + shutil.move(extracted_dir, STEAM_COMPATIBILITY_PATH) + + shutil.rmtree(temp_dir) + + os.remove(tar_file_path) + + if button_update_callback: + button_update_callback("Remove") + if progress_callback: + progress_callback(100) + + except Exception as e: + print(f"Error during extraction: {e}") + if message_callback: + message_callback("Error during extraction") + if button_update_callback: + button_update_callback("Download") + finally: + if button_enable_callback: + button_enable_callback() + + + diff --git a/fungus/run_manager.py b/fungus/run_manager.py index fc96ee5..258d636 100644 --- a/fungus/run_manager.py +++ b/fungus/run_manager.py @@ -28,7 +28,7 @@ from fungus.constants import ( ) from fungus.game_model import Game, load_games_json, save_games_json from fungus.path_manager import PathManager -from fungus.utils import update_games_and_config, has_proton_installed, is_executable_in_whitelist +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) @@ -989,7 +989,6 @@ def main(): from fungus.dark_theme import apply_dark_theme apply_dark_theme() - update_games_and_config() parser = argparse.ArgumentParser(description=None) parser.add_argument("--game") diff --git a/fungus/settings_dialog.py b/fungus/settings_dialog.py index f84d1cc..15a1df0 100644 --- a/fungus/settings_dialog.py +++ b/fungus/settings_dialog.py @@ -225,10 +225,8 @@ class SettingsDialog(EntryTooltipMixin, Gtk.Dialog): self.box.set_vexpand(True) self.box.set_hexpand(True) - #url = f"https://github.com/Fungus/fungus-launcher/releases" label_version = Gtk.Label() label_version.set_text(fungus_version) - #label_version.set_use_markup(True) frame = Gtk.Frame() frame.set_label_widget(label_version) diff --git a/fungus/utils.py b/fungus/utils.py index 4cb56c9..5ad2523 100644 --- a/fungus/utils.py +++ b/fungus/utils.py @@ -1,6 +1,5 @@ #!/usr/bin/python3 -import json import os import re import unicodedata @@ -113,80 +112,6 @@ def _resolve_runner_to_directory(runner): return matches[0].name -def update_games_and_config(): - """Migrate games.json and config.ini to the latest schema. - - Handles runner-name renames, empty playtime normalisation, - and deprecated key removal. Called once at startup by both - the launcher (app.py) and the standalone runner (fungus_run.py). - - Note: This function intentionally works with raw dicts instead of - ``Game`` objects. It runs before any ``Game`` instances are - constructed and needs to touch fields that may not match the - current ``Game`` dataclass schema (e.g. deprecated keys). - """ - from fungus.constants import games_json, config_file_dir - - if os.path.exists(games_json): - try: - with open(games_json, encoding="utf-8") as f: - games = json.load(f) - except json.JSONDecodeError: - games = [] - - changed = False - - for game in games: - title = game.get("title", "") - if title: - formatted = format_title(title) - if game.get("gameid") != formatted: - game["gameid"] = formatted - changed = True - - if game.get("playtime", "") == "": - game["playtime"] = 0 - changed = True - - runner = game.get("runner") - # Migrate old-style runner names to actual directory names - if runner in ("Linux-Native", "Steam"): - del game["runner"] - elif runner is not None: - resolved = _resolve_runner_to_directory(runner) - if resolved and resolved != runner: - game["runner"] = resolved - changed = True - - if changed: - with open(games_json, "w", encoding="utf-8") as f: - json.dump(games, f, indent=4, ensure_ascii=False) - - config_path = Path(config_file_dir) - if not config_path.exists(): - return - - lines = config_path.read_text(encoding="utf-8").splitlines() - new_lines = [] - changed = False - - for raw_line in lines: - if raw_line.startswith("default-runner="): - value = raw_line.split("=", 1)[1].strip('"') - - resolved = _resolve_runner_to_directory(value) - if resolved and resolved != value: - new_lines.append(f'default-runner="{resolved}"') - changed = True - else: - # Keep as-is (including empty, Linux-Native, Steam — they pass through) - new_lines.append(raw_line) - else: - new_lines.append(raw_line) - - if changed: - config_path.write_text("\n".join(new_lines) + "\n", encoding="utf-8") - def populate_combobox_with_runners(combobox): """Populate a GTK ComboBoxText with available Proton/compatibility tool runners. |
