1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
|
#!/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))
|