#!/usr/bin/python3 """UMU-Launcher (umu-run) installation and update management. Provides functions to query the latest version from GitHub, check the 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" ) UMU_VERSION_API = "https://api.github.com/repos/Open-Wine-Components/umu-launcher/releases" 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: """Return the path to the umu-run binary.""" from fungus.constants import umu_run 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" 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: log.debug("Fetching latest version from %s", UMU_VERSION_API) r = requests.get(UMU_VERSION_API, timeout=5) log.debug("Response status: %d", r.status_code) if r.status_code == 200: releases = r.json() if releases: tag = releases[0]["tag_name"] log.debug("Latest version: %s", tag) return tag log.warning("No releases found") log.warning("Unexpected status: %d, body: %s", r.status_code, r.text[:200]) except Exception as e: log.error("Error fetching version: %s", e) return None def get_installed_umu_version() -> str | None: """Read the version file from the local UMU-Launcher installation. Returns the stored version string or ``None`` if not installed. """ if os.path.exists(UMU_VERSION_FILE): with open(UMU_VERSION_FILE, encoding="utf-8") as f: return f.read().strip() return None def is_umu_installed() -> bool: """Check whether the umu-run binary exists and is executable.""" 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. The release asset is a tar containing ``umu/umu-run``. We extract just the ``umu-run`` executable and place it at ``UMU_BIN_PATH``. Args: version: The tag to download (e.g. ``"1.4.0"``). progress_callback: Optional callable receiving ``percent: int``. Returns: ``True`` on success, ``False`` on failure. """ 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) log.debug("Directory ready: %s", os.path.isdir(UMU_INSTALL_DIR)) except OSError as e: log.error("Failed to create directory: %s", e) return False url = UMU_TAR_URL_TEMPLATE.format(version, version) log.debug("Download URL: %s", url) try: r = requests.get(url, timeout=15, stream=True) log.debug("Download response status: %d", r.status_code) if r.status_code != 200: log.warning("Response body: %s", r.text[:500]) return False except Exception as e: log.error("Download request failed: %s", e) return False total = int(r.headers.get("content-length", 0)) log.debug("Content-Length: %d", total) # Download tar to a temp file, then extract umu-run tmp_path = None try: with tempfile.NamedTemporaryFile(suffix=".tar", delete=False) as tmp: tmp_path = tmp.name downloaded = 0 for chunk in r.iter_content(chunk_size=8192): tmp.write(chunk) downloaded += len(chunk) if progress_callback and total: progress_callback(int(downloaded / total * 100)) 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: log.error("Could not find umu/umu-run in archive") os.remove(tmp_path) return False with open(UMU_BIN_PATH, "wb") as f: f.write(member.read()) os.remove(tmp_path) log.info("Extracted umu-run from archive") except Exception as e: log.error("Error during extraction: %s", e) # Clean up if tmp_path is not None: try: os.remove(tmp_path) except OSError: pass try: os.remove(UMU_BIN_PATH) except OSError: pass return False try: os.chmod(UMU_BIN_PATH, 0o755) except OSError as 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: log.error("Failed to write version file: %s", e) return False log.info("Installed successfully, version written to %s", UMU_VERSION_FILE) return True def check_and_install_if_needed(progress_callback=None) -> tuple[bool, str]: """Install or update the UMU-Launcher to the latest version. If the binary is not installed, it will be downloaded. If the installed version differs from the latest, it will be updated. Args: progress_callback: Optional callable receiving ``percent: int``. Returns: A tuple ``(success, status)`` where ``status`` is one of: ``"up_to_date"``, ``"updated"``, ``"installed"``, ``"failed"``. """ installed = is_umu_installed() log.debug("Already installed: %s", installed) if installed: installed_version = get_installed_umu_version() latest = get_latest_umu_version() log.debug("Installed version: %s", installed_version) log.debug("Latest version: %s", latest) if latest is None: return (False, "failed") if installed_version == latest: log.info("Already up to date") return (True, "up_to_date") 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() log.debug("Latest version result: %s", latest) if latest is None: return (False, "failed") if download_umu_run(latest, progress_callback): return (True, "installed") return (False, "failed") 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`` 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"``). progress_callback: Optional callable receiving ``percent: int``. Returns: A tuple ``(success, message)``. """ share_dir = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share")) proton_path = Path(share_dir) / "Steam/compatibilitytools.d" / protonpath if not proton_path.is_dir(): return (False, f"Proton path not found: {protonpath}") umu_run_path = get_umu_run_path() cmd = [umu_run_path, "wineprefixcreate", "/usr/bin/true"] 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( cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, text=True, ) if proc.stdout is None: proc.wait() return (False, "No output from umu-run") for raw_line in proc.stdout: line = raw_line.strip() if 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() 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: log.error("Error: %s", e) return (False, str(e))