fix: resolve zram focus conflicts

This commit is contained in:
Kurt Himebauch committed 2026-10-26 11:45:17 -04:00
commit 36135327f5
327 files changed
+20986 -2696

No files matched your search

+3
View File
@@ -12,6 +12,9 @@ export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
export MOZ_SHM_NO_SEALS=1
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
for conf in client client-rt; do
mkdir -p "/etc/pipewire/$conf.conf.d" && printf 'context.properties = {\n module.rt = false\n}\n' >"/etc/pipewire/$conf.conf.d/droiddeck-rt.conf"
done 2>/dev/null
export DROIDDECK_NESTED_SCALE=1
export DROIDDECK_GLTHREAD=${mesa_glthread:-}
unset MESA_LOADER_DRIVER_OVERRIDE LIBGL_KOPPER_DRI2 mesa_glthread
+25 -4
View File
@@ -6,21 +6,42 @@ if [ -n "${BL_DEBUG_DIR:-}" ]; then
fi
width=${BL_WIDTH:-1280}
height=${BL_HEIGHT:-720}
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
window=0
if [ "${BL_DESKTOP_GPU_WINDOW:-1}" != 0 ] && [ -n "${WAYLAND_DISPLAY:-}" ] && [ "$WAYLAND_DISPLAY" != wayland-0 ]; then
window=1
parent=$WAYLAND_DISPLAY
args=(--backend sdl --expose-wayland -W "$width" -H "$height" -w "$width" -h "$height")
else
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
fi
if [ "${BL_FPS:-0}" -gt 0 ]; then
args+=(-r "$BL_FPS")
elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
args+=(-r "$BL_REFRESH")
fi
[ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled)
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on wayland-0)"
export WAYLAND_DISPLAY=wayland-0
if [ "$window" = 1 ]; then
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} in a window on $parent)"
else
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on wayland-0)"
export WAYLAND_DISPLAY=wayland-0
fi
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND KWIN_COMPOSE
wsi=",${MESA_VK_WSI_DEBUG:-},"
while [[ $wsi == *,sw,* ]]; do wsi=${wsi//,sw,/,}; done
wsi=${wsi#,}; wsi=${wsi%,}
if [ -n "$wsi" ]; then export MESA_VK_WSI_DEBUG=$wsi; else unset MESA_VK_WSI_DEBUG; fi
export BL_DESKTOP_GPU_CHILD=1
export MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
[ -n "${DROIDDECK_GLTHREAD:-}" ] && export mesa_glthread=$DROIDDECK_GLTHREAD
export APPIMAGE_EXTRACT_AND_RUN=1
gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
if [ "$window" = 1 ]; then
export BL_GPU_CHILD_WSI=${MESA_VK_WSI_DEBUG:-}
SDL_VIDEODRIVER=wayland MESA_VK_WSI_DEBUG=sw gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
else
gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
fi
rc=$?
echo "== droiddeck-gpu $(date -u +%H:%M:%S): exited $rc"
exit $rc
@@ -0,0 +1,7 @@
#!/bin/sh
# Runs DroidDeck's bundled innoextract with its own boost libraries. The guest's
# env -i startup has no LD_LIBRARY_PATH, and the rootfs must not grow a second
# copy of boost for the installer fallback.
LD_LIBRARY_PATH=/usr/local/lib/droiddeck-inno
export LD_LIBRARY_PATH
exec /usr/local/lib/droiddeck-inno/innoextract "$@"
@@ -0,0 +1,23 @@
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,18 @@
Copyright (C) 2011-2020 Daniel Scharrer <daniel@constexpr.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the author(s) be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
File diff suppressed because it is too large. Load diff
@@ -3,6 +3,7 @@ set -u
export LANG=C.UTF-8
step() { echo "== STEP $*"; }
fail() { echo "== FAIL $*"; exit 1; }
[ "$(id -u)" = 0 ] || fail "needs root: install Flatpak from the launcher's Store, which runs this as root"
PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy"
while read -r pkg probe; do
@@ -48,10 +49,13 @@ if [ ! -f /etc/pacman.d/gnupg/pubring.gpg ] && [ ! -f /etc/pacman.d/gnupg/pubrin
fi
step "Reading the package lists"
pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy >/dev/null 2>&1 \
|| pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1 | tail -3 \
|| fail "could not reach the Arch Linux ARM mirrors"
[ -f "$WORK/db/sync/extra.db" ] || fail "could not reach the Arch Linux ARM mirrors"
sync_log=$(pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1) \
|| sync_log=$(pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1)
if [ ! -f "$WORK/db/sync/extra.db" ]; then
printf '%s\n' "$sync_log" | tail -3
reason=$(printf '%s\n' "$sync_log" | grep -m1 -i '^error' | cut -c1-160)
fail "could not reach the Arch Linux ARM mirrors${reason:+ ($reason)}"
fi
step "Downloading Flatpak"
out=$(pacman --config "$CONF" --dbpath "$WORK/db" --cachedir "$WORK/pkg" --noconfirm -Sw -dd $PACKAGES 2>&1)
@@ -122,12 +122,26 @@ def arkham_city_x87(game):
@fix
def protonfixes_off(game):
if game.stem in ("blackops3", "darksoulsremastered"):
return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)"
@fix
def caravan_sandwitch_feature_level(game):
if "caravansandwitch.exe" in game.files or game.stem == "caravansandwitch-win64-shipping":
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "Caravan SandWitch: D3D12 feature level 12_1 (12_2 hands it mesh shader pipelines vkd3d-proton cannot build)"
@fix
def robocop_rogue_city_feature_level(game):
"""vkd3d-proton turns mesh shaders off on Adreno, but 12_2 still advertises them, and UE5 then builds mesh
pipelines with no pipeline layout that crash Turnip on launch."""
if "robocop.exe" in game.files or game.stem == "robocop-win64-shipping":
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "RoboCop: Rogue City: D3D12 feature level 12_1"
@fix
def cyberpunk_feature_level(game):
if game.stem == "cyberpunk2077" or (
@@ -273,6 +287,58 @@ def game_gpu(env):
return result
def vram_cap(env):
"""Puts the session's VRAM cap ahead of the game's own DXVK settings, so a game profile can still raise it."""
value = env.get("BL_VRAM_MB", "")
if not re.fullmatch(r"[1-9][0-9]{0,6}", value):
return env
result = env.copy()
cap = "dxgi.maxDeviceMemory = %d" % int(value)
own = result.get("DXVK_CONFIG", "").strip().strip(";").strip()
result["DXVK_CONFIG"] = cap + "; " + own if own else cap
return result
def parse_cores(text):
"""CPU numbers from a list such as "0-3,6"; None when the text is not one."""
cores = set()
for part in text.replace(" ", "").split(","):
match = re.fullmatch(r"(\d{1,3})(?:-(\d{1,3}))?", part)
if not match:
return None
first, last = int(match.group(1)), int(match.group(2) or match.group(1))
if last < first:
return None
cores.update(range(first, last + 1))
return cores or None
def online_cores():
try:
with open("/sys/devices/system/cpu/online") as f:
cores = parse_cores(f.read().strip())
except OSError:
cores = None
return cores or os.sched_getaffinity(0) | set(range(os.cpu_count() or 0))
def game_cores(env):
"""Pins the game to the cores its profile names, in place of the session's game cores."""
text = env.get("DROIDDECK_GAME_CORES", "").strip()
if not text:
return
cores = parse_cores(text)
chosen = cores & online_cores() if cores else None
if not chosen:
print("droiddeck-game-env: ignoring game cores %r" % text, file=sys.stderr)
return
try:
os.sched_setaffinity(0, chosen)
print("droiddeck-game-env: game cores %s" % ",".join(map(str, sorted(chosen))), file=sys.stderr)
except OSError as error:
print("droiddeck-game-env: could not use game cores %r (%s)" % (text, error), file=sys.stderr)
def apply_config(env, config, app_id, fixes=None):
if config.get("version") != 1:
raise ValueError("unsupported environment configuration")
@@ -546,7 +612,9 @@ def main():
command = offline_without_anticheat(command, env)
if mic_enabled == "0":
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
env = vram_cap(env)
env = force_ssbs(command, env)
game_cores(env)
try:
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
except Exception as error:
@@ -45,6 +45,13 @@ def advertise_compositing():
if __name__ == '__main__':
if len(sys.argv) < 2:
raise SystemExit('usage: droiddeck-gpu-window <program> [args...]')
if 'BL_GPU_CHILD_WSI' in os.environ:
wsi = os.environ.pop('BL_GPU_CHILD_WSI')
if wsi:
os.environ['MESA_VK_WSI_DEBUG'] = wsi
else:
os.environ.pop('MESA_VK_WSI_DEBUG', None)
os.environ['SDL_VIDEODRIVER'] = 'x11'
os.environ.setdefault('GTK_CSD', '1')
try:
connection = advertise_compositing()
@@ -9,9 +9,9 @@ Add an app does) when that holds native programs or libraries. A Steam library's
droiddeck-open --exec FILE [ARGS...] an exec the kernel refused (libblsession)
droiddeck-open --install the Run entries and default handlers
The desktop composites in software, so a program started from it goes full screen on the GPU
(droiddeck-gpu), as the menu's games do: --window keeps it in a desktop window instead, --terminal
runs it in Konsole. A plain script stays on the desktop, and an exec whose output is read (a terminal,
The desktop composites in software, so a program started from it runs on the GPU in a window of its
own (droiddeck-gpu), as the menu's games do: --window keeps it on the desktop's software drawing
instead, --terminal runs it in Konsole. A plain script stays on the desktop, and an exec whose output is read (a terminal,
a pipe, a file) stays where it was started.
"""
import fcntl
@@ -337,7 +337,7 @@ def unattended(env):
def placed(cmd, what, mode, env):
"""[cmd] where it shows: full screen on the GPU from the desktop, else where it was started."""
"""[cmd] where it shows: on the GPU from the desktop, else where it was started."""
if mode == "terminal" and what not in ("windows", "steam") and shutil.which("konsole"):
return ["konsole", "--hold", "-e"] + cmd
if mode == "window" or what in ("script", "steam") or not on_desktop(env):
@@ -1,7 +1,7 @@
#!/usr/bin/python3
"""Runs a Windows program with the Proton the Steam client has chosen for it.
droiddeck-proton-run [--window] PROGRAM [ARGS...]
droiddeck-proton-run [--window] [--prefix ID] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]
droiddeck-proton-run --app ID [--dir FOLDER] [--options TEXT] [PROGRAM [ARGS...]]
The program belongs to an installed Steam game when it sits in one's folder, to a prefix when it
@@ -10,10 +10,15 @@ its own, under the id the client gives a new shortcut. That title's CompatToolMa
config.vdf picks the tool, else the client's default for all other titles ("0"). The tool is
started as the client starts it - its toolmanifest's command line, the waitforexitandrun verb and
the STEAM_COMPAT_* environment - so its wrapper applies the game's settings, components and audio.
--window keeps the program in the desktop's own window, drawn with WineD3D.
--window keeps the program in the desktop's own window, drawn with WineD3D on the desktop's software
GL (llvmpipe): KWin there composites in software, and the session's zink finds no device.
--prefix ID puts the program in compatdata/ID whatever it is. --verb run starts it beside what already
runs in the prefix, which waitforexitandrun would wait for; the wrapper's launch-time steps are skipped.
--game-id ID keeps the id of the launch it runs for: gamescope shows the windows that carry the id Steam launched.
--app starts one game without the Steam client (its Start without Steam): a Steam game's default
Windows launch option from appinfo.vdf when no program is given, else the program in that
shortcut's own prefix, started in --dir with the shortcut's launch options (--options).
shortcut's own prefix, started in --dir with the shortcut's launch options (--options). Without
--options it takes the launch options set in the client's Properties for that game or shortcut.
"""
import json
import os
@@ -30,7 +35,10 @@ BIN_DIR = os.path.dirname(os.path.abspath(__file__))
STATE = os.path.join(HOME, ".local", "share", "droiddeck-compat", "state.json")
EXTRA_LIBRARIES = ("/mnt/droiddeck", "/mnt/droiddeck-sd")
SYSTEM_TOOLS = ("/usr/share/steam/compatibilitytools.d", "/usr/local/share/steam/compatibilitytools.d")
DESKTOP_GL = {"LIBGL_ALWAYS_SOFTWARE": "1", "GALLIUM_DRIVER": "llvmpipe"}
NOT_DESKTOP_GL = ("MESA_LOADER_DRIVER_OVERRIDE", "LIBGL_KOPPER_DRI2")
VERB = "waitforexitandrun"
VERBS = (VERB, "run")
SHORTCUT_BIT = 0x80000000
STEAM_APP_LIMIT = 2 ** 31
@@ -185,9 +193,9 @@ def steam_game(program, libs):
def prefix_of(program):
for folder, below in ancestors(program):
parent = os.path.dirname(folder)
if below == "pfx" and os.path.basename(parent) == "compatdata" and os.path.basename(folder).isdigit():
if below == "pfx" and os.path.basename(parent) == "compatdata" and re.fullmatch(r"-?[0-9]+", os.path.basename(folder)):
library = os.path.dirname(os.path.dirname(parent))
return Target(os.path.basename(folder), folder, os.path.dirname(program), library, "prefix")
return Target(str(int(os.path.basename(folder)) % 2 ** 32), folder, os.path.dirname(program), library, "prefix")
return None
@@ -230,10 +238,68 @@ def shortcut_entries(root):
return entries
def prefix_folder(root, appid):
"""The prefix folder the client made for [appid], under either spelling of the id."""
folder = os.path.join(root, "steamapps", "compatdata")
try:
names = sorted(os.listdir(folder))
except OSError:
names = []
candidates = []
for name in names:
if not re.fullmatch(r"-?[0-9]+", name):
continue
try:
matches = int(name) % 2 ** 32 == appid % 2 ** 32
except ValueError:
continue
match = os.path.join(folder, name)
if matches and os.path.isdir(match):
candidates.append((os.path.isdir(os.path.join(match, "pfx")),
name == str(appid % 2 ** 32), name, match))
if candidates:
return min(candidates, key=lambda item: (not item[0], not item[1], item[2]))[3]
return os.path.join(folder, str(appid % 2 ** 32))
def vdf_string(token):
return re.sub(r'\\(.)', r'\1', token[1:-1]) if token.startswith('"') else ""
def steam_options(app, root):
"""The launch options the client keeps for a game (localconfig.vdf) or a shortcut (shortcuts.vdf)."""
try:
tool = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-steam-shortcuts"))
account = tool["account_dir"](root)
if not account:
return ""
if int(app) >= STEAM_APP_LIMIT:
with open(os.path.join(account, "config", "shortcuts.vdf"), "rb") as f:
shortcuts = tool["parse"](f.read()).get("shortcuts", {})
for value in shortcuts.values():
if isinstance(value, dict) and (value.get("appid", value.get("AppId")) or 0) & 0xFFFFFFFF == int(app):
options = value.get("LaunchOptions", value.get("launchoptions", ""))
return options if isinstance(options, str) else ""
return ""
tokens = compat()["tokenize"](read_text(os.path.join(account, "config", "localconfig.vdf")) or "")
start = compat()["find_block"](tokens, ["UserLocalConfigStore", "Software", "Valve", "Steam", "apps", app])
if start is None:
return ""
end, depth = compat()["block_end"](tokens, start), 0
for i in range(start + 1, end):
if tokens[i] in ("{", "}"):
depth += 1 if tokens[i] == "{" else -1
elif depth == 0 and tokens[i].lower() == '"launchoptions"' and i + 1 < end:
return vdf_string(tokens[i + 1])
except (OSError, ValueError, IndexError, KeyError, TypeError, AttributeError, struct.error):
pass
return ""
def shortcut(program, root):
for appid, exe, start in shortcut_entries(root):
if same_file(program, exe):
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)),
return Target(appid, prefix_folder(root, appid),
os.path.dirname(program), root, "shortcut", start if os.path.isdir(start) else None)
return None
@@ -250,10 +316,19 @@ def locate(program, root):
if found:
return found
appid = own_id(program)
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)),
return Target(appid, prefix_folder(root, appid),
os.path.dirname(program), root, "own")
def fixed(program, root, appid):
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)),
os.path.dirname(program), root, "fixed")
def prefix_id(value):
return value if value.isdigit() and not value.startswith("0") and int(value) <= 0xFFFFFFFF else None
def split_words(text):
try:
return shlex.split(text or "")
@@ -325,7 +400,8 @@ def steam_launch(appid, root):
def shortcut_target(appid, program, start, root):
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), os.path.dirname(program), root,
appid = int(appid) % 2 ** 32
return Target(str(appid), prefix_folder(root, appid), os.path.dirname(program), root,
"shortcut", start if start and os.path.isdir(start) else None)
@@ -337,7 +413,7 @@ def steam_launches(target, program, root):
return os.path.relpath(program, target.install).replace(os.sep, "/").lower() in entry.get("launch", ())
def environment(env, target, tool_folder, root, window=False):
def environment(env, target, tool_folder, root, window=False, game_id=None):
env = dict(env)
steamapps = [os.path.join(lib, "steamapps") for lib in libraries(root)]
env.update({
@@ -355,28 +431,52 @@ def environment(env, target, tool_folder, root, window=False):
else:
game = str(number << 32 | 0x02000000)
env.update(SteamAppId="0", STEAM_COMPAT_APP_ID="0", SteamGameId=game, SteamOverlayGameId=game)
if game_id:
env.update(SteamGameId=game_id, SteamOverlayGameId=game_id)
if window:
env.setdefault("PROTON_USE_WINED3D", "1")
env.update(DESKTOP_GL)
for name in NOT_DESKTOP_GL:
env.pop(name, None)
return env
def windows_path(path):
def windows_path(path, compatdata=None):
if compatdata:
drive = os.path.join(compatdata, "pfx", "drive_c")
inside = os.path.relpath(path, drive)
if inside != "." and not inside.startswith(".."):
return "C:\\" + inside.replace("/", "\\")
return "Z:" + path.replace("/", "\\")
def arguments(program, args):
def arguments(program, args, desktop=None, compatdata=None):
if program.lower().endswith(".msi"):
return ["msiexec", "/i", windows_path(program)] + args
if desktop:
return ["explorer.exe", "/desktop=droiddeck,%s" % desktop, windows_path(program, compatdata)] + args
return [program] + args
def main(argv):
window = False
app, start, options = None, None, ""
prefix = None
verb = VERB
game_id = None
desktop = None
app, start, options = None, None, None
while argv and argv[0].startswith("--"):
option = argv.pop(0)
if option == "--window":
window = True
elif option == "--prefix" and argv and prefix_id(argv[0]):
prefix = argv.pop(0)
elif option == "--verb" and argv and argv[0] in VERBS:
verb = argv.pop(0)
elif option == "--game-id" and argv and argv[0].isdigit() and argv[0] != "0":
game_id = argv.pop(0)
elif option == "--desktop" and argv and re.fullmatch(r"[1-9][0-9]{2,4}x[1-9][0-9]{2,4}", argv[0]):
desktop = argv.pop(0)
elif option in ("--app", "--dir", "--options") and argv:
value = argv.pop(0)
if option == "--app":
@@ -394,9 +494,11 @@ def main(argv):
say("%s is not an app id" % app)
return 2
if not argv and app is None:
say("usage: droiddeck-proton-run [--window] PROGRAM [ARGS...]")
say("usage: droiddeck-proton-run [--window] [--prefix ID] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]")
return 2
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or STEAM_ROOT
if options is None:
options = steam_options(app, root) if app is not None else ""
extra, args = split_options(options)
if not argv:
if int(app) >= STEAM_APP_LIMIT:
@@ -416,6 +518,8 @@ def main(argv):
args = args + argv[1:]
if app is not None and int(app) >= STEAM_APP_LIMIT:
target = shortcut_target(app, program, start, root)
elif prefix:
target = fixed(program, root, prefix)
else:
target = locate(program, root)
available = tools(root)
@@ -425,7 +529,7 @@ def main(argv):
return 69
folder, command = available[name]
os.makedirs(target.compatdata, exist_ok=True)
env = environment(os.environ, target, folder, root, window)
env = environment(os.environ, target, folder, root, window, game_id)
env.update(extra)
say("%s with %s (%s), %s prefix %s%s" % (program, name, why, target.kind, target.compatdata,
", without the Steam client" if app is not None else ""))
@@ -434,7 +538,7 @@ def main(argv):
except OSError:
os.chdir(os.path.dirname(program))
entry = os.path.join(folder, command)
os.execve(entry, [entry, VERB] + arguments(program, args), env)
os.execve(entry, [entry, verb] + arguments(program, args, desktop, target.compatdata), env)
if __name__ == "__main__":
@@ -16,7 +16,7 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
fi
exec > >({ dd of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
echo "== droiddeck-session $(date) mode=$mode $*"
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} fps=${BL_FPS:-0} icd=${VK_ICD_FILENAMES:-none}"
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
fi
@@ -211,13 +211,19 @@ if [ -z "${BL_INSIDE:-}" ]; then
width=${BL_WIDTH:-1280}
height=${BL_HEIGHT:-720}
nested=$width
nested_h=$height
if [ "${BL_FOLLOW_OUTPUT:-0}" = 1 ]; then
echo "== gamescope: the output follows the screen (${width}x${height} to start)"
elif [ "$mode" = steam ] && [ "${BL_GAMESCOPE_STRETCH_16X9:-0}" = 1 ]; then
wide=$(( (height * 16 + 4) / 9 / 2 * 2 ))
tall=$(( (width * 9 + 8) / 16 / 2 * 2 ))
if [ "$wide" -gt "$width" ]; then
nested=$wide
echo "== gamescope: games at ${nested}x${height} stretched to the ${width}x${height} output"
elif [ "$tall" -gt "$height" ]; then
nested_h=$tall
fi
if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then
echo "== gamescope: games at ${nested}x${nested_h} stretched to the ${width}x${height} output"
fi
fi
# Off unless Performance asks for it. Compositing the cursor here adds a second
@@ -225,11 +231,12 @@ if [ -z "${BL_INSIDE:-}" ]; then
if [ "$mode" = steam ] && [ "${BL_CURSOR_COMPOSITE:-0}" = 1 ]; then
export gamescope_cursor_composite=2
fi
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
[ "$nested" != "$width" ] && args+=(-S stretch) && export BL_STRETCHED=1
if [ "${BL_FPS:-0}" -gt 0 ]; then
args+=(-r "$BL_FPS")
elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then
args+=(-S stretch)
export BL_STRETCHED=1
fi
if [ "${BL_REFRESH:-0}" -gt 0 ]; then
args+=(-r "$BL_REFRESH")
fi
[ "$mode" = steam ] && [ "${BL_STEAM_UI:-}" != desktop ] && args+=(-e)
@@ -249,6 +256,10 @@ if [ -z "${BL_INSIDE:-}" ]; then
echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)"
fi
export BL_INSIDE=1
# A fixed path: left to itself gamescope creates a new limiter state file on every start.
rm -f "${XDG_RUNTIME_DIR:-/tmp}"/gamescope-limiter-*
export GAMESCOPE_LIMITER_FILE="${XDG_RUNTIME_DIR:-/tmp}/droiddeck-gamescope-limiter"
rm -f "$GAMESCOPE_LIMITER_FILE"
if [ "$mode" = steam ]; then
if /usr/local/bin/droiddeck-pipewire start; then
eval "$(/usr/local/bin/droiddeck-pipewire env)"
@@ -446,11 +457,19 @@ case $mode in
fi
if [ "${BL_ZRAM:-0}" = 1 ]; then
step "zRAM compression: on"
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam is not compressed while games run (turned off in Performance)"
_bl_ram_cap=0
case ${BL_RAM_CAP_MB:-} in
''|0) ;;
*[!0-9]*|0*|???????*) step "RAM cap: ignored invalid value '$BL_RAM_CAP_MB'" ;;
*) _bl_ram_cap=$((BL_RAM_CAP_MB * 1024)); step "RAM cap: ${BL_RAM_CAP_MB} MB" ;;
esac
(
bl_zram_scan() {
_bl_game=0 _bl_pids=() _bl_apps=
_bl_game=0 _bl_pids=() _bl_others=() _bl_apps=
local _d _c _args _name _a _id
for _d in /proc/[0-9]*; do
[ "${_d##*/}" != "$BASHPID" ] || continue
_args=()
# Under FEX the program is FEX's first argument. AppId= is its own argument.
while IFS= read -r -d '' _c; do _args+=("$_c"); done 2>/dev/null < "$_d/cmdline" || true
@@ -472,30 +491,67 @@ case $mode in
done
;;
steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;;
*) _bl_others+=("${_d##*/}") ;;
esac
done
}
bl_zram_usage() {
local _p _k _v _u _rss=0 _swap=0
for _p in "${_bl_pids[@]}"; do
for _p in "$@"; do
while read -r _k _v _u; do
case $_k in VmRSS:) _rss=$((_rss + _v)) ;; VmSwap:) _swap=$((_swap + _v)) ;; esac
done 2>/dev/null < "/proc/$_p/status"
done
echo "${#_bl_pids[@]} processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
_bl_rss=$_rss
echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
}
# Only processes that loaded libblsession are the session's own and answer SIGURG.
bl_session_others() {
local _p
_bl_session=()
for _p in "${_bl_others[@]}"; do
grep -q -m1 '/libblsession\.so$' "/proc/$_p/maps" 2>/dev/null && _bl_session+=("$_p")
done
}
bl_zram_pick() {
if [ "$1" = session ]; then
bl_session_others
_pids=("${_bl_session[@]}")
else
_pids=("${_bl_pids[@]}")
fi
}
# Same protocol as SessionSuspendController: an empty ack when the page-out starts, a byte when it is done.
# A process whose SIGURG handler was replaced never acks, so it is not waited for after the first 2 s.
bl_zram_wait() {
local _p _left _start=$SECONDS
while [ $((SECONDS - _start)) -lt 12 ]; do
_left=0
for _p in "$@"; do
[ -s "/tmp/.bl-zram.ack.$_p" ] && continue
[ -d "/proc/$_p" ] || continue
[ $((SECONDS - _start)) -ge 2 ] && [ ! -e "/tmp/.bl-zram.ack.$_p" ] && continue
_left=1
done
[ "$_left" = 1 ] || break
nap 0.2
done
for _p in "$@"; do rm -f "/tmp/.bl-zram.ack.$_p"; done
}
bl_zram_send() {
step "zRAM: $2 ($(bl_zram_usage))"
printf '%s' "$1" > /tmp/.bl-zram
[ "${#_bl_pids[@]}" = 0 ] || kill -URG "${_bl_pids[@]}" 2>/dev/null
nap 5
local _mode=$1 _what=$2 _which=$3 _pids _p
bl_zram_pick "$_which"
step "zRAM: $_what ($(bl_zram_usage "${_pids[@]}"))"
for _p in "${_pids[@]}"; do rm -f "/tmp/.bl-zram.ack.$_p"; done
printf '%s' "$_mode" > /tmp/.bl-zram
[ "${#_pids[@]}" = 0 ] || kill -URG "${_pids[@]}" 2>/dev/null
if [ "$_mode" = 1 ]; then bl_zram_wait "${_pids[@]}"; else nap 5; fi
bl_zram_scan
step "zRAM: done ($(bl_zram_usage))"
bl_zram_pick "$_which"
step "zRAM: done ($(bl_zram_usage "${_pids[@]}"))"
}
# Proton's reaper exists before the game window does, and compressing then stalls the
# launch. focusedApp uses the same 32-bit id as that reaper's AppId= (769 is Steam; a
# shortcut's CGameID keeps this id in its high half). The clock starts on a match, then
# waits 20 s more. Desktop Steam never writes focus.json, so the game process is enough.
# Proton starts its reaper before the game window; compressing during launch stalls it.
# Desktop Steam has no focus.json, so it still uses the game process as its trigger.
bl_game_focused() {
if [ "${BL_DESKTOP:-}" = 1 ] || [ -z "${BL_LAUNCH_DIR:-}" ]; then
return 0
@@ -509,18 +565,58 @@ case $mode in
esac
return 1
}
_bl_since=-1 _bl_packed=-1
bl_over_cap() {
[ "$_bl_ram_cap" -gt 0 ] || return 1
_bl_measured=$SECONDS
bl_session_others
bl_zram_usage "${_bl_pids[@]}" "${_bl_session[@]}" > /dev/null
[ "$_bl_rss" -gt "$_bl_ram_cap" ]
}
bl_cap_due() {
[ "$_bl_ram_cap" -gt 0 ] && { [ "$_bl_measured" -lt 0 ] || [ $((SECONDS - _bl_measured)) -ge 30 ]; }
}
_bl_since=-1 _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30
while kill -0 $$ 2>/dev/null; do
bl_zram_scan
if bl_cap_due; then
if bl_over_cap; then
# A cap below the game's working set cannot be met; paging out again every 30 s only churns.
if [ "$_bl_capped" -lt 0 ] || [ $((SECONDS - _bl_capped)) -ge "$_bl_backoff" ]; then
bl_zram_usage "${_bl_pids[@]}" > /dev/null
if [ "$_bl_rss" -ge $((512 * 1024)) ]; then
bl_zram_send 1 "over the ${BL_RAM_CAP_MB} MB RAM cap, compressing the client" client
[ "$_bl_game" = 1 ] && _bl_packed=$SECONDS
else
step "RAM cap: over, client already small ($((_bl_rss / 1024)) MB resident), skipping it"
fi
bl_over_cap && bl_zram_send 1 "still over the RAM cap, compressing the rest of the session" session
if bl_over_cap; then
_bl_backoff=$((_bl_backoff * 2 > 600 ? 600 : _bl_backoff * 2))
step "RAM cap: still over after paging out, next try in ${_bl_backoff} s"
else
_bl_backoff=30
fi
_bl_capped=$SECONDS
fi
else
_bl_backoff=30
if [ "$_bl_unpack" = 1 ] && [ "$_bl_game" = 0 ]; then
bl_zram_send 0 "back under the RAM cap, reading the client back" client
_bl_unpack=0
fi
fi
fi
if [ "$_bl_game" = 1 ] && bl_game_focused; then
[ "$_bl_since" -ge 0 ] || _bl_since=$SECONDS
if [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] &&
if [ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] &&
{ [ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 300 ]; }; then
bl_zram_send 1 "compressing the client"
bl_zram_send 1 "compressing the client" client
_bl_packed=$SECONDS
fi
elif [ "$_bl_game" != 1 ]; then
[ "$_bl_packed" -lt 0 ] || bl_zram_send 0 "game closed, reading the client back"
if [ "$_bl_packed" -ge 0 ]; then
if bl_over_cap; then _bl_unpack=1; else bl_zram_send 0 "game closed, reading the client back" client; _bl_unpack=0; fi
fi
_bl_since=-1 _bl_packed=-1
else
_bl_since=-1
@@ -843,7 +939,11 @@ BUSCONF
echo "== steam: devtools port $BL_CDP_PORT, guest processes only"
fi
[ -n "${BL_LAUNCH_DIR:-}" ] && mkdir -p "$BL_LAUNCH_DIR/agent" && echo "$BL_CDP_PORT" > "$BL_LAUNCH_DIR/agent/cdp-port"
[ "$steam_x64" = 1 ] || { "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 & }
if [ "$steam_x64" = 1 ]; then
{ droiddeck-steam-compat --files-only "$steam_root" 2>&1 & }
else
{ "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 & }
fi
_bl_ui=(-gamepadui)
[ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=()
_bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle=vulkan)
@@ -620,10 +620,11 @@ class Watcher:
class Helper:
def __init__(self, steam_root, port, steamos=False):
def __init__(self, steam_root, port, steamos=False, files_only=False):
self.steam_root = steam_root
self.port = port
self.steamos = steamos
self.files_only = files_only
self.page = None
self.known = set()
self.installed = None
@@ -647,9 +648,14 @@ class Helper:
self.finish_chooser(ident, None)
return
command = [sys.executable, os.path.realpath(__file__), "--choose-file"]
reaper = os.path.join(self.steam_root, "steamrtarm64", "reaper")
if os.access(reaper, os.X_OK):
command = [reaper, "SteamLaunch", "AppId=769", "--"] + command
# Gamescope shows the dialog over the client by the AppId on a reaper above it; the x86-64 client has no
# native reaper, so the arm64 client's is borrowed when it is installed.
data = os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share")
for root in (self.steam_root, os.path.join(data, "Steam")):
reaper = os.path.join(root, "steamrtarm64", "reaper")
if os.access(reaper, os.X_OK):
command = [reaper, "SteamLaunch", "AppId=769", "--"] + command
break
try:
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, start_new_session=True)
@@ -699,6 +705,11 @@ class Helper:
try:
if page.evaluate("typeof SteamClient === 'object' && typeof SteamClient.WebUITransport === 'object'") is not True:
raise LookupError("SteamClient is not ready")
if self.files_only:
page.call("Runtime.addBinding", {"name": FILE_BINDING})
page.evaluate(FILE_JS)
self.page = page
return True
page.call("Runtime.addBinding", {"name": BINDING})
page.call("Runtime.addBinding", {"name": VR_BINDING})
page.evaluate(VR_JS)
@@ -847,7 +858,22 @@ class Helper:
self.open_chooser(e["params"]["payload"])
return events
def serve_files(self):
say("attached to the client on port %d for its file dialogs" % self.port)
while True:
sources = [self.page.ws] + ([self.chooser[1].stdout] if self.chooser is not None else [])
queued = self.page.ws.pending() or bool(self.page.events)
ready = [self.page.ws] if queued else select.select(sources, [], [], 30)[0]
if self.chooser is not None and self.chooser[1].stdout in ready:
self.chooser_done()
if self.page.ws in ready or self.page.events:
for e in self.page.drain():
if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
self.open_chooser(e["params"]["payload"])
def serve(self, watcher):
if self.files_only:
return self.serve_files()
with open(COMPAT["state_path"]("live.pid"), "w") as f:
f.write("%d\n" % os.getpid())
say("attached to the client on port %d" % self.port)
@@ -903,12 +929,29 @@ def chooser_main():
def main():
steam_root = sys.argv[1]
files_only = sys.argv[1:2] == ["--files-only"]
steam_root = sys.argv[2 if files_only else 1]
try:
port = int(os.environ.get("BL_CDP_PORT", ""))
except ValueError:
say("no devtools port for this session; the client's mapping is kept through config.vdf")
return 0
if files_only:
helper = Helper(steam_root, port, files_only=True)
failures = 0
while True:
try:
helper.attach()
failures = 0
helper.serve(None)
except Exception as e:
helper.close_chooser()
if helper.page is not None:
say("lost the client (%s); reattaching" % e)
helper.page.ws.close()
helper.page = None
failures += 1
time.sleep(min(2 * max(failures, 1), 10))
os.makedirs(COMPAT["COMPAT_DIR"], exist_ok=True)
watcher = Watcher([COMPAT["state_path"]("request.json"), COMPAT["state_path"]("games.json")] +
[os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
@@ -943,4 +986,5 @@ if __name__ == "__main__":
try:
sys.exit(main())
finally:
detach()
if sys.argv[1:2] != ["--files-only"]:
detach()
@@ -25,6 +25,8 @@ Android: an EOS sign-in step that falls back to a browser (a consent Epic asks f
is finished there. An EOS overlay pointer (HKCU\Software\Epic Games\EOS "OverlayPath") an earlier
build wrote is removed - with it the game exited while loading.
Battle.net.exe in Battle.net's prefix is handed to droiddeck-battlenet, which runs the whole launch.
droiddeck-store-launch <the arguments Steam gave the compat tool>
"""
@@ -291,6 +293,27 @@ def create_prefix(compat_data, proton, timeout=120):
CLOUD_TIMEOUT = 15.0
CLOUD_STORES = ("gog", "epic")
STORE_GAME = 10
RAN = 11
RAN_FAILED = 12
BATTLENET = "/usr/local/bin/droiddeck-battlenet"
BATTLENET_EXE = re.compile(r"(?i)/compatdata/2596113170/pfx/drive_c/Program Files \(x86\)/Battle\.net/Battle\.net\.exe$")
BATTLENET_LAUNCH = re.compile(r'(?i)^--exec=\s*"?launch\s+([A-Za-z0-9_]{1,16})"?$')
def battlenet(argv, env=os.environ):
if env.get("BL_BATTLENET"):
return None
exe, code = False, None
for raw in argv:
arg = raw.strip().strip('"').strip("'")
if BATTLENET_EXE.search(arg.replace("\\", "/")):
exe = True
found = BATTLENET_LAUNCH.match(arg)
if found:
code = found.group(1)
if not exe:
return None
return [BATTLENET, "launch", code] if code else [BATTLENET, "open"]
def cloud_on(sidecar):
@@ -511,6 +534,10 @@ def main(argv):
pass
rest = rest[2:]
return exited(rest, code)
command = battlenet(argv)
if command is not None:
log("battlenet " + " ".join(command[1:]))
return RAN if subprocess.call(command) == 0 else RAN_FAILED
found = find_store_game(argv)
if found is None:
return 0
@@ -69,7 +69,10 @@ bl_store_launch() {
fi
[ -x /usr/local/bin/droiddeck-store-launch ] || return 0
/usr/local/bin/droiddeck-store-launch "$@"
[ $? -eq 10 ] && BL_STORE_EXIT=1
rc=$?
[ $rc -eq 10 ] && BL_STORE_EXIT=1
[ $rc -eq 11 ] && exit 0
[ $rc -eq 12 ] && exit 1
return 0
}
@@ -87,6 +90,34 @@ bl_run() {
}
"""
BL_DESKTOP_GPU_SETUP = """
bl_desktop_gpu() {
local name saved gpu=/usr/local/bin/droiddeck-gpu
local names=(LD_PRELOAD LD_LIBRARY_PATH ENABLE_VK_LAYER_VALVE_steam_overlay_1 ENABLE_VK_LAYER_VALVE_steam_fossilize_1)
if [ -n "${BL_DESKTOP_GPU_CHILD:-}" ]; then
for name in "${names[@]}"; do
saved=BL_GPU_SAVED_$name
[ -n "${!saved+x}" ] || continue
export "$name=${!saved}"
unset "$saved"
done
return 0
fi
[ "${BL_DESKTOP:-}" = 1 ] && [ "${verb:-}" = waitforexitandrun ] && [ -x "$gpu" ] || return 0
local choice=${BL_DESKTOP_GPU:-on}
case "${choice,,}" in off | 0 | no | false) return 0 ;; esac
case " $* " in *iscriptevaluator*) return 0 ;; esac
local clear=()
for name in "${names[@]}"; do
[ -n "${!name+x}" ] || continue
export "BL_GPU_SAVED_$name=${!name}"
clear+=(-u "$name")
done
echo "droiddeck-gpu: the desktop starts this game on the GPU" >&2
exec env "${clear[@]}" "$gpu" "$0" "$verb" "$@"
}
bl_desktop_gpu "$@"
"""
BL_COMPONENTS_SETUP = """
bl_components() {
base=$1
@@ -377,7 +408,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
def launcher_sh(sources=SOURCES):
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
"verb=$1; shift", "verb=$1; shift\n" + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
@@ -466,7 +497,7 @@ verb=$1; shift
case $verb in
getcompatpath | getnativepath) printf '%s\\n' "$1"; exit 0 ;;
esac
""" + BL_GAME_CPUS_SETUP + """
""" + BL_DESKTOP_GPU_SETUP + BL_GAME_CPUS_SETUP + """
bl_game_cpus
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "$verb"; then
exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@"
@@ -649,7 +680,7 @@ def adopt_extras(tools):
try:
body = (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
'here=$(dirname "$0")\n' + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
write_changed(wrapper, body, 0o755)
write_changed(manifest, EXTRA_MANIFEST_VDF)
@@ -1219,6 +1250,32 @@ def requested_games(requests, catalog, runnable=None):
return resolved
OWN_PROTON = "DroidDeck-Proton"
ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64")
def own_builds(tools):
return [t for t in tools if isinstance(t, dict) and not t.get("valve") and
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")]
def build_key(name):
return [int(n) for n in re.findall(r"\d+", ARCH_WORDS.sub(" ", name))]
def own_proton_moves(state, catalog):
names = {t["name"] for t in catalog}
before = state.get("tools") if isinstance(state.get("tools"), list) else ()
seen = state.get("own_builds") if isinstance(state.get("own_builds"), list) else []
known = {n for n in seen if isinstance(n, str)} | {t["name"] for t in own_builds(before)} | {t["name"] for t in own_builds(catalog)}
state["own_builds"] = sorted(known)
builds = own_builds(catalog)
if not builds:
return None, set()
newest = max(builds, key=lambda t: (build_key(t["dir"]), t["dir"]))["name"]
return newest, known - names
def now_ms():
import time
return int(time.time() * 1000)
@@ -1379,11 +1436,26 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
catalog = tool_catalog(os.path.dirname(os.path.dirname(os.path.abspath(config_path))),
dict(protect) if isinstance(protect, dict) else {name: name for name in protect})
names = [t["name"] for t in catalog]
newest, gone = own_proton_moves(state, catalog)
previous, applied, chosen = state.get("default"), state.get("applied"), state.get("seq")
if default is None:
if settle:
default, state = choose_default(current.get("0", ""), state, read_json(state_path("request.json", directory)), catalog)
else:
default = state.get("default") if state.get("default") in names else TOOL
if settle and newest and default == TOOL and state.get("applied") == applied and state.get("seq") == chosen and (
previous in gone or not state.get("own_proton")):
default = newest
state.update(default=newest, seq=now_ms(), source="update")
if settle and newest:
state["own_proton"] = True
if newest:
for app, name in list(current.items()):
if app != "0" and name in gone:
set_mapping(tokens, mapping, app, newest)
current[app] = newest
if isinstance(state.get("auto"), dict):
state["auto"] = {app: newest if name in gone else name for app, name in state["auto"].items()}
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
requests = settled_game_requests(state, current, catalog, not steam_running(), directory)
overrides = requested_games(requests or {}, catalog)