chore: merge main into feat/lse-emu

This commit is contained in:
Kurt Himebauch committed 2026-11-24 00:23:06 -05:00
commit 83f9067a51
609 files changed
+46314 -8272

No files matched your search

@@ -432,7 +432,7 @@ class FocusWatcher(threading.Thread):
class WebSocket:
def __init__(self, url, timeout):
def __init__(self, url, timeout, bounded=False):
target = urllib.parse.urlsplit(url)
if (target.scheme != "ws" or target.hostname not in ("127.0.0.1", "::1", "localhost")
or target.username is not None or target.password is not None or target.fragment):
@@ -442,6 +442,7 @@ class WebSocket:
if target.query:
path += "?" + target.query
host = "127.0.0.1" if target.hostname == "localhost" else target.hostname
self.deadline = time.monotonic() + timeout if bounded else None
self.s = socket.create_connection((host, target.port or 80), timeout=timeout)
try:
self._handshake(path, hostport)
@@ -457,6 +458,7 @@ class WebSocket:
).encode())
head = b""
while b"\r\n\r\n" not in head:
self._wait()
chunk = self.s.recv(4096)
if not chunk:
raise OSError("DevTools closed the connection during the handshake")
@@ -468,8 +470,17 @@ class WebSocket:
raise OSError("DevTools refused the WebSocket: " + status.decode(errors="replace"))
self.buffer = head.split(b"\r\n\r\n", 1)[1]
def _wait(self):
if self.deadline is None:
return
left = self.deadline - time.monotonic()
if left <= 0:
raise socket.timeout("DevTools did not answer in time")
self.s.settimeout(left)
def _read(self, n):
while len(self.buffer) < n:
self._wait()
chunk = self.s.recv(65536)
if not chunk:
raise OSError("DevTools closed the connection")
@@ -547,22 +558,51 @@ def cdp_targets(agent_dir, timeout=5):
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach the client's DevTools at %s: %s" % (url, e))
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15):
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
want = target or "SharedJSContext"
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
if not match:
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
ws = WebSocket(match[0]["webSocketDebuggerUrl"], timeout)
INSPECTOR_URL = re.compile(r"ws://127\.0\.0\.1:([0-9]{4,5})/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
def inspector_url(url):
found = INSPECTOR_URL.fullmatch(url) if isinstance(url, str) else None
if not found or not 1024 <= int(found.group(1)) <= 65535:
raise AgentError("INVALID_REQUEST", "inspector must be a ws://127.0.0.1 inspector URL with its session id")
return url
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
command_line_api=False):
if inspector is not None:
url, name = inspector_url(inspector), "inspector"
else:
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
want = target or "SharedJSContext"
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
if not match:
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
url, name = match[0]["webSocketDebuggerUrl"], match[0].get("title")
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
"userGesture": True,
}}))
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
message = json.loads(ws.recv())
ws = WebSocket(url, timeout, bounded=True)
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach DevTools: %s" % e)
try:
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
"userGesture": True, "includeCommandLineAPI": command_line_api,
}}))
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e)
while True:
try:
message = json.loads(ws.recv())
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e)
if message.get("id") != 1:
continue
if "error" in message:
@@ -573,9 +613,8 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
text = (details.get("exception") or {}).get("description") or details.get("text") or "exception"
raise AgentError("JS_EXCEPTION", text)
value = result.get("result", {})
return {"target": match[0].get("title"), "type": value.get("type"),
return {"target": name, "type": value.get("type"),
"value": value.get("value"), "description": value.get("description")}
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
finally:
ws.close()
@@ -1157,7 +1196,7 @@ def handle(agent_dir, req):
if not isinstance(expression, str) or not expression:
raise AgentError("INVALID_REQUEST", "cdp eval needs an expression")
return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)),
request_timeout(req, 15))
request_timeout(req, 15), req.get("inspector"), req.get("commandLineApi") is True)
if kind == "steam-selection":
return steam_selection(agent_dir, request_timeout(req, 5))
if kind == "quit":
@@ -1167,6 +1206,15 @@ def handle(agent_dir, req):
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
def reply(agent_dir, req):
try:
return dict(handle(agent_dir, req), ok=True)
except AgentError as e:
return {"ok": False, "error": {"code": e.code, "message": str(e)}}
except Exception as e:
return {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
def answer(agent_dir, path):
rid = path.stem
try:
@@ -1186,12 +1234,7 @@ def answer(agent_dir, path):
except OSError:
pass
if req is not None:
try:
result = dict(handle(agent_dir, req), ok=True)
except AgentError as e:
result = {"ok": False, "error": {"code": e.code, "message": str(e)}}
except Exception as e:
result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}}
result = reply(agent_dir, req)
write_json(agent_dir / "resp" / (rid + ".json"), result)
@@ -1218,6 +1261,13 @@ def serve(agent_dir, focus=True, poll=0.1):
def main(argv):
if argv and argv[0] == "--cdp-inspector":
if len(argv) != 4:
print("usage: droiddeck-agent --cdp-inspector <inspector url> <seconds> <expression>", file=sys.stderr)
return 2
print(json.dumps(reply(Path("/"), {"kind": "cdp", "inspector": argv[1], "timeout": argv[2],
"expression": argv[3], "commandLineApi": True})))
return 0
base = os.environ.get("DD_LAUNCH_DIR")
if not base:
print("DD_LAUNCH_DIR is not set", file=sys.stderr)
@@ -45,11 +45,20 @@ if [ "$qt" = wayland ] && [ -n "$wayland" ]; then
elif [ "$qt" = xcb ] && [ -n "${DISPLAY:-}" ]; then
export QT_QPA_PLATFORM=xcb
fi
arch=$(cat "$dir/arch" 2>/dev/null)
if [ "$arch" = arm64 ]; then
find -H "$APPDIR" -maxdepth 6 ! -type d \( -name libGL.so.1 -o -name libGLX.so.0 -o -name libEGL.so.1 -o -name libGLESv2.so.2 \
-o -name libOpenGL.so.0 -o -name libGLdispatch.so.0 \) -print 2>/dev/null |
while IFS= read -r lib; do
kept=$dir/bundled-gl/${lib#"$APPDIR"/}
mkdir -p "${kept%/*}" && mv -f "$lib" "$kept" && echo "== appimage: the session's ${lib##*/} replaces the bundled one"
done
fi
fex=$(cat "$dir/fex" 2>/dev/null)
case $fex in on|off) ;; *) fex=auto ;; esac
run=("$APPDIR/AppRun")
if [ -x /usr/local/bin/droiddeck-fex ]; then
case $fex:$(cat "$dir/arch" 2>/dev/null) in
case $fex:$arch in
auto:x86_64|auto:i386) run=(/usr/local/bin/droiddeck-fex run --mode on -- "$APPDIR/AppRun") ;;
auto:arm64) ;;
*) run=(/usr/local/bin/droiddeck-fex run --mode "$fex" --for "$APPDIR" -- "$APPDIR/AppRun") ;;
@@ -37,9 +37,6 @@ USER_PREFERENCES = "UserPreferencesMask"
WINE_USER_PREFERENCES = bytes((0x10, 0x00, 0x00, 0x80, 0x12, 0x00, 0x00, 0x00))
CLIENT_AREA_ANIMATION = (4, 0x02)
WALLPAPER_MAX = (1280, 720)
FEX_REQUEST = "battlenet-fex.request"
FEX_RESULT = "battlenet-fex.result"
FEX_WAIT = 120
START_GRACE = 90
POLL = 2
STOP_WAIT = 5
@@ -82,8 +79,7 @@ AGENT_START = 90
AGENT_HELPER = "agent.js"
AGENT_RUNTIME = "agent-runtime"
AGENT_LOG = "agent.log"
AGENT_LOG_LIMIT = 4 << 20
HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"]
HEADLESS = "/usr/local/bin/droiddeck-headless"
PRODUCT = re.compile(r"[a-z0-9_]{1,32}")
LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}")
COUNTRY = re.compile(r"[A-Z]{3}")
@@ -321,6 +317,15 @@ def install_path(root, library):
return letter.upper() + ":\\" + path[len(target):].strip("/").replace("/", "\\")
def keeps_open(root):
try:
with open(os.path.join(drive_c(root), *CONFIG), encoding="utf-8-sig") as f:
client = json.load(f).get("Client")
except (OSError, ValueError, AttributeError):
return False
return isinstance(client, dict) and LAUNCH_BEHAVIOR[0] in client and client[LAUNCH_BEHAVIOR[0]] != LAUNCH_BEHAVIOR[1]
def write_config(root, library=None):
path = os.path.join(drive_c(root), *CONFIG)
key, value = LAUNCH_BEHAVIOR
@@ -338,7 +343,7 @@ def write_config(root, library=None):
return None
client = config["Client"]
changes = []
if client.get(key) != value:
if key not in client:
client[key] = value
changes.append("launch")
if client.get("HardwareAcceleration") != "false":
@@ -770,32 +775,6 @@ def write_menu(path=MENU):
say("menu entry not written: %s" % error)
def ask_fex(launch_dir, wait=FEX_WAIT):
if not launch_dir or not os.path.isdir(launch_dir):
say("not inside a DroidDeck session; FEX stays as Components has it")
return None
result = os.path.join(launch_dir, FEX_RESULT)
request = os.path.join(launch_dir, FEX_REQUEST)
try:
os.unlink(result)
except OSError:
pass
with open(request + ".tmp", "w", encoding="utf-8") as f:
f.write("appid=%s\n" % APP_ID)
os.replace(request + ".tmp", request)
deadline = time.monotonic() + wait
while time.monotonic() < deadline:
try:
with open(result, encoding="utf-8") as f:
answer = f.read().strip()
except OSError:
time.sleep(0.5)
continue
os.unlink(result)
return answer
return None
def wine_processes(pfx, proc="/proc"):
want = os.path.realpath(pfx).rstrip("/")
found = []
@@ -875,6 +854,9 @@ class Tidy:
self.game_since = self.game_since if self.game_since is not None else now
if own and not self.closed_for_game and now - self.game_since >= self.settle:
self.closed_for_game, self.agent_seen, self.agent_lost = True, False, None
if keeps_open(steam_root()):
say("Battle.net is set to stay open as a game launches: left open")
return False
if any(is_client(argv) for _, argv in own) and any(shares_sign_in(argv) for argv in games):
say("Battle.net stayed open beside a game signing in with its token: left open")
return False
@@ -1136,8 +1118,6 @@ def stop_leftovers(pfx):
def open_client(root, reinstall=False):
pfx = os.path.join(prefix(root), "pfx")
write_menu()
answer = ask_fex(os.environ.get("DD_LAUNCH_DIR"))
say("FEX: %s" % (answer or "no answer from the app; Components' choice stays"))
if running(pfx):
say("Battle.net is already running in its prefix; waiting for it to close")
wait_while_open(pfx, grace=0)
@@ -1226,8 +1206,6 @@ def launch(root, code):
try:
own = None
if lock is not None and not running(pfx):
answer = ask_fex(os.environ.get("DD_LAUNCH_DIR"))
say("FEX: %s" % (answer or "no answer from the app; Components' choice stays"))
verb = None if stop_leftovers(pfx) else "run"
configure(root, LIBRARY)
own = start(launcher(root), verb)
@@ -1437,33 +1415,23 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
windows = install_path(root, folder)
emit("STATE", "starting")
base = os.path.join(CACHE, "agent-%s" % uid)
os.makedirs(CACHE, exist_ok=True)
for suffix in (".json", ".game", ".form", ".error"):
try:
os.unlink(base + suffix)
except OSError:
pass
runtime = os.path.join(CACHE, AGENT_RUNTIME)
os.makedirs(runtime, mode=0o700, exist_ok=True)
env = agent_env()
for name in ("DISPLAY", "WAYLAND_DISPLAY"):
env.pop(name, None)
env["XDG_RUNTIME_DIR"] = runtime
cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
cmd = [HEADLESS, os.path.join(CACHE, AGENT_RUNTIME), "--log", os.path.join(CACHE, AGENT_LOG), "--",
os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-",
windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")]
say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd)))
output = os.path.join(CACHE, AGENT_LOG)
try:
if os.path.getsize(output) > AGENT_LOG_LIMIT:
os.replace(output, output + ".1")
except OSError:
pass
before = {pid for pid, _ in wine_processes(pfx)}
with open(output, "ab") as log:
try:
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env)
except OSError as error:
emit("ERROR", "stopped gamescope: %s" % error)
return 1
try:
child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
except OSError as error:
emit("ERROR", "stopped gamescope: %s" % error)
return 1
seen = None
mark = None
moved = time.monotonic()
+129
View File
@@ -0,0 +1,129 @@
#!/bin/bash
set -u
umask 077
self=${BASH_SOURCE[0]}
proc=${DD_PROC:-/proc}
state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge}
runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run}
headless=${DD_HEADLESS_RUN:-${self%/*}/droiddeck-headless}
wait_s=${DD_CURSEFORGE_WAIT:-60}
cmd=${1:-}
dir=${2:-}
flag=--inspect-publish-uid=stderr
case $cmd in start|stop) ;; *) echo "usage: droiddeck-curseforge start|stop <imported AppImage directory>" >&2; exit 2 ;; esac
if [ ! -d "$dir/app" ]; then
echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2
exit 2
fi
running() {
local p
for p in "$proc"/[0-9]*; do
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && return 0
done
return 1
}
started_at() {
local stat
stat=$(cat "/proc/$1/stat" 2>/dev/null) || return 1
stat=${stat##*) }
set -- $stat
echo "${20}"
}
tracked() {
local pid at launched
read -r pid at launched 2>/dev/null < "$state/pid" || return 1
case $pid in ''|*[!0-9]*) return 1 ;; esac
kill -0 "$pid" 2>/dev/null && [ "$(started_at "$pid")" = "$at" ] || return 1
printf '%s %s\n' "$pid" "$launched"
}
ours() {
local pid launched
read -r pid launched <<<"$(tracked)"
[ -n "$pid" ] && [ "$launched" = "$dir" ] && echo "$pid"
}
lock() {
mkdir -p "$state" && chmod 700 "$state" || return 1
exec 9>"$state/lock" || return 1
flock 9
}
inspector() {
grep -aom1 'ws://127\.0\.0\.1:[0-9]*/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}' "$state/log" 2>/dev/null
}
start() {
local url pid child=
lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; }
if ! ours >/dev/null; then
if tracked >/dev/null || running; then
exec 9>&-
echo busy
return 3
fi
mv -f "$state/log" "$state/log.1" 2>/dev/null
env -u DBUS_SESSION_BUS_ADDRESS setsid "$headless" "$state/runtime" --log "$state/log" -- \
"$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" </dev/null >/dev/null 2>&1 9>&- &
pid=$!
child=$pid
printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid"
fi
exec 9>&-
for _ in $(seq 1 $((wait_s * 2))); do
if url=$(inspector); then
echo "$url"
hold "$child"
return 0
fi
ours >/dev/null || break
sleep 0.5
done
tail -n 20 "$state/log" >&2
return 5
}
hold() {
local pid
if [ -n "$1" ]; then
wait "$1"
return 0
fi
pid=$(ours) || return 0
while kill -0 "$pid" 2>/dev/null && [ "$(ours)" = "$pid" ]; do
sleep 1
done
}
stop() {
local pid p
lock || return 1
pid=$(ours) || { tracked >/dev/null || rm -f "$state/pid"; exec 9>&-; return 0; }
kill -TERM -- "-$pid" 2>/dev/null
for _ in $(seq 1 20); do
kill -0 -- "-$pid" 2>/dev/null || break
sleep 0.5
done
kill -KILL -- "-$pid" 2>/dev/null
kill -KILL "$pid" 2>/dev/null
for p in "$proc"/[0-9]*; do
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null
done
rm -f "$state/pid"
exec 9>&-
return 0
}
case $cmd in
start)
start
exit $?
;;
stop)
stop
exit 0
;;
esac
@@ -51,7 +51,7 @@ PROVIDED = frozenset((
"libssl.so.3", "libcrypto.so.3",
"libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1",
"libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8",
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1",
"libgbm.so.1", "libdrm.so.2", "libexpat.so.1", "libOpenGL.so.0",
))
PROVIDED_NEEDS = {
"libwayland-client.so.0": ("libffi.so.8",),
@@ -670,6 +670,8 @@ def guest_environment(fex, env):
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
result.pop("GLIBC_TUNABLES", None)
if "aarch64" in result.get("GCONV_PATH", ""):
result["GCONV_PATH"] = ""
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
if fex["portable"]:
result["FEX_PORTABLE"] = "1"
@@ -14,7 +14,6 @@ from pathlib import Path
GAME_PREFIX = "DROIDDECK_GAME_"
GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR")
CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"}
D3D9_DEFAULT_MEMORY_MB = 4096
SYNC_KEYS = ("DD_SYNC", "DD_SYNC_FALLBACK", "DD_FSYNC_FIRST", "DD_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
PACK_KEYS = ("WINESERVER", "DD_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
@@ -86,9 +85,10 @@ def game_files(exe):
class Game:
def __init__(self, exe, args):
def __init__(self, exe, args, app_id=""):
self.exe = exe
self.args = args
self.app_id = app_id
self.stem = os.path.splitext(os.path.basename(exe))[0].lower()
self.files = game_files(exe)
@@ -152,12 +152,24 @@ def deep_rock_gdk_raytracing(game):
return {}, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"], "Deep Rock Galactic GDK: ray tracing off (D3D12 pipeline creation fails on Thor)"
@fix
def dragons_dogma_2_wine_detection(game):
if game.app_id == "2054970" and not any(a.lower().startswith("/winedetectionenabled:") for a in game.args):
return {}, ["/WineDetectionEnabled:False"], "Dragon's Dogma 2: the game's Wine detection off (its Wine path does not start)"
@fix
def ff7_rebirth_feature_level(game):
if game.stem in ("ff7rebirth", "ff7rebirth_"):
return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Final Fantasy VII Rebirth: D3D12 feature level 12_2 (the device-reported level fails its DX12 check)"
@fix
def kcd2_feature_level(game):
if game.app_id == "1771300":
return {"VKD3D_FEATURE_LEVEL": "12_2", "VKD3D_SHADER_MODEL": "6_9"}, [], "Kingdom Come: Deliverance II: D3D12 feature level 12_2 and shader model 6_9 (the detected level fails its startup check, and 12_0 alone stalls on the splash screen)"
@fix
def arkham_city_x87(game):
if "batmanac.exe" in game.files:
@@ -188,6 +200,12 @@ def protonfixes_off(game):
return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)"
@fix
def black_ops_ii_steam_exec(game):
if game.app_id in ("202970", "202990", "212910") or game.stem in ("t6sp", "t6mp", "t6zm"):
return {"WINESTEAMNOEXEC": "0"}, [], "Black Ops II: Steam exec handling on (the game does not start without it)"
@fix
def little_nightmares_threads(game):
if game.stem == "littlenightmares":
@@ -367,8 +385,8 @@ def offline_without_anticheat(command, env):
return command[:2] + [game] + command[3:]
def engine_fixes(exe, args):
game = Game(exe, args)
def engine_fixes(exe, args, app_id=""):
game = Game(exe, args, app_id)
env, extra, notes = {}, [], []
for check in FIXES:
found = check(game)
@@ -453,18 +471,13 @@ def game_gpu(env, keep=False):
return result
def vram_cap(env):
value = env.get("DD_VRAM_MB", "")
if not re.fullmatch(r"[1-9][0-9]{0,6}", value):
return env
result = env.copy()
cap = "dxgi.maxDeviceMemory = {0}; dxgi.maxSharedMemory = {0}".format(int(value))
if int(value) < D3D9_DEFAULT_MEMORY_MB:
cap += "; d3d9.maxAvailableMemory = {0}".format(int(value))
own = result.get("DXVK_CONFIG", "").strip().strip(";").strip()
result["DXVK_CONFIG"] = cap + "; " + own if own else cap
result["DROIDDECK_VRAM_CAP"] = "1"
result["DROIDDECK_VRAM_CAP_MB"] = value
def split_game_gpu(entries):
result = dict(entries)
for key in GAME_SPLIT_KEYS:
if GAME_PREFIX + key in result:
value = result.pop(GAME_PREFIX + key)
if key not in entries:
result[key] = None if value == "" else value
return result
@@ -596,12 +609,12 @@ def apply_config(env, config, app_id, fixes=None):
if config.get("version") != 1:
raise ValueError("unsupported environment configuration")
result = env.copy()
entries = dict(config.get("shared", {}))
entries = split_game_gpu(config.get("shared", {}))
for name, value in (fixes or {}).items():
if name == "WINEDLLOVERRIDES" and entries.get(name, env.get(name)):
value = entries.get(name, env.get(name)) + ";" + value
entries[name] = value
game = config.get("games", {}).get(app_id, {})
game = split_game_gpu(config.get("games", {}).get(app_id, {}))
fix = (fixes or {}).get("WINEDLLOVERRIDES")
if fix and isinstance(game.get("WINEDLLOVERRIDES"), str):
own = game["WINEDLLOVERRIDES"]
@@ -1395,7 +1408,7 @@ def main():
death_stranding_allocator(app_id, command[2])
ubisoft_overlay_off(env)
project_zomboid_jvm(command)
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
fixes, extra, notes = engine_fixes(command[2], command[3:], app_id) if len(command) > 2 else ({}, [], [])
if not gl_default:
fixes.pop("vblank_mode", None)
for note in notes:
@@ -1439,7 +1452,6 @@ def main():
if mic_enabled == "0":
env["AUDIO_DIRECT_MIC"] = "0"
env = directaudio_settings(env)
env = vram_cap(env)
note = render_path_defaults(command, env) if app_id else None
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
+24
View File
@@ -0,0 +1,24 @@
#!/bin/bash
set -u
runtime=${1:-}
shift
log=
if [ "${1:-}" = --log ]; then
log=${2:-}
shift 2
fi
if [ -z "$runtime" ] || [ "${1:-}" != -- ] || [ $# -lt 2 ]; then
echo "usage: droiddeck-headless <private runtime directory> [--log <file>] -- <command> [args...]" >&2
exit 2
fi
shift
umask 077
mkdir -p "$runtime" && chmod 700 "$runtime" || exit 1
if [ -n "$log" ]; then
size=$(stat -c %s "$log" 2>/dev/null || echo 0)
[ "$size" -gt "${DD_HEADLESS_LOG_LIMIT:-4194304}" ] && mv -f "$log" "$log.1"
exec >>"$log" 2>&1
fi
unset DISPLAY WAYLAND_DISPLAY GAMESCOPE_WAYLAND_DISPLAY XAUTHORITY
export XDG_RUNTIME_DIR=$runtime
exec gamescope --backend headless -w 640 -h 480 -- "$@"
@@ -137,6 +137,7 @@ clear_stale_tmp() {
[ -z "${DD_INSIDE:-}" ] && clear_stale_tmp
if [ -z "${DD_INSIDE:-}" ]; then
if [ "${DD_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.dd-zram; else rm -f /tmp/.dd-zram; fi
rm -f /tmp/.dd-zram.hold
dd if=/dev/zero of=/tmp/.dd-clock bs=8 count=1 conv=notrunc status=none
fi
@@ -761,13 +762,6 @@ case $mode in
fi
if [ "${DD_ZRAM:-0}" = 1 ]; then
step "zRAM compression: on"
[ "${DD_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam, the hidden Epic Games Launcher and Battle.net are not compressed while games run (turned off in Performance)"
_dd_ram_cap=0
case ${DD_RAM_CAP_MB:-} in
''|0) ;;
*[!0-9]*|0*|???????*) step "RAM cap: ignored invalid value '$DD_RAM_CAP_MB'" ;;
*) _dd_ram_cap=$((DD_RAM_CAP_MB * 1024)); step "RAM cap: ${DD_RAM_CAP_MB} MB" ;;
esac
(
dd_zram_scan() {
_dd_game=0 _dd_pids=() _dd_others=() _dd_apps=
@@ -844,284 +838,235 @@ case $mode in
echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
}
dd_memory_read() {
local _k _v _u _kind _fields _avg _whole _frac _gpu_bytes _growth _saved_growth _saved_fall
_saved_growth=${_dd_preserved_growth:-0} _saved_fall=${_dd_preserved_fall:-0}
_dd_preserved_growth=0 _dd_preserved_fall=0
_dd_mem_total=0 _dd_available=-1 _dd_swap_total=0 _dd_swap_free=-1
_dd_psi_some=0 _dd_psi_full=0 _dd_gpu=0 _dd_unevictable=0 _dd_shmem=0
local _k _v _u _kind _fields _name _type _size _used _orig _comp _mem _dt _fall
local _stall=-1 _swap_total=0 _swap_free=0 _total=0 _room=0 _listed=0 _in=-1
_dd_mem_total=0 _dd_available=-1
while read -r _k _v _u; do
case $_v in ''|*[!0-9]*) continue ;; esac
case $_k in
MemTotal:) _dd_mem_total=$_v ;;
MemAvailable:) _dd_available=$_v ;;
SwapTotal:) _dd_swap_total=$_v ;;
SwapFree:) _dd_swap_free=$_v ;;
Unevictable:) _dd_unevictable=$_v ;;
Shmem:) _dd_shmem=$_v ;;
SwapTotal:) _swap_total=$_v ;;
SwapFree:) _swap_free=$_v ;;
esac
done 2>/dev/null < /proc/meminfo
while read -r _name _type _size _used _u; do
_listed=1
case $_name in */zram[0-9]*) ;; *) continue ;; esac
case $_size$_used in ''|*[!0-9]*) continue ;; esac
_total=$((_total + _size)) _room=$((_room + _size - _used))
done 2>/dev/null < /proc/swaps
[ "$_listed" = 1 ] || _total=$_swap_total _room=$_swap_free
_dd_swap_room=$((_total / 8))
[ "$_dd_swap_room" -ge $((128 * 1024)) ] || _dd_swap_room=$((128 * 1024))
_dd_swap_room=$((_room - _dd_swap_room))
_dd_saving=600
if [ -r /sys/block/zram0/mm_stat ] && read -r _orig _comp _mem _u 2>/dev/null < /sys/block/zram0/mm_stat; then
case $_orig$_mem in
''|*[!0-9]*) ;;
*) [ "$_orig" -lt $((64 << 20)) ] || _dd_saving=$(((_orig - _mem) / (_orig / 1000))) ;;
esac
[ "$_dd_saving" -ge 167 ] || _dd_saving=167
[ "$_dd_saving" -le 833 ] || _dd_saving=833
fi
if [ -r /proc/pressure/memory ]; then
while read -r _kind _fields; do
[ "$_kind" = some ] || [ "$_kind" = full ] || continue
_avg=${_fields#avg10=} _avg=${_avg%% *}
_whole=${_avg%%.*} _frac=${_avg#*.}
[ "$_frac" = "$_avg" ] && _frac=00
_frac=${_frac}00
_frac=${_frac:0:2}
case $_whole$_frac in ''|*[!0-9]*) continue ;; esac
if [ "$_kind" = some ]; then
_dd_psi_some=$((10#$_whole * 100 + 10#$_frac))
else
_dd_psi_full=$((10#$_whole * 100 + 10#$_frac))
fi
[ "$_kind" = some ] || continue
_fields=${_fields##*total=}
case $_fields in ''|*[!0-9]*) ;; *) _stall=$_fields ;; esac
done 2>/dev/null < /proc/pressure/memory
fi
if [ -r /sys/class/kgsl/kgsl/page_alloc ]; then
read -r _gpu_bytes _u < /sys/class/kgsl/kgsl/page_alloc
case $_gpu_bytes in ''|*[!0-9]*) _gpu_bytes=0 ;; esac
_dd_gpu=$((_gpu_bytes / 1024))
while read -r _k _v; do
[ "$_k" = pswpin ] || continue
case $_v in ''|*[!0-9]*) ;; *) _in=$((_v * _dd_page_kb)) ;; esac
break
done 2>/dev/null < /proc/vmstat
_dt=$((SECONDS - ${_dd_sample_at:-$SECONDS}))
if [ -z "${_dd_sample_at:-}" ]; then
_dd_rate=0 _dd_psi=0 _dd_returned=0
elif [ "$_dt" -gt 0 ] && [ "$_dd_available" -ge 0 ]; then
_fall=$(((_dd_sample_available - _dd_available + _dd_freed) / _dt))
_dd_rate=$((_dd_rate * 3 / 4))
[ "$_fall" -le "$_dd_rate" ] || _dd_rate=$_fall
_dd_psi=0
[ "$_stall" -lt 0 ] || [ "$_dd_sample_stall" -lt 0 ] || _dd_psi=$(((_stall - _dd_sample_stall) / (_dt * 100)))
_dd_returned=$((_dt < 30 ? _dd_returned * (30 - _dt) / 30 : 0))
[ "$_in" -lt "$_dd_sample_in" ] || [ "$_dd_sample_in" -lt 0 ] || _dd_returned=$((_dd_returned + _in - _dd_sample_in))
fi
_dd_psi=$_dd_psi_some
[ "$_dd_psi_full" -gt "$_dd_psi" ] && _dd_psi=$_dd_psi_full
if [ "${_dd_sample_at:-}" = "" ]; then
_dd_growth=0 _dd_fall=0
_dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_gpu=$_dd_gpu
_dd_sample_unevictable=$_dd_unevictable _dd_sample_shmem=$_dd_shmem
elif [ "$SECONDS" -gt "$_dd_sample_at" ]; then
_dd_growth=0 _dd_fall=0
_growth=$((_dd_gpu - _dd_sample_gpu)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth))
_growth=$((_dd_unevictable - _dd_sample_unevictable)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth))
_growth=$((_dd_shmem - _dd_sample_shmem)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth))
_dd_fall=$((_dd_sample_available - _dd_available))
[ "$_saved_growth" -gt "$_dd_growth" ] && _dd_growth=$_saved_growth
[ "$_saved_fall" -gt "$_dd_fall" ] && _dd_fall=$_saved_fall
if [ $((SECONDS - _dd_sample_at)) -ge 5 ]; then
_dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_gpu=$_dd_gpu
_dd_sample_unevictable=$_dd_unevictable _dd_sample_shmem=$_dd_shmem
fi
if [ "$_dd_available" -ge 0 ] && { [ -z "${_dd_sample_at:-}" ] || [ "$_dt" -gt 0 ]; }; then
_dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_stall=$_stall _dd_sample_in=$_in _dd_freed=0
fi
_dd_real_available=$_dd_available
[ "$_dd_real_available" -ge 0 ] && _dd_real_available=$((_dd_real_available - _dd_growth))
_dd_headroom=$((_dd_mem_total / 5))
[ "$_dd_headroom" -ge $((512 * 1024)) ] || _dd_headroom=$((512 * 1024))
[ "$_dd_headroom" -le $((1536 * 1024)) ] || _dd_headroom=$((1536 * 1024))
_dd_tier_headroom=$((_dd_mem_total / 4))
[ "$_dd_tier_headroom" -ge $((768 * 1024)) ] || _dd_tier_headroom=$((768 * 1024))
[ "$_dd_tier_headroom" -le $((2560 * 1024)) ] || _dd_tier_headroom=$((2560 * 1024))
_dd_fall_headroom=$((_dd_tier_headroom * 2))
[ "$_dd_fall_headroom" -ge $((_dd_mem_total * 2 / 5)) ] || _dd_fall_headroom=$((_dd_mem_total * 2 / 5))
_dd_swap_reserve=$((_dd_swap_total / 5))
[ "$_dd_swap_reserve" -ge $((256 * 1024)) ] || _dd_swap_reserve=$((256 * 1024))
_dd_floor=$((_dd_mem_total / 8))
[ "$_dd_floor" -ge $((640 * 1024)) ] || _dd_floor=$((640 * 1024))
[ "$_dd_floor" -le $((1280 * 1024)) ] || _dd_floor=$((1280 * 1024))
_dd_target=$((_dd_floor + _dd_rate * 10))
}
dd_memory_tight() {
[ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] &&
{ [ "$_dd_real_available" -lt "$_dd_headroom" ] ||
{ [ "$_dd_psi" -ge 100 ] && [ "$_dd_real_available" -lt $((_dd_mem_total / 3)) ]; } ||
{ [ "$_dd_fall" -ge $((256 * 1024)) ] && [ "$_dd_real_available" -lt $((_dd_headroom * 2)) ]; }; }
}
dd_client_can_pageout() {
dd_memory_read
dd_zram_usage "${_dd_pids[@]}" > /dev/null
[ "$_dd_mem_total" -gt 0 ] && dd_zram_has_room
}
dd_zram_has_room() {
[ "$_dd_swap_total" -gt 0 ] &&
[ $((_dd_swap_free - _dd_anon - ${_dd_client_reserve:-0})) -ge "$_dd_swap_reserve" ]
}
dd_client_can_readback() {
dd_memory_read
dd_zram_usage "${_dd_pids[@]}" > /dev/null
[ "$_dd_mem_total" -gt 0 ] && ! dd_memory_tight && ! dd_memory_critical &&
[ "$_dd_real_available" -ge $((_dd_swap * 2)) ] &&
[ $((_dd_real_available - _dd_swap)) -ge "$_dd_headroom" ]
}
dd_client_pressure() {
[ "${DD_ZRAM_CLIENT:-1}" = 1 ] && [ "$_dd_game" = 1 ] &&
[ "${#_dd_pids[@]}" -gt 0 ] && { dd_memory_tight || dd_memory_critical; } || return 0
[ "$_dd_pressure_at" -lt 0 ] ||
[ $((SECONDS - _dd_pressure_at)) -ge "$_dd_pressure_backoff" ] || return 0
[ "$_dd_packed" -lt 0 ] || [ $((SECONDS - _dd_packed)) -ge 30 ] || return 0
_dd_pressure_at=$SECONDS
if ! dd_client_can_pageout; then
step "zRAM: pressure reclaim skipped, swap headroom too small ($((_dd_swap_free / 1024)) MB free)"
return 0
dd_memory_need() {
local _burst=$((_dd_rate * 2))
_dd_need=0 _dd_hard=0 _dd_force=0
[ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] || return 0
_dd_need=$((_dd_target - _dd_available)) _dd_hard=$((_dd_floor - _dd_available))
if [ "$_burst" -ge $((64 * 1024)) ] && [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] && [ "$_burst" -gt "$_dd_need" ]; then
_dd_need=$_burst
fi
[ "$_dd_rss" -ge $((128 * 1024)) ] || return 0
_dd_pressure_before=$_dd_rss
if [ "${1:-}" = defer ]; then
_dd_client_reserve=$_dd_anon
_dd_client_pending=1
fi
dd_zram_send 1 "memory pressure, compressing the client (available $((_dd_available / 1024)) MB, swap free $((_dd_swap_free / 1024)) MB)" client "${1:-}"
_dd_packed=$SECONDS
if [ "${1:-}" = defer ]; then
_dd_client_targets=("${_dd_zram_targets[@]}")
else
dd_client_pressure_result
if [ "$_dd_psi" -ge 100 ] && [ "$_burst" -gt "$_dd_hard" ]; then
_dd_hard=$_burst
fi
[ "$_dd_hard" -gt 0 ] || _dd_hard=0
[ "$_dd_need" -ge "$_dd_hard" ] || _dd_need=$_dd_hard
[ "$_dd_available" -ge $((_dd_floor / 2)) ] || _dd_force=1
}
dd_client_pressure_finish() {
[ "${_dd_client_pending:-0}" = 1 ] || return 0
dd_zram_finish 1 "${_dd_client_targets[@]}"
dd_client_pressure_result "${_dd_client_targets[@]}"
_dd_client_pending=0 _dd_client_reserve=0 _dd_client_targets=()
}
dd_client_pressure_result() {
[ "${_dd_pageout_complete:-0}" = 1 ] || return 0
if [ "$#" -gt 0 ]; then dd_zram_usage "$@" > /dev/null; else dd_zram_usage "${_dd_pids[@]}" > /dev/null; fi
if [ $((_dd_pressure_before - _dd_rss)) -lt $((16 * 1024)) ]; then
_dd_pressure_backoff=$((_dd_pressure_backoff * 2 > 300 ? 300 : _dd_pressure_backoff * 2))
else
_dd_pressure_backoff=30
fi
}
dd_memory_critical() {
[ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] &&
{ [ "$_dd_real_available" -lt "$_dd_tier_headroom" ] ||
{ [ "$_dd_psi" -ge 100 ] && [ "$_dd_real_available" -lt $((_dd_tier_headroom * 3 / 2)) ]; } ||
{ [ "$_dd_fall" -ge $((256 * 1024)) ] && [ "$_dd_real_available" -lt "$_dd_fall_headroom" ]; }; }
}
dd_session_pressure() {
dd_memory_read
dd_memory_critical || _dd_tier_backoff=30 _dd_tier_nogain=0
[ "$_dd_game" = 1 ] && dd_memory_critical || return 0
[ "${DD_ZRAM_IDLE:-1}" = 1 ] && dd_game_focused 0 || return 0
local _wait=$_dd_tier_backoff _before _available_before _pids _targets _gain _min_gain
[ "$_dd_available" -ge $((_dd_headroom / 2)) ] || [ "$_dd_tier_pushed" -lt 0 ] || _wait=30
[ "$_dd_tier_at" -lt 0 ] || [ $((SECONDS - _dd_tier_at)) -ge "$_wait" ] || return 0
if [ "$_dd_tier_at" -ge 0 ] && [ "$_dd_tier_pushed" -gt 0 ]; then
dd_tier_readback
if [ "$_dd_tier_back" -le $((_dd_tier_pushed / 2)) ]; then
[ "${_dd_tier_nogain:-0}" = 1 ] || _dd_tier_backoff=30
else
_dd_tier_backoff=$((_dd_tier_backoff * 2 > 300 ? 300 : _dd_tier_backoff * 2))
_dd_tier_at=$SECONDS _dd_tier_pushed=-1
step "zRAM: the game read back most of its last page-out, next try in ${_dd_tier_backoff} s"
return 0
fi
fi
_dd_tier_at=$SECONDS _dd_tier_pushed=0
dd_zram_pick session
dd_zram_usage "${_pids[@]}" > /dev/null
[ "$_dd_rss" -ge $((256 * 1024)) ] || return 0
if ! dd_zram_has_room; then
step "zRAM: low-memory page-out skipped, swap headroom too small ($((_dd_swap_free / 1024)) MB free)"
return 0
fi
_targets=("${_pids[@]}") _before=$_dd_swap _available_before=$_dd_available
dd_zram_send 1 "low memory (available $((_dd_real_available / 1024)) MB), compressing idle game memory" session
dd_zram_usage "${_targets[@]}" > /dev/null
_dd_tier_pushed=$((_dd_swap - _before))
dd_tier_note "${_targets[@]}"
if [ "${_dd_pageout_complete:-0}" = 1 ]; then
dd_memory_read
_gain=$((_dd_available - _available_before))
_min_gain=$((_dd_tier_headroom / 16))
[ "$_min_gain" -ge $((16 * 1024)) ] || _min_gain=$((16 * 1024))
if [ "$_gain" -lt "$_min_gain" ]; then
_dd_tier_backoff=$((_dd_tier_backoff * 2 > 300 ? 300 : _dd_tier_backoff * 2))
_dd_tier_at=$SECONDS _dd_tier_nogain=1
step "zRAM: low-memory page-out gained only $((_gain / 1024)) MB available, next try in ${_dd_tier_backoff} s"
else
_dd_tier_nogain=0
fi
fi
}
dd_proc_start() {
local _s=
_dd_start=
read -r _s 2>/dev/null < "/proc/$1/stat" || return 1
_s=${_s##*) }
set -- $_s
[ "$1" != Z ] && [ "$#" -ge 20 ] || return 1
_dd_start=${20}
}
dd_tier_note() {
local _p
_dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=()
for _p in "$@"; do
dd_proc_start "$_p" || continue
dd_zram_usage "$_p" > /dev/null
_dd_tier_targets+=("$_p") _dd_tier_swaps+=("$_dd_swap") _dd_tier_starts+=("$_dd_start")
done
}
dd_tier_readback() {
local _i _back=0
for _i in "${!_dd_tier_targets[@]}"; do
dd_proc_start "${_dd_tier_targets[$_i]}" && [ "$_dd_start" = "${_dd_tier_starts[$_i]}" ] || continue
dd_zram_usage "${_dd_tier_targets[$_i]}" > /dev/null
[ "${_dd_tier_swaps[$_i]}" -le "$_dd_swap" ] || _back=$((_back + _dd_tier_swaps[_i] - _dd_swap))
done
_dd_tier_back=$_back
}
dd_watch_nap() {
local _i
if [ "$_dd_game" = 1 ] && [ "$_dd_available" -ge 0 ] && [ "$_dd_real_available" -lt "$_dd_fall_headroom" ]; then
for _i in 1 2 3 4 5; do
nap 1
dd_memory_read
dd_memory_critical && return 0
done
else
nap 5
fi
return 0
dd_pid_key() {
local _s
_dd_key=$1
read -r _s 2>/dev/null < "/proc/$1/stat" || return 0
set -- ${_s##*) }
_dd_key=$_dd_key.${20:-}
}
dd_session_others() {
local _p
local -A _known=()
_dd_session=()
for _p in "${_dd_others[@]}"; do
grep -q -m1 '/libddsession\.so$' "/proc/$_p/maps" 2>/dev/null && _dd_session+=("$_p")
dd_pid_key "$_p"
[ -n "${_dd_preloaded[$_dd_key]:-}" ] ||
grep -q -m1 '/libddsession\.so$' "/proc/$_p/maps" 2>/dev/null || continue
_known[$_dd_key]=1
dd_zram_usage "$_p" > /dev/null
_dd_session+=("$_dd_anon $_p")
done
_dd_preloaded=()
for _p in "${!_known[@]}"; do
_dd_preloaded[$_p]=1
done
[ "${#_dd_session[@]}" -gt 0 ] || return 0
mapfile -t _dd_session < <(printf '%s\n' "${_dd_session[@]}" | sort -rn)
_dd_session=("${_dd_session[@]#* }")
}
dd_zram_pick() {
if [ "$1" = game ]; then
dd_session_others
_pids=("${_dd_session[@]}")
[ "${DD_ZRAM_CLIENT:-1}" != 1 ] || _pids+=("${_dd_pids[@]}")
elif [ "$1" = session ]; then
dd_session_others
_pids=("${_dd_session[@]}")
dd_memory_relieved() {
local _k _v _u
while read -r _k _v _u; do
[ "$_k" = MemAvailable: ] || continue
case $_v in ''|*[!0-9]*) return 1 ;; esac
[ "$_v" -ge "$_dd_goal" ]
return
done 2>/dev/null < /proc/meminfo
return 1
}
dd_zram_trim() {
local _mode=$1 _left=$2 _p _k _n _i _acks=()
shift 2
_dd_trimmed=0
for _k in "${!_dd_deaf[@]}"; do
[ "${_dd_deaf[$_k]}" -gt "$SECONDS" ] || unset "_dd_deaf[$_k]"
done
for _p in "$@"; do
[ "$_left" -ge 4096 ] && [ "$_dd_polls" -lt 250 ] && [ $((SECONDS - _dd_pass_at)) -lt 6 ] &&
[ ! -e /tmp/.dd-zram.hold ] || break
! dd_memory_relieved || break
dd_pid_key "$_p"
_k=$_dd_key
[ "${_dd_deaf[$_k]:-0}" -le "$SECONDS" ] || continue
dd_zram_usage "$_p" > /dev/null
[ "$_dd_anon" -ge 8192 ] || continue
printf %s - > "/tmp/.dd-zram.trim.$_p"
_acks+=("/tmp/.dd-zram.trim.$_p")
printf '%s %s\n' "$_mode" "$_left" > /tmp/.dd-zram
kill -URG "$_p" 2>/dev/null || continue
_dd_deaf[$_k]=$((SECONDS + 60))
for ((_i = 0; _dd_polls < 250 && SECONDS - _dd_pass_at < 6; _i++, _dd_polls++)); do
[ ! -e /tmp/.dd-zram.hold ] || { _dd_deaf[$_k]=0; break; }
_n=
read -r _n 2>/dev/null < "/tmp/.dd-zram.trim.$_p" || :
case $_n in
-) [ "$_i" -lt 25 ] || break ;;
''|*[!0-9]*) ;;
*) _dd_trimmed=$((_dd_trimmed + _n)) _left=$((_left - _n)) _dd_deaf[$_k]=0; break ;;
esac
nap 0.02
done
done
[ ! -e /tmp/.dd-zram.hold ] || return 0
printf '2 0\n' > /tmp/.dd-zram
[ "${#_acks[@]}" = 0 ] || rm -f "${_acks[@]}"
}
dd_memory_relieve() {
local _mode=2 _budget _gain=0 _rest _cap=$((256 * 1024)) _all=$((1024 * 1024))
dd_memory_need
_dd_polls=0 _dd_pass_at=$SECONDS
if [ "$_dd_need" -le 0 ]; then
_dd_rest=0
return 0
fi
[ "$_dd_rest" = 0 ] || [ "$_dd_force" = 1 ] || [ "$SECONDS" -ge "$_dd_rest_until" ] ||
[ "$_dd_available" -lt $((_dd_rest_available - _dd_floor / 8)) ] || return 0
if [ "$_dd_swap_room" -lt $((64 * 1024)) ]; then
if [ $((SECONDS - _dd_full_at)) -ge 60 ]; then
_dd_full_at=$SECONDS
step "memory: available $((_dd_available / 1024)) MB and zRAM has no room left"
fi
return 0
fi
if [ "$_dd_force" = 1 ] && [ $((SECONDS - _dd_forced_at)) -ge 10 ]; then
_mode=3 _dd_forced_at=$SECONDS _cap=$_all
else
_pids=("${_dd_pids[@]}")
_cap=$((_cap - _dd_returned)) _all=$((_all - _dd_returned))
fi
if [ "${#_dd_pids[@]}" -gt 0 ] && [ "$_all" -ge 4096 ] &&
{ [ "$_dd_hard" -gt 0 ] ||
{ [ "$_dd_game" = 1 ] && [ "$_dd_focus" != 1 ] && [ $((SECONDS - _dd_back_at)) -ge 30 ]; }; }; then
_budget=$((_dd_need * 1000 / _dd_saving))
[ "$_budget" -le "$_all" ] || _budget=$_all
[ "$_budget" -le "$_dd_swap_room" ] || _budget=$_dd_swap_room
_dd_goal=$((_dd_available + _dd_need))
dd_zram_trim "$_mode" "$_budget" "${_dd_pids[@]}"
_gain=$((_dd_trimmed * _dd_saving / 1000))
_dd_swap_room=$((_dd_swap_room - _dd_trimmed)) _all=$((_all - _dd_trimmed))
[ "$_cap" -le "$_all" ] || _cap=$_all
_dd_client_out=$((_dd_client_out + _dd_trimmed)) _dd_note_client=$((_dd_note_client + _dd_trimmed))
[ "$_dd_trimmed" = 0 ] || _dd_trim_at=$SECONDS
fi
_rest=$((_dd_hard - _gain))
if [ "$_rest" -gt 0 ] && [ "$_cap" -ge 4096 ] && [ "$_dd_swap_room" -ge $((64 * 1024)) ]; then
[ "$_dd_session_at" = "$_dd_scan_at" ] || dd_session_others
_dd_session_at=$_dd_scan_at
_budget=$((_rest * 1000 / _dd_saving))
[ "$_budget" -le "$_cap" ] || _budget=$_cap
[ "$_budget" -le "$_dd_swap_room" ] || _budget=$_dd_swap_room
_dd_goal=$((_dd_available + _dd_hard))
dd_zram_trim "$_mode" "$_budget" "${_dd_session[@]}"
_gain=$((_gain + _dd_trimmed * _dd_saving / 1000))
_dd_note_session=$((_dd_note_session + _dd_trimmed))
fi
_dd_freed=$((_dd_freed + _gain))
if [ "$_dd_hard" -gt 0 ] && [ "$_gain" -lt $((_dd_hard / 4)) ]; then
_dd_rest=$((_dd_rest > 0 ? _dd_rest * 2 : 5))
[ "$_dd_rest" -le 60 ] || _dd_rest=60
_dd_rest_until=$((SECONDS + _dd_rest)) _dd_rest_available=$_dd_available
else
_dd_rest=0
fi
}
dd_zram_wait() {
local _p _left _start=$SECONDS
while [ $((SECONDS - _start)) -lt 12 ]; do
_left=0
for _p in "$@"; do
[ -s "/tmp/.dd-zram.ack.$_p" ] && continue
[ -d "/proc/$_p" ] || continue
[ $((SECONDS - _start)) -ge 2 ] && [ ! -e "/tmp/.dd-zram.ack.$_p" ] && continue
_left=1
done
[ "$_left" = 1 ] || break
nap 0.2
done
_dd_pageout_complete=1
for _p in "$@"; do
if [ -d "/proc/$_p" ] && [ ! -s "/tmp/.dd-zram.ack.$_p" ]; then _dd_pageout_complete=0; fi
rm -f "/tmp/.dd-zram.ack.$_p"
done
dd_memory_note() {
[ $((_dd_note_client + _dd_note_session)) -ge $((16 * 1024)) ] && [ $((SECONDS - _dd_noted_at)) -ge 5 ] || return 0
step "memory: available $((_dd_available / 1024)) MB, falling $((_dd_rate / 1024)) MB/s, compressed $((_dd_note_client / 1024)) MB of the client and $((_dd_note_session / 1024)) MB of the session"
_dd_note_client=0 _dd_note_session=0 _dd_noted_at=$SECONDS
}
dd_zram_send() {
local _mode=$1 _what=$2 _which=$3 _pids _p
dd_zram_pick "$_which"
step "zRAM: $_what ($(dd_zram_usage "${_pids[@]}"))"
for _p in "${_pids[@]}"; do rm -f "/tmp/.dd-zram.ack.$_p"; done
printf '%s' "$_mode" > /tmp/.dd-zram
[ "${#_pids[@]}" = 0 ] || kill -URG "${_pids[@]}" 2>/dev/null
_dd_zram_targets=("${_pids[@]}")
[ "${4:-}" != defer ] || return 0
dd_zram_finish "$_mode" "${_pids[@]}"
}
dd_zram_finish() {
local _mode=$1
shift
if [ "$_mode" = 1 ]; then dd_zram_wait "$@"; else nap 5; fi
dd_zram_scan
step "zRAM: done ($(dd_zram_usage "$@"))"
dd_client_readback() {
[ "$_dd_client_out" -gt 0 ] && [ "${#_dd_pids[@]}" -gt 0 ] || return 0
[ "$_dd_game" = 0 ] || { [ -n "$_dd_away" ] && [ $((SECONDS - _dd_away)) -ge 5 ]; } || return 0
[ $((SECONDS - _dd_trim_at)) -ge 30 ] || return 0
dd_zram_usage "${_dd_pids[@]}" > /dev/null
if [ "$_dd_swap" -lt $((16 * 1024)) ]; then
_dd_client_out=0
return 0
fi
[ $((_dd_available - _dd_swap)) -ge $((_dd_target + _dd_floor)) ] || return 0
step "memory: available $((_dd_available / 1024)) MB, reading $((_dd_swap / 1024)) MB of the client back"
printf 0 > /tmp/.dd-zram || return 0
kill -URG "${_dd_pids[@]}" 2>/dev/null || return 0
_dd_freed=$((_dd_freed - _dd_swap * _dd_saving / 1000))
_dd_client_out=0 _dd_back_at=$SECONDS
}
dd_game_focused() {
if [ "${DD_DESKTOP:-}" = 1 ] || [ -z "${DD_LAUNCH_DIR:-}" ]; then
@@ -1136,92 +1081,40 @@ case $mode in
esac
return 1
}
dd_over_cap() {
[ "$_dd_ram_cap" -gt 0 ] || return 1
_dd_measured=$SECONDS
dd_session_others
dd_zram_usage "${_dd_pids[@]}" "${_dd_session[@]}" > /dev/null
[ "$_dd_rss" -gt "$_dd_ram_cap" ]
}
dd_cap_due() {
[ "$_dd_ram_cap" -gt 0 ] && { [ "$_dd_measured" -lt 0 ] || [ $((SECONDS - _dd_measured)) -ge 30 ]; }
}
_dd_since=-1 _dd_since_apps= _dd_packed=-1 _dd_measured=-1 _dd_unpack=0 _dd_capped=-1 _dd_backoff=30
_dd_pressure_at=-1 _dd_pressure_backoff=30 _dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_nogain=0 _dd_tier_pushed=0 _dd_tier_back=0 _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=()
_dd_client_pending=0 _dd_client_reserve=0 _dd_client_targets=() _dd_away=
_dd_sample_at= _dd_sample_available=0 _dd_sample_gpu=0 _dd_sample_unevictable=0 _dd_sample_shmem=0
while kill -0 $$ 2>/dev/null; do
dd_zram_scan
dd_memory_read
if dd_cap_due; then
if dd_over_cap; then
if [ "$_dd_capped" -lt 0 ] || [ $((SECONDS - _dd_capped)) -ge "$_dd_backoff" ]; then
dd_zram_usage "${_dd_pids[@]}" > /dev/null
if [ "$_dd_rss" -ge $((512 * 1024)) ]; then
dd_zram_send 1 "over the ${DD_RAM_CAP_MB} MB RAM cap, compressing the client" client
[ "$_dd_game" = 1 ] && _dd_packed=$SECONDS
else
step "RAM cap: over, client already small ($((_dd_rss / 1024)) MB resident), skipping it"
fi
dd_over_cap && dd_zram_send 1 "still over the RAM cap, compressing the rest of the session" session
if dd_over_cap; then
_dd_backoff=$((_dd_backoff * 2 > 600 ? 600 : _dd_backoff * 2))
step "RAM cap: still over after paging out, next try in ${_dd_backoff} s"
else
_dd_backoff=30
fi
_dd_capped=$SECONDS
fi
else
_dd_backoff=30
dd_memory_tick() {
if [ $((SECONDS - _dd_scan_at)) -ge 5 ]; then
_dd_scan_at=$SECONDS
dd_zram_scan
_dd_focus=1
if [ "$_dd_game" = 1 ]; then
dd_game_focused && _dd_focus=0 || _dd_focus=$?
fi
fi
_dd_preserved_growth=$_dd_growth _dd_preserved_fall=$_dd_fall
dd_client_pressure defer
_dd_preserved_growth=$_dd_growth _dd_preserved_fall=$_dd_fall
dd_session_pressure
dd_client_pressure_finish
_dd_focus=1
[ "$_dd_game" = 1 ] && { dd_game_focused && _dd_focus=0 || _dd_focus=$?; }
if [ "$_dd_game" = 1 ] && [ "$_dd_focus" = 0 ]; then
_dd_away=
if [ "$_dd_since" -lt 0 ] || [ "$_dd_since_apps" != "$_dd_apps" ]; then
_dd_since=$SECONDS _dd_since_apps=$_dd_apps
fi
if [ "${DD_ZRAM_CLIENT:-1}" = 1 ] && [ $((SECONDS - _dd_since)) -ge 20 ] && [ "${#_dd_pids[@]}" -gt 0 ] &&
{ [ "$_dd_packed" -lt 0 ] || [ $((SECONDS - _dd_packed)) -ge 300 ]; } && dd_client_can_pageout; then
dd_zram_send 1 "compressing the client" client
_dd_packed=$SECONDS
fi
elif [ "$_dd_game" != 1 ]; then
_dd_away=
if [ "$_dd_packed" -ge 0 ]; then
_dd_unpack=1
fi
_dd_since=-1 _dd_packed=-1 _dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_nogain=0 _dd_tier_pushed=0 _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=()
else
_dd_since=-1
if [ "$_dd_focus" = 1 ]; then
[ -n "${_dd_away-}" ] || _dd_away=$SECONDS
if [ "$_dd_game" = 1 ] && [ "$_dd_focus" = 1 ]; then
[ -n "$_dd_away" ] || _dd_away=$SECONDS
else
_dd_away=
fi
if [ "$_dd_packed" -ge 0 ]; then
_dd_unpack=1
fi
fi
if [ "$_dd_unpack" = 1 ] &&
{ [ "$_dd_game" = 0 ] || { [ "${_dd_ram_cap:-0}" = 0 ] && [ -n "${_dd_away-}" ] && [ $((SECONDS - _dd_away)) -ge 5 ]; }; } &&
! dd_over_cap && dd_client_can_readback; then
if [ "$_dd_game" = 0 ]; then
dd_zram_send 0 "memory recovered, reading the client back" client
else
dd_zram_send 0 "the client is in front of the game, reading it back" client
_dd_packed=-1
fi
_dd_unpack=0
dd_memory_read
[ ! -e /tmp/.dd-zram.hold ] || return 0
dd_memory_relieve
dd_memory_note
[ "$_dd_need" -gt 0 ] || dd_client_readback
}
declare -A _dd_deaf=() _dd_preloaded=()
_dd_scan_at=-5 _dd_session_at=-1 _dd_session=() _dd_focus=1 _dd_away=
_dd_page_kb=$(($(getconf PAGESIZE 2>/dev/null || echo 4096) / 1024)) _dd_returned=0 _dd_polls=0 _dd_pass_at=0 _dd_goal=0
_dd_sample_at= _dd_freed=0 _dd_client_out=0 _dd_note_client=0 _dd_note_session=0
_dd_trim_at=-30 _dd_back_at=-30 _dd_forced_at=-10 _dd_full_at=-60 _dd_noted_at=-5
_dd_rest=0 _dd_rest_until=0 _dd_rest_available=0
while kill -0 $$ 2>/dev/null; do
dd_memory_tick
if [ "$_dd_available" -ge 0 ] &&
{ [ "$_dd_available" -lt $((_dd_mem_total * 2 / 5)) ] || [ "$_dd_rate" -ge $((16 * 1024)) ]; }; then
nap 1
else
nap 5
fi
dd_watch_nap
done
) &
fi
@@ -1529,11 +1422,10 @@ case $mode in
export STEAM_STEAMRT_RECURSION_GUARD=1
export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export SDL_VIDEO_X11_DGAMOUSE=0
dd_steam_path=$PATH
dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH"
dd_steam_angle=vulkan
dd_steam_presentation=()
if [ "${DD_STEAM_GL_PRESENT:-}" = 1 ]; then
dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH"
export DISABLE_GAMESCOPE_WSI=1 LIBGL_KOPPER_DISABLE=true
dd_steam_angle=gl
dd_steam_presentation=(-cef-disable-gpu-compositing)
@@ -66,19 +66,32 @@ BRIGHTNESS_JS = r"""
""".replace("__BINDING__", BRIGHTNESS_BINDING)
def control_request(name, text, directory):
path = os.path.join(directory, name)
with open(path + ".tmp", "w") as target:
target.write(text + "\n")
os.replace(path + ".tmp", path)
def brightness_request(payload, directory=CONTROLS_DIR):
try:
value = float(payload)
if not math.isfinite(value) or not 0 <= value <= 1:
return
path = os.path.join(directory, "brightness.request")
with open(path + ".tmp", "w") as target:
target.write(str(value) + "\n")
os.replace(path + ".tmp", path)
control_request("brightness.request", str(value), directory)
except (ValueError, TypeError, OSError):
return
def hdr_request(payload, directory=CONTROLS_DIR):
if payload not in ("0", "1"):
return
try:
control_request("hdr.request", payload, directory)
except OSError:
return
INSTALL_JS = r"""
(() => {
if (window.__droiddeckCompat) return "present";
@@ -256,6 +269,49 @@ TOUR_JS = r"""
return "off";
})()
"""
SET_SETTING_JS = r"""(field, value) => {
const bytes = [];
for (let n of [field * 8, value]) {
while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); }
bytes.push(n);
}
return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
}"""
HDR_BINDING = "droiddeckHdrChanged"
HDR_JS = r"""
(() => {
if (window.__droiddeckHdr) return "present";
const settings = window.settingsStore;
if (typeof settings?.clientSettings?.gamescope_hdr_enabled !== "boolean" ||
typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable";
const write = __SET_SETTING__;
const HOLD_MS = 3000;
const self = { known: settings.clientSettings.gamescope_hdr_enabled, pending: null, until: 0 };
self.set = value => {
if (typeof value !== "boolean") return true;
self.known = value;
if (settings.clientSettings.gamescope_hdr_enabled === value && self.pending === null) return true;
self.pending = value;
self.until = performance.now() + HOLD_MS;
write(21015, value ? 1 : 0);
return true;
};
self.check = () => {
const value = settings.clientSettings.gamescope_hdr_enabled;
if (typeof value !== "boolean") return;
if (self.pending !== null) {
if (value !== self.pending && performance.now() < self.until) return;
self.pending = null;
}
if (value === self.known) return;
self.known = value;
if (typeof window.__BINDING__ === "function") window.__BINDING__(value ? "1" : "0");
};
self.interval = setInterval(self.check, 500);
window.__droiddeckHdr = self;
return "installed";
})()
""".replace("__BINDING__", HDR_BINDING).replace("__SET_SETTING__", SET_SETTING_JS)
FRAME_LIMIT_JS = r"""
(() => {
if (window.__droiddeckFrameLimit) return "present";
@@ -281,14 +337,7 @@ FRAME_LIMIT_JS = r"""
}
if (!service || !settings?.clientSettings || typeof SteamClient.Settings?.SetSetting !== "function") return "unavailable";
const self = { timer: null };
const write = value => {
const bytes = [];
for (let n of [21002 * 8, value]) {
while (n > 127) { bytes.push((n & 127) | 128); n = Math.floor(n / 128); }
bytes.push(n);
}
return SteamClient.Settings.SetSetting(btoa(String.fromCharCode(...bytes)));
};
const write = value => (__SET_SETTING__)(21002, value);
self.check = async () => {
let rates;
try {
@@ -316,7 +365,7 @@ FRAME_LIMIT_JS = r"""
window.__droiddeckFrameLimit = self;
return "installed";
})()
"""
""".replace("__SET_SETTING__", SET_SETTING_JS)
WINDOW_BINDING = "droiddeckWindowAction"
WINDOW_TARGET = "createflags=18"
WINDOW_MOVES = {"nw": 0, "n": 1, "ne": 2, "e": 3, "se": 4, "s": 5, "sw": 6, "w": 7, "move": 8}
@@ -923,6 +972,9 @@ class Helper:
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
self.hdr_state = None
self.hdr_installed = False
self.hdr_retry = 0
self.windows = {}
self.windows_retry = 0
@@ -983,6 +1035,29 @@ class Helper:
except (Closed, OSError, ValueError):
del self.windows[ident]
def sync_hdr(self):
try:
with open(os.path.join(CONTROLS_DIR, "state.json")) as source:
value = json.load(source).get("hdr")
if not isinstance(value, bool):
return
if not self.hdr_installed:
if time.monotonic() < self.hdr_retry:
return
self.page.call("Runtime.addBinding", {"name": HDR_BINDING})
self.hdr_installed = self.page.evaluate(HDR_JS) in ("installed", "present")
if not self.hdr_installed:
self.hdr_retry = time.monotonic() + 10
return
if value != self.hdr_state:
if self.page.evaluate("window.__droiddeckHdr ? window.__droiddeckHdr.set(%s) : false" % json.dumps(value)) is True:
self.hdr_state = value
else:
self.hdr_state = None
self.hdr_installed = False
except (OSError, ValueError, TypeError, AttributeError):
pass
def sync_frame_limit(self):
if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry:
return
@@ -1095,6 +1170,9 @@ class Helper:
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
self.hdr_state = None
self.hdr_installed = False
self.hdr_retry = 0
self.sync_controls()
return True
@@ -1231,6 +1309,8 @@ class Helper:
for e in events:
if called(e, BRIGHTNESS_BINDING):
brightness_request(e.get("params", {}).get("payload"))
if called(e, HDR_BINDING):
hdr_request(e.get("params", {}).get("payload"))
if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
self.open_chooser(e["params"]["payload"])
return events
@@ -1260,6 +1340,7 @@ class Helper:
while True:
self.sync_controls()
self.sync_frame_limit()
self.sync_hdr()
self.sync_windows()
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
sources += [page.ws for page in self.windows.values()]
@@ -65,12 +65,14 @@ if [ -n "$repair" ]; then
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
done
fi
cache_only=
[ "${1:-}" = --cache ] && cache_only=1
sync=
if [ "${1:-}" = --sync ]; then
case "${2:-}" in publicbeta|steamdeck_publicbeta) sync=$2 ;; *) sync=$steam_channel ;; esac
manifest=steam_client_${sync}_linuxarm64
fi
[ -z "$sync" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
[ -z "$sync" ] && [ -z "$cache_only" ] && [ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
@@ -167,6 +169,46 @@ if ! fetch_manifest; then
fallback=1
fetch_manifest || exit 1
fi
if [ -n "$cache_only" ]; then
cache=$steam_root/package
cached=$cache/droiddeck-cached
[ "$(cat "$cached" 2>/dev/null)" = "$version" ] && exit 0
awk -F'"' '
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
$2 == "sha2" { sha[block] = $4 }
$2 == "size" { size[block] = $4 }
$2 == "zipvz" { vz[block] = $4 }
$2 == "sha2vz" { vzsha[block] = $4 }
END {
for (b in file) {
f = file[b]; h = sha[b]; n = size[b] + 0
if (b in vz) { f = vz[b]; h = vzsha[b]; k = split(f, bits, "_"); n = bits[k] + 0 }
print b, f, h, n
}
}
' "$work/manifest" | sort > "$work/cache"
mkdir -p "$cache"
total=$(grep -c . "$work/cache" 2>/dev/null || echo 0)
total_bytes=$(awk '{ n += $4 } END { print n + 0 }' "$work/cache")
done_bytes=0
i=0
while read -r block file sum size; do
i=$((i + 1))
progress "$cache/$file" "$block"
fetched=""
for host in "${cdn_order[@]}"; do
if fetch "$host/$file" "$cache/$file" "$size" "$sum" "$block"; then
fetched=$host
break
fi
done
[ -n "$fetched" ] || { echo "droiddeck-steam-install: $file failed on every CDN" >&2; exit 1; }
done_bytes=$((done_bytes + size))
done < "$work/cache"
echo "$version" > "$cached"
exit 0
fi
if [ -n "$sync" ]; then
installed=$(awk -F'"' '$2 == "version" { print $4; exit }' "$steam_root/package/$manifest.manifest" 2>/dev/null || true)
if [ -x "$steam_root/steamrtarm64/steam" ] && [ "$installed" = "$version" ]; then
@@ -10,6 +10,7 @@ import tempfile
DISPLAY = "External: gamescope|||Windowed"
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame")
SCREENSAVER_CURRENT = ("Customization", "Screensaver", "CurrentScreensaver")
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
@@ -137,6 +138,10 @@ def seed_no_screensaver_in_game(text):
return seed_value(text, SCREENSAVER_IN_GAME, '0')
def seed_bouncing_logo(text):
return seed_value(text, SCREENSAVER_CURRENT, 'steam-bouncinglogo')
def atomic_write(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
@@ -179,6 +184,11 @@ def initialize_screensaver(steam_root):
'== steam: no screensaver over a running game')
def initialize_screensaver_choice(steam_root):
return seed_once(steam_root, 'droiddeck-screensaver-choice-initialized', seed_bouncing_logo,
'== steam: bouncing logo screensaver')
if __name__ == '__main__':
status = 0
try:
@@ -186,7 +196,7 @@ if __name__ == '__main__':
except (OSError, ValueError, RecursionError) as error:
print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr)
status = 1
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)):
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver), ('screensaver choice', initialize_screensaver_choice)):
try:
step(sys.argv[1])
except (OSError, ValueError, RecursionError) as error:
@@ -713,14 +713,67 @@ x64_webhelper_gpu() {
x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && [ "${DD_X64_CEF_GPU:-1}" != 0 ]
}
x64_thunk_appconfigs() {
python3 - "$1" "$2" "$3" "$4" <<'PY' || true
import json, os, sys, tempfile
src, dst, cfg, on = sys.argv[1:5]
want = json.loads(cfg)
try:
names = sorted(os.listdir(src))
except OSError:
names = []
for name in names:
if not name.endswith(".json"):
continue
try:
db = json.load(open(os.path.join(src, name), encoding="utf-8")).get("ThunksDB") or {}
if not any(k in want["ThunksDB"] and not v for k, v in db.items()):
continue
except (OSError, ValueError, AttributeError):
continue
path = os.path.join(dst, name)
try:
cur = json.load(open(path, encoding="utf-8"))
except FileNotFoundError:
cur = None
except (OSError, ValueError):
continue
if cur is not None and cur != want:
continue
if on == "1" and cur is None:
try:
os.makedirs(dst, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=dst, prefix=".fex", suffix=".tmp")
except OSError:
continue
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(cfg + "\n")
os.link(tmp, path)
except OSError:
pass
finally:
try:
os.remove(tmp)
except OSError:
pass
elif on != "1" and cur is not None:
try:
os.remove(path)
except OSError:
pass
PY
}
x64_env() {
export -p | grep -v -E '^declare -x (PWD|OLDPWD|SHLVL|_)=' > "$X64_HOME/arm-session.env.new" || true
mv -f "$X64_HOME/arm-session.env.new" "$X64_HOME/arm-session.env"
unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME STEAM_RUNTIME_PREFER_HOST_LIBRARIES
gpu_vars="GALLIUM_DRIVER MESA_LOADER_DRIVER_OVERRIDE VK_ICD_FILENAMES VK_DRIVER_FILES LIBGL_KOPPER_DRI2 ZINK_DEBUG ZINK_DESCRIPTORS TU_DEBUG MESA_NO_ERROR mesa_glthread"
thunk_cfg='{"ThunksDB": {"GL": 1, "Vulkan": 1}}'
rm -f "$X64_HOME/game-gpu.env"
if x64_gpu; then
printf '{"ThunksDB": {"GL": 1, "Vulkan": 1}}\n' > "$X64_HOME/thunks.json"
printf '%s\n' "$thunk_cfg" > "$X64_HOME/thunks.json"
{
echo "export FEX_THUNKCONFIG='$X64_HOME/thunks.json'"
echo "unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER"
@@ -729,7 +782,10 @@ if x64_gpu; then
done
} > "$X64_HOME/game-gpu.env"
fi
if x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ]; then
client_thunks=0
x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && client_thunks=1
x64_thunk_appconfigs /usr/local/share/fex-emu/AppConfig "$X64_HOME/.config/fex-emu/AppConfig" "$thunk_cfg" "$client_thunks"
if [ "$client_thunks" = 1 ]; then
export FEX_THUNKCONFIG=$X64_HOME/thunks.json
unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE
else
@@ -5,6 +5,7 @@ import binascii
import json
import os
import re
import runpy
import shlex
import shutil
import stat
@@ -116,7 +117,7 @@ def through_client(folder, sidecar, timeout=CLIENT_TIMEOUT):
return str(answer.get("reason") or "failed")
def ask(channel, request, timeout=TIMEOUT):
def ask(channel, request, timeout=TIMEOUT, claim=False):
req_dir, resp_dir = channel / "req", channel / "resp"
req_dir.mkdir(parents=True, exist_ok=True)
resp_dir.mkdir(parents=True, exist_ok=True)
@@ -125,19 +126,33 @@ def ask(channel, request, timeout=TIMEOUT):
tmp.write_text(json.dumps(request))
os.rename(tmp, req_dir / (rid + ".json"))
answer = resp_dir / (rid + ".json")
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
def wait(seconds):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
value = json.loads(answer.read_text())
answer.unlink()
return value
except (OSError, ValueError):
time.sleep(0.05)
return None
value = wait(timeout)
if value is not None:
return value
for pending in (req_dir / (rid + ".json"), resp_dir / (rid + ".taken")):
abandoned = pending.with_name(rid + ".abandoned")
try:
value = json.loads(answer.read_text())
answer.unlink()
return value
except (OSError, ValueError):
time.sleep(0.05)
try:
(req_dir / (rid + ".json")).unlink()
except OSError:
pass
return None
os.rename(pending, abandoned)
except OSError:
continue
try:
abandoned.unlink()
except OSError:
pass
return None
return wait(CLAIMED_TIMEOUT) if claim else None
def windows_path(unix):
@@ -255,7 +270,8 @@ def create_prefix(compat_data, proton, timeout=120):
CLOUD_TIMEOUT = 15.0
CLOUD_STORES = ("gog", "epic")
CLAIMED_TIMEOUT = 120.0
CLOUD_STORES = ("gog", "epic", "ea", "ubisoft")
STORE_GAME = 10
RAN = 11
RAN_FAILED = 12
@@ -304,11 +320,14 @@ def exited(argv, code=0):
if found is not None and launch_dir and str(found[1].get("store")) == "ea":
ask(Path(launch_dir) / "stores", {"op": "ea-exited", "store": "ea", "id": str(found[1].get("id"))}, timeout=1.0)
log("ea %s exited" % found[1].get("id"))
return 0
if found is None or not launch_dir or not cloud_on(found[1]):
return 0
store, game = str(found[1].get("store")), str(found[1].get("id"))
ask(Path(launch_dir) / "stores", {"op": "cloud-up", "store": store, "id": game}, timeout=1.0)
try:
ask(Path(launch_dir) / "stores", {"op": "cloud-up", "store": store, "id": game}, timeout=1.0)
except OSError as error:
log("cloud %s %s up not requested (%s)" % (store, game, type(error).__name__))
return 0
log("cloud %s %s up requested" % (store, game))
return 0
@@ -319,6 +338,13 @@ UBISOFT_INSTALLER_URL = "https://static3.cdn.ubi.com/orbit/launcher_installer/Ub
ROCKSTAR_SERVICE = Path("/usr/local/lib/droiddeck-rockstar")
SERVICE_WAIT = 300.0
ROCKSTAR_FOLDER = "drive_c/Program Files/Rockstar Games/Launcher"
EPIC_SDK_SETUP = ROCKSTAR_FOLDER + "/Redistributables/SocialClub/Social-Club-Setup.exe"
SDK_SOURCE = ".droiddeck-sdk-source"
SDK_SETUP_LIMIT = 256 * 1024 * 1024
EPIC_PARENT = Path("/usr/local/lib/droiddeck-epic/EpicGamesLauncher.exe")
EPIC_PARENT_ON = 'set "DD_P=1"'
EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
EPIC_SERVICE_WAIT = 60.0
ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: Vice City", "gtasa": "GTA: San Andreas",
"gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"}
@@ -376,10 +402,9 @@ def rockstar_sdk(folder, sidecar):
return False
def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None):
def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None, launcher=True):
pfx = Path(compat_data) / "pfx"
launcher = r"C:\Program Files\Rockstar Games\Launcher"
values = [(r"Rockstar Games\Launcher", launcher)]
values = [(r"Rockstar Games\Launcher", r"C:\Program Files\Rockstar Games\Launcher")] if launcher else []
if title:
values.append(("Rockstar Games\\" + title, windows_path(str(folder))))
entries = [("Software\\" + view + key, value) for view in ("", "Wow6432Node\\") for key, value in values]
@@ -402,23 +427,29 @@ def rockstar_registry(folder, title, compat_data, proton, sdk_arch=None):
return result.returncode == 0
def rockstar_runtime(folder, exe, compat_data, arch):
def rockstar_runtime(folder, exe, compat_data, arch, installer=None):
if arch == "x86":
rockstar_runtime(folder, exe, compat_data, "x64")
rockstar_runtime(folder, exe, compat_data, "x64", installer)
pfx = Path(compat_data) / "pfx"
target = pfx / "drive_c" / ("Program Files (x86)" if arch == "x86" else "Program Files") / "Rockstar Games/Social Club"
if not target.resolve().is_relative_to(pfx.resolve()):
raise ValueError("invalid Social Club destination")
required = ("socialclub.dll", "socialclub.pak") + (("SocialClubHelper.exe",) if arch == "x64" else ())
marker = target / ".droiddeck-installing"
if all((target / name).is_file() for name in required) and not marker.exists():
source_file, stamp = target / SDK_SOURCE, None
if installer is not None:
info = installer.stat()
stamp = "%d %d %s" % (info.st_size, info.st_mtime_ns, installer)
current = stamp is None or source_file.is_file() and not source_file.is_symlink() and source_file.read_text(errors="replace") == stamp
if all((target / name).is_file() for name in required) and not marker.exists() and current:
return "present"
root = folder.resolve()
installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent)
for sub in ("Redistributables", "Installers")]
installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= 256 * 1024 * 1024), None)
if installer is None:
return "game-runtime"
root = folder.resolve()
installers = [base / sub / "Social-Club-Setup.exe" for base in (root, exe.parent)
for sub in ("Redistributables", "Installers")]
installer = next((p for p in installers if p.is_file() and p.resolve().is_relative_to(root) and p.stat().st_size <= SDK_SETUP_LIMIT), None)
if installer is None:
return "game-runtime"
tool = shutil.which("7z")
if not tool:
return "no-unpacker"
@@ -470,15 +501,67 @@ def rockstar_runtime(folder, exe, compat_data, arch):
raise
os.replace(stage_path, output)
marker.unlink()
if stamp is not None:
source_file.unlink(missing_ok=True)
source_file.write_text(stamp)
return "installed"
def fetch_service(service, store, launch_dir, ask_app=None):
def epic_parent_switch(sidecar, env=None):
own = sidecar.get("env") if isinstance(sidecar.get("env"), dict) else {}
if EPIC_PARENT_SWITCH in own:
return str(own[EPIC_PARENT_SWITCH]).replace('"', "")
env = os.environ if env is None else env
try:
game_env = runpy.run_path(str(Path(__file__).resolve().with_name("droiddeck-game-env")))
try:
config = json.loads((Path(env.get("HOME") or "/root") / ".config/droiddeck/game-environment.json").read_text(encoding="utf-8"))
except FileNotFoundError:
config = {"version": 1}
env = game_env["apply_config"](env, config, game_env["game_id"](env))
except (OSError, ValueError, KeyError, TypeError, AttributeError):
pass
return env.get(EPIC_PARENT_SWITCH, "")
def wants_epic_parent(folder, switch):
if switch in ("0", "1"):
return switch == "1"
try:
return EPIC_PARENT_ON in (folder / LAUNCHER).read_text(errors="replace").splitlines()
except OSError:
return False
def epic_rockstar_sdk(folder, sidecar, compat_data, proton):
if not compat_data:
return None
pfx = Path(compat_data) / "pfx"
root = folder.resolve()
exe = (folder / str(sidecar.get("exe") or "").replace("\\", "/")).resolve()
if not exe.is_relative_to(root):
return None
setups = [(pfx / EPIC_SDK_SETUP, pfx)] + [(base / sub / "Social-Club-Setup.exe", root) for base in (root, exe.parent)
for sub in ("Redistributables", "Installers")]
setup = next((path for path, inside in setups if path.is_file() and path.resolve().is_relative_to(inside.resolve())
and path.stat().st_size <= SDK_SETUP_LIMIT), None)
if setup is None:
return None
made = "present" if (pfx / "user.reg").is_file() else create_prefix(compat_data, proton)
if made not in ("created", "present"):
return "prefix-" + made
state = rockstar_runtime(folder, exe, compat_data, "x64", setup)
if state in ("present", "installed") and not rockstar_registry(folder, None, compat_data, proton, sdk_arch="x64", launcher=False):
return state + " registry-unavailable"
return state
def fetch_service(service, store, launch_dir, ask_app=None, timeout=SERVICE_WAIT):
if service.is_file():
return True
if not launch_dir:
return False
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=SERVICE_WAIT)
answer = (ask_app or ask)(Path(launch_dir) / "stores", {"op": "store-service", "store": store}, timeout=timeout)
return isinstance(answer, dict) and bool(answer.get("ok")) and service.is_file()
@@ -1601,7 +1684,7 @@ def main(argv):
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
prefix_id = os.path.basename(compat_data) if compat_data else ""
launch_dir = os.environ.get("DD_LAUNCH_DIR", "")
if launch_dir and cloud_on(sidecar):
if launch_dir and cloud_on(sidecar) and store != "ea":
made = create_prefix(compat_data, os.environ.get("DD_STORE_PROTON", ""))
if made != "present":
log("cloud %s %s prefix=%s" % (store, game, made))
@@ -1632,6 +1715,15 @@ def main(argv):
pass
log("ubisoft %s: not prepared (%s), starting directly" % (game, e))
if store == "epic":
try:
if launch_dir and not EPIC_PARENT.is_file() and wants_epic_parent(folder, epic_parent_switch(sidecar)):
got = fetch_service(EPIC_PARENT, "epic", launch_dir, timeout=EPIC_SERVICE_WAIT)
log("epic parent stand-in: " + ("staged" if got else "unavailable"))
sdk = epic_rockstar_sdk(folder, sidecar, compat_data, os.environ.get("DD_STORE_PROTON", ""))
except (OSError, ValueError, subprocess.TimeoutExpired) as error:
sdk = "failed (%s)" % type(error).__name__
if sdk:
log("epic rockstar sdk: " + sdk)
handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file()
if not handled:
drop_stale(folder)
@@ -1670,13 +1762,16 @@ def main(argv):
log("epic prefix=%s %s" % (prefix_id or "?", provision_prefix(compat_data)))
if store == "ea":
prepare_ea(folder, sidecar, compat_data, launch_dir)
return STORE_GAME
if not cloud_on(sidecar):
if store in CLOUD_STORES:
log("cloud %s %s down result=skipped reason=off" % (store, game))
return 0
return STORE_GAME if store == "ea" else 0
if launch_dir:
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT)
try:
answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT, claim=True)
except OSError as error:
log("cloud %s %s down result=failed reason=%s" % (store, game, type(error).__name__))
return STORE_GAME
if answer is None:
log("cloud %s %s down result=timeout" % (store, game))
else:
@@ -1,4 +1,5 @@
#!/usr/bin/python3
import hashlib
import hmac
import json
import os
@@ -11,6 +12,7 @@ import subprocess
import sys
import tempfile
import threading
import xml.etree.ElementTree as ElementTree
BIN = Path(__file__).resolve().parent
RUNTIME = Path('/usr/local/lib/droiddeck-xbox')
@@ -137,6 +139,117 @@ def register_classes(proton, prefix, env):
print('droiddeck-xbox: Windows Runtime class registration failed; launching without it', file=sys.stderr)
def game_config(exe):
path = Path(exe)
if not path.is_absolute():
return None
for folder in list(path.parents)[:4]:
config = folder / 'MicrosoftGame.config'
if config.is_file():
return config
return None
def windows_arguments(text):
arguments, current, quoted, started, at = [], [], False, False, 0
while at < len(text):
char = text[at]
if char == '\\':
run = len(text) - at - len(text[at:].lstrip('\\'))
at += run
if at < len(text) and text[at] == '"':
current.append('\\' * (run // 2))
if run % 2:
current.append('"')
at += 1
else:
current.append('\\' * run)
started = True
continue
if char == '"':
if quoted and text[at + 1:at + 2] == '"':
current.append('"')
at += 2
continue
quoted = not quoted
started = True
elif char in ' \t' and not quoted:
if started:
arguments.append(''.join(current))
current, started = [], False
else:
current.append(char)
started = True
at += 1
if started:
arguments.append(''.join(current))
return arguments
def install_actions(config):
try:
root = ElementTree.fromstring(config.read_bytes())
except (OSError, ElementTree.ParseError):
return []
actions = []
for registration in root.iter():
if registration.tag.rsplit('}', 1)[-1] != 'CustomInstallActions':
continue
folder = next((node.text or '' for node in registration if node.tag.rsplit('}', 1)[-1] == 'Folder'), '')
for node in registration.iter():
if node.tag.rsplit('}', 1)[-1] != 'InstallAction':
continue
name, file = node.get('Name', ''), node.get('File', '')
parts = [part for part in (folder.strip() + '\\' + file).replace('/', '\\').split('\\') if part]
if not name or not file or any(part in ('.', '..') or ':' in part for part in parts):
continue
target = config.parent.joinpath(*parts)
try:
inside = target.resolve().is_relative_to(config.parent.resolve())
except OSError:
inside = False
if inside and target.is_file() and target.suffix.lower() in ('.msi', '.exe'):
actions.append((name, target, windows_arguments(node.get('Arguments', ''))))
return actions
def run_install_actions(proton, prefix, exe, env):
config = game_config(exe)
if config is None:
return
done = prefix / 'drive_c' / 'ProgramData' / 'DroidDeck' / 'install-actions'
for name, target, arguments in install_actions(config):
try:
content = hashlib.sha256()
with target.open('rb') as source:
for block in iter(lambda: source.read(1 << 20), b''):
content.update(block)
identity = hashlib.sha256(name.encode('utf-8') + b'\0' + content.digest()).hexdigest()[:24]
marker = done / ('%s-%s' % (''.join(c for c in name if c.isalnum() or c in '-_')[:64], identity))
if marker.exists():
continue
except OSError as error:
print('droiddeck-xbox: install action %s could not be read (%s); launching without it' % (name, error), file=sys.stderr)
continue
windows = 'Z:' + str(target).replace('/', '\\')
if target.suffix.lower() == '.msi':
command = [proton, 'run', 'msiexec', '/i', windows, *arguments]
else:
command = [proton, 'run', windows, *arguments]
try:
code = subprocess.run(command, stdout=sys.stderr, env=env, timeout=600).returncode
except (OSError, subprocess.TimeoutExpired):
code = None
if code != 0:
print('droiddeck-xbox: install action %s did not finish; launching without it' % name, file=sys.stderr)
continue
try:
done.mkdir(parents=True, exist_ok=True)
marker.touch()
except OSError as error:
print('droiddeck-xbox: install action %s finished but could not be recorded (%s)' % (name, error), file=sys.stderr)
def view_drive(prefix, exe):
path = Path(exe)
view = next((parent for parent in path.parents if parent.name.startswith('droiddeck-xbox-')), None)
@@ -184,6 +297,7 @@ def wine(argv, source_env=None):
target.unlink()
shutil.copyfile(RUNTIME / 'windows' / name, target)
register_classes(command[0], prefix, env)
run_install_actions(command[0], prefix, argv[0], env)
overrides = ';'.join(name[:-4] + '=n' for name in DLLS if name != 'libnghttp2.dll')
env['WINEDLLOVERRIDES'] = overrides + ';' + env.get('WINEDLLOVERRIDES', '')
exe, drive = view_drive(prefix, argv[0])
@@ -390,7 +504,7 @@ def launch(command, env):
raise RuntimeError('No Xbox account channel; start the game from DroidDeck')
reply = store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-prepare', 'id': sidecar['id']}, timeout=190)
if not reply or not reply.get('ok'):
raise RuntimeError('Xbox account service is unavailable; sign in again and retry')
raise RuntimeError((reply or {}).get('reason') or 'Xbox account service is unavailable; sign in again and retry')
stopped = threading.Event()
close = lambda: None
try:
@@ -404,7 +518,7 @@ def launch(command, env):
context.chmod(0o600)
owned_env = dict(env, DROIDDECK_XBOX_ACTIVE='1', DROIDDECK_XBOX_COMMAND_FILE=str(context),
XODUS_SOCKET=reply['socket'], XODUS_BRIDGE_PORT=str(port), XODUS_BRIDGE_KEY=key,
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'off')
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'none')
for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'):
owned_env.pop(name, None)
if reply.get('playfab'):
@@ -1089,9 +1089,10 @@ NATIVE_CHOICE = object()
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None, managed=None,
native_choices=(), tools=None):
native_choices=(), tools=None, removed=()):
tools = tools or {}
runnable = {n.lower() for n in runnable}
removed = {n.lower() for n in removed} - runnable
installed = set(installed)
picks = set(picks) | {app for app, platforms in tools.items() if "linux" not in platforms}
native = native or {}
@@ -1121,7 +1122,7 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks
target = native.get(app, default)
if not name and (app in native_choices or (app in current and app in FEX_DEFAULT_APPS)):
target = NATIVE_CHOICE
stale = unrunnable(name, runnable)
stale = unrunnable(name, runnable) or name.lower() in removed
if name and not stale and (mine is None or name != mine):
continue
if target is NATIVE_CHOICE:
@@ -1163,6 +1164,26 @@ def followers(state, current):
return {app: name for app, name in current.items() if app != "0" and name == TOOL}
REPLACING = ".droiddeck-experimental-old"
def removed_tools(state, catalog, directory=None):
known = state.get("tools") if isinstance(state.get("tools"), list) else ()
previous = {t.get("name") for t in known if isinstance(t, dict) and not t.get("valve") and t.get("name")}
removed = previous - {t["name"] for t in catalog}
if directory is None:
return removed
known_dirs = {t.get("name"): t.get("dir") for t in known if isinstance(t, dict)}
return {name for name in removed if isinstance(known_dirs.get(name), str) and
not os.path.lexists(os.path.join(directory, known_dirs[name])) and
not os.path.lexists(os.path.join(directory, REPLACING, known_dirs[name]))}
def removed_dirs(state, removed):
known = state.get("tools") if isinstance(state.get("tools"), list) else ()
return {t["dir"] for t in known if isinstance(t, dict) and not t.get("valve") and t.get("name") in removed and isinstance(t.get("dir"), str)} - {""}
def tool_entry(name, display, path, valve):
return {"name": name, "display": display, "dir": os.path.basename(path) if path else "", "valve": valve}
@@ -1248,15 +1269,19 @@ def valid_game_request(app, request):
request["dir"] != "" and isinstance(request.get("valve"), bool)))
def settle_game_requests(requests, state, current, catalog, missing_is_cleared=False):
def settle_game_requests(requests, state, current, catalog, missing_is_cleared=False, removed=()):
recorded = state.get("games_applied")
if isinstance(recorded, dict):
applied = dict(recorded)
else:
applied = dict(requests) if "tools" in state else {}
by_name = {t["name"]: t for t in catalog}
gone = removed_dirs(state, removed)
out = dict(requests)
for app, request in requests.items():
if isinstance(request, dict) and request.get("valve") is False and isinstance(request.get("dir"), str) and request["dir"] in gone:
del out[app]
continue
if not valid_game_request(app, request) or app not in applied or applied[app] != request:
continue
if request is None:
@@ -1281,10 +1306,10 @@ def settle_game_requests(requests, state, current, catalog, missing_is_cleared=F
return out, out != requests
def settled_game_requests(state, current, catalog, missing_is_cleared=False, directory=None):
def settled_game_requests(state, current, catalog, missing_is_cleared=False, directory=None, removed=()):
for _ in range(2):
requests, text = read_game_requests(directory)
settled, moved = settle_game_requests(requests, state, current, catalog, missing_is_cleared)
settled, moved = settle_game_requests(requests, state, current, catalog, missing_is_cleared, removed)
if not moved or write_game_requests(settled, text, directory):
return settled
return None
@@ -1579,7 +1604,8 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
set_mappings(tokens, mapping, moved)
current.update(moved)
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
requests = settled_game_requests(state, current, catalog, not steam_running(), directory)
removed = removed_tools(state, catalog, os.path.join(steam_root, "compatibilitytools.d"))
requests = settled_game_requests(state, current, catalog, not steam_running(), directory, removed)
overrides = requested_games(requests or {}, catalog)
managed = state.get("auto", {}).keys() if isinstance(state.get("auto"), dict) else ()
native_choices = state.get("native_choices", ())
@@ -1590,7 +1616,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
current.setdefault(app, "")
changes, auto = plan_mapping(
current, apps, names, default, followers(state, current), native, picks,
overrides, managed, native_choices, tool_platforms(steam_root))
overrides, managed, native_choices, tool_platforms(steam_root), removed)
set_mappings(tokens, mapping, changes)
text = serialize(tokens)
if text != serialize(tokenize(original)):