Merge remote-tracking branch 'droiddeck/main' into feat/malibridge

# Conflicts:
#	README.md
#	app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java
#	app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt
#	app/src/main/res/values-ar/strings.xml
#	app/src/main/res/values-b+es+419/strings.xml
#	app/src/main/res/values-bg/strings.xml
#	app/src/main/res/values-cs/strings.xml
#	app/src/main/res/values-da/strings.xml
#	app/src/main/res/values-de/strings.xml
#	app/src/main/res/values-el/strings.xml
#	app/src/main/res/values-es/strings.xml
#	app/src/main/res/values-fi/strings.xml
#	app/src/main/res/values-fr/strings.xml
#	app/src/main/res/values-hi/strings.xml
#	app/src/main/res/values-hu/strings.xml
#	app/src/main/res/values-in/strings.xml
#	app/src/main/res/values-it/strings.xml
#	app/src/main/res/values-ja/strings.xml
#	app/src/main/res/values-ko/strings.xml
#	app/src/main/res/values-ms/strings.xml
#	app/src/main/res/values-nb/strings.xml
#	app/src/main/res/values-nl/strings.xml
#	app/src/main/res/values-pl/strings.xml
#	app/src/main/res/values-pt-rPT/strings.xml
#	app/src/main/res/values-pt/strings.xml
#	app/src/main/res/values-ro/strings.xml
#	app/src/main/res/values-ru/strings.xml
#	app/src/main/res/values-sv/strings.xml
#	app/src/main/res/values-th/strings.xml
#	app/src/main/res/values-tr/strings.xml
#	app/src/main/res/values-uk/strings.xml
#	app/src/main/res/values-vi/strings.xml
#	app/src/main/res/values-zh-rCN/strings.xml
#	app/src/main/res/values-zh-rHK/strings.xml
#	app/src/main/res/values-zh-rTW/strings.xml
#	app/src/main/res/values/strings.xml
#	tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env
This commit is contained in:
maxjivi05 committed 2026-10-30 11:58:55 -04:00
commit 0a5955d6fa
731 files changed
+54131 -2491

No files matched your search

@@ -605,9 +605,56 @@ KEYBOARD_CHECK_SECONDS = 30
KEYBOARD_JS = r"""
(() => {
const self = window.__droiddeckKeyboard || (window.__droiddeckKeyboard = { watched: new WeakSet(), last: null });
self.wrapped = self.wrapped || new WeakSet();
self.route = self.route === true;
self.wrap = vkm => {
if (!vkm || self.wrapped.has(vkm) || typeof vkm.ShowVirtualKeyboard !== "function") return;
self.wrapped.add(vkm);
const show = vkm.ShowVirtualKeyboard;
vkm.ShowVirtualKeyboard = function (ref, props, modal) {
if (self.route && !modal && typeof this.SetActiveVirtualKeyboardTarget === "function" &&
!this.BUseVRKeyboard?.() && !this.m_Instance?.IsDesktopOverlayWindow?.()) {
this.SetActiveVirtualKeyboardTarget(ref, props);
self.follow(this);
if (typeof window.__BINDING__ === "function") window.__BINDING__("request");
return;
}
return show.call(this, ref, props, modal);
};
};
self.editing = vkm => {
let el = null;
try { el = vkm?.m_ownerWindow?.document?.activeElement || null; } catch (e) {}
if (!el) return null;
return el.tagName === "TEXTAREA" || el.isContentEditable === true ||
(el.tagName === "INPUT" && !/^(button|checkbox|radio|range|submit|reset|file|image|color)$/i.test(el.type || ""));
};
self.follow = vkm => {
self.active = vkm;
self.missed = 0;
self.seen = false;
self.follower = self.follower || setInterval(() => {
if (!self.active) return;
const ref = self.active.m_currentVirtualKeyboardRef;
const editing = self.editing(self.active);
const valid = !!ref && (editing !== null ? editing :
(typeof ref.BIsElementValidForInput !== "function" || ref.BIsElementValidForInput()));
if (valid) self.seen = true;
if (self.route && ref && (valid || !self.seen)) {
self.missed = 0;
return;
}
if (++self.missed < 2) return;
self.active = null;
clearInterval(self.follower);
self.follower = null;
if (typeof window.__BINDING__ === "function") window.__BINDING__("dismiss");
}, 150);
};
self.check = () => {
let showing = false;
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
self.wrap(win?.VirtualKeyboardManager);
const value = win?.VirtualKeyboardManager?.IsShowingVirtualKeyboard;
if (!value) continue;
if (!self.watched.has(value) && typeof value.Subscribe === "function") {
@@ -626,6 +673,29 @@ KEYBOARD_JS = r"""
return self.check();
})()
""".replace("__BINDING__", KEYBOARD_BINDING)
KEYBOARD_ROUTE_SECONDS = 0.5
KEYBOARD_ROUTE_JS = r"""
(route => {
const self = window.__droiddeckKeyboard;
if (!self) return false;
self.route = route;
if (!route) return true;
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
const vkm = win?.VirtualKeyboardManager;
if (vkm?.m_bIsInlineVirtualKeyboardOpen?.m_currentValue === true && vkm?.m_bIsVirtualKeyboardModal?.m_currentValue !== true &&
typeof vkm.SetVirtualKeyboardHidden === "function") {
const ref = vkm.m_currentVirtualKeyboardRef, props = vkm.m_ActiveElementProps;
vkm.SetVirtualKeyboardHidden();
if (ref && typeof vkm.SetActiveVirtualKeyboardTarget === "function") {
vkm.SetActiveVirtualKeyboardTarget(ref, props);
if (typeof self.follow === "function") self.follow(vkm);
}
if (typeof window.__BINDING__ === "function") window.__BINDING__("request");
}
}
return true;
})(__ROUTE__)
""".replace("__BINDING__", KEYBOARD_BINDING)
class KeyboardWatcher(threading.Thread):
@@ -633,8 +703,14 @@ class KeyboardWatcher(threading.Thread):
super().__init__(daemon=True, name="keyboard")
self.agent_dir = agent_dir
self.path = agent_dir / "keyboard.json"
self.request_path = agent_dir / "keyboard-request.json"
self.dismiss_path = agent_dir / "keyboard-dismiss.json"
self.dismissals = 0
self.route_path = agent_dir / "keyboard-route"
self.showing = None
self.seq = 0
self.requests = 0
self.route = None
self.next_id = 0
self.attached = False
@@ -645,6 +721,30 @@ class KeyboardWatcher(threading.Thread):
self.seq += 1
write_json(self.path, {"steamKeyboard": showing, "seq": self.seq})
def request(self):
self.requests += 1
write_json(self.request_path, {"seq": self.requests})
def dismiss(self):
self.dismissals += 1
write_json(self.dismiss_path, {"seq": self.dismissals})
def wanted_route(self):
try:
return self.route_path.read_text().strip() == "bottom"
except OSError:
return False
def apply_route(self, ws, force=False):
route = self.wanted_route()
if route == self.route and not force:
return
result = self.call(ws, "Runtime.evaluate", {
"expression": KEYBOARD_ROUTE_JS.replace("__ROUTE__", "true" if route else "false"), "returnByValue": True})
if result.get("exceptionDetails"):
raise AgentError("JS_EXCEPTION", json.dumps(result["exceptionDetails"])[:500])
self.route = route
def run(self):
failures, last = 0, None
while True:
@@ -671,10 +771,18 @@ class KeyboardWatcher(threading.Thread):
try:
self.call(ws, "Runtime.addBinding", {"name": KEYBOARD_BINDING})
self.report(self.install(ws))
self.apply_route(ws, force=True)
self.attached = True
installed = time.monotonic()
while True:
if not ws.buffer and not select.select([ws.s], [], [], KEYBOARD_CHECK_SECONDS)[0]:
self.report(self.install(ws))
wait = min(KEYBOARD_ROUTE_SECONDS, KEYBOARD_CHECK_SECONDS)
if not ws.buffer and not select.select([ws.s], [], [], wait)[0]:
if time.monotonic() - installed >= KEYBOARD_CHECK_SECONDS:
self.report(self.install(ws))
self.apply_route(ws, force=True)
installed = time.monotonic()
else:
self.apply_route(ws)
continue
self.event(json.loads(ws.recv()))
finally:
@@ -702,7 +810,12 @@ class KeyboardWatcher(threading.Thread):
def event(self, message):
params = message.get("params") or {}
if message.get("method") == "Runtime.bindingCalled" and params.get("name") == KEYBOARD_BINDING:
self.report(params.get("payload") == "true")
if params.get("payload") == "request":
self.request()
elif params.get("payload") == "dismiss":
self.dismiss()
else:
self.report(params.get("payload") == "true")
def steam_idle_inhibit(agent_dir, inhibit):
@@ -1,5 +1,6 @@
#!/usr/bin/python3
import base64
import fcntl
import json
import os
import signal
@@ -87,6 +88,7 @@ class Spec:
self.info_fds = []
self.json_fds = []
self.keep_fds = []
self.lock_files = []
self.command = []
self.argv0 = None
@@ -159,6 +161,8 @@ def parse(argv):
read_fd(int(args[0]))
elif a == "--sync-fd":
s.keep_fds.append(int(args[0]))
elif a == "--lock-file":
s.lock_files.append(args[0])
elif a == "--info-fd":
s.info_fds.append(int(args[0]))
elif a == "--json-status-fd":
@@ -203,6 +207,31 @@ def remaps_nothing(s):
return True
def host_path(s, path):
for op in reversed(s.ops):
if op["t"] != "bind":
continue
dest = op["dest"].rstrip("/")
if path == dest or path.startswith(dest + "/"):
return op["src"].rstrip("/") + path[len(dest):]
return path
def hold_locks(s):
for path in s.lock_files:
try:
fd = os.open(host_path(s, path), os.O_RDONLY)
except OSError as e:
sys.stderr.write("bwrap: Can't open lock file %s: %s\n" % (path, e.strerror))
sys.exit(1)
try:
fcntl.lockf(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
except OSError as e:
sys.stderr.write("bwrap: Can't lock file %s: %s\n" % (path, e.strerror))
sys.exit(1)
os.set_inheritable(fd, True)
def report_pid(s, pid):
for fd in s.info_fds:
try:
@@ -282,7 +311,7 @@ def run_by_app(s):
if payload is None:
break
if kind == b"P":
report_pid(s, int(payload))
report_pid(s, os.getpid())
elif kind == b"O":
out.write(payload)
out.flush()
@@ -301,6 +330,7 @@ def run_by_app(s):
def main():
s = parse(expand(sys.argv[1:]))
hold_locks(s)
if remaps_nothing(s):
run_here(s)
else:
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
free_name() {
local dir=$1 name=$2 base ext n=2
[ -e "$dir/$name" ] || { echo "$name"; return; }
base=${name%.*} ext=
[ "$base" != "$name" ] && [ -n "$base" ] && ext=.${name##*.} || base=$name
while [ -e "$dir/$base ($n)$ext" ]; do n=$((n + 1)); done
echo "$base ($n)$ext"
}
share() {
local android=$HOME/Storage/$1 link=$HOME/$2 f
[ -d "$android" ] && [ -w "$android" ] || return 0
[ "$(readlink "$link" 2>/dev/null)" = "$android" ] && return 0
if [ -L "$link" ]; then
rm -f "$link"
elif [ -d "$link" ]; then
shopt -s dotglob nullglob
for f in "$link"/*; do
mv -n -- "$f" "$android/$(free_name "$android" "${f##*/}")" || return 1
done
shopt -u dotglob nullglob
rmdir "$link" 2>/dev/null || mv "$link" "$link.old.$$" || return 1
elif [ -e "$link" ]; then
mv "$link" "$link.old.$$" || return 1
fi
ln -s "$android" "$link"
}
status=0
share Download Downloads || status=1
share Documents Documents || status=1
exit $status
+22
View File
@@ -0,0 +1,22 @@
#!/bin/bash
set -u
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
cores="libretro-core-info libretro-beetle-pce-fast libretro-beetle-psx libretro-beetle-vb libretro-beetle-wswan
libretro-bsnes-mercury-performance libretro-desmume libretro-gambatte libretro-genesisplusgx libretro-mgba
libretro-nestopia libretro-sameboy libretro-snes9x"
case "${1:-}" in
install)
echo "== STEP RetroArch"
droiddeck-root /usr/bin/apt-get update -q || { echo "== FAIL apt-get update"; exit 1; }
droiddeck-root /usr/bin/apt-get install -y -q retroarch retroarch-assets $cores || { echo "== FAIL apt-get install"; exit 1; }
echo "== STEP PPSSPP"
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo || { echo "== FAIL flathub"; exit 1; }
flatpak install --user -y --noninteractive flathub org.ppsspp.PPSSPP || { echo "== FAIL org.ppsspp.PPSSPP"; exit 1; }
printf '#!/bin/sh\nexec /usr/local/bin/droiddeck-flatpak-run org.ppsspp.PPSSPP "$@"\n' > /usr/local/bin/PPSSPPSDL.new &&
chmod 755 /usr/local/bin/PPSSPPSDL.new && mv -f /usr/local/bin/PPSSPPSDL.new /usr/local/bin/PPSSPPSDL || { echo "== FAIL PPSSPPSDL"; exit 1; }
;;
*)
echo "usage: droiddeck-emulators install" >&2
exit 2
;;
esac
@@ -100,6 +100,10 @@ CLIENT_ENV = {
"JSC_useDFGJIT": "0",
"JSC_useFTLJIT": "0",
}
HIDDEN_ENV = {
"DROIDDECK_EPIC_HIDDEN": "1",
"EGL_DISABLE_STORE_PREWARM": "1",
}
KEPT_ENV = ("HOME", "USER", "LOGNAME", "LANG", "LANGUAGE", "LC_ALL", "LC_MESSAGES", "TZ", "XDG_RUNTIME_DIR", "BL_LAUNCH_DIR")
LAUNCH_VERBS = ("waitforexitandrun", "run", "runinprefix")
EPIC_ARGS = ("-auth_", "-epic")
@@ -725,7 +729,7 @@ def fex_environment(fex, files, env):
return result
def client_environment(base, fex, files, display, bus, broker, a11y=None):
def client_environment(base, fex, files, display, bus, broker, a11y=None, hidden=False):
env = {name: base[name] for name in KEPT_ENV if base.get(name)}
env.setdefault("HOME", HOME)
env.setdefault("LANG", "C.UTF-8")
@@ -734,6 +738,8 @@ def client_environment(base, fex, files, display, bus, broker, a11y=None):
env["DBUS_SESSION_BUS_ADDRESS"] = bus
env[BROKER_ENV] = broker
env.update(CLIENT_ENV)
if hidden:
env.update(HIDDEN_ENV)
if a11y:
for name in A11Y_OFF:
env.pop(name, None)
@@ -1248,7 +1254,7 @@ class Session:
path = broker_path()
self.broker = Broker(path, self.mode, base)
write_json(instance_file(), {"pid": os.getpid(), "mode": self.mode, "bus": bus, "broker": path})
env = client_environment(base, fex, files, display, bus, path, self.a11y)
env = client_environment(base, fex, files, display, bus, path, self.a11y, hidden=self.mode == "hidden")
self.command = [fex["bin"], os.path.join(app_dir, "AppRun")]
self.env = env
say("starting the Epic Games Launcher %s (%s, display %s)" % (current.get("app"), self.mode, display))
@@ -5,6 +5,7 @@ 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"
if command -v pacman >/dev/null 2>&1; then
PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy"
while read -r pkg probe; do
[ -n "$pkg" ] || continue
@@ -77,7 +78,13 @@ done
mv -f "$WORK/installed.new" "$WORK/installed"
find "$WORK/pkg" -type f -mtime +1 -delete 2>/dev/null
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
else
command -v flatpak >/dev/null 2>&1 || fail "Flatpak is missing from the runtime"
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
fi
missing=$(for f in /usr/bin/flatpak /usr/lib/libflatpak.so.0 /usr/lib/libostree-1.so.1 /usr/lib/aarch64-linux-gnu/libflatpak.so.0 /usr/lib/aarch64-linux-gnu/libostree-1.so.1 /usr/bin/xdg-dbus-proxy; do
[ -e "$f" ] || continue
ldd "$f" 2>&1 | grep -E 'not found|version .* not found'
done | sort -u)
[ -z "$missing" ] || { echo "$missing"; fail "Flatpak is missing libraries"; }
@@ -97,7 +104,7 @@ Description=Central repository of Flatpak applications
Icon=https://dl.flathub.org/repo/logo.svg
GPGKey=mQINBFlD2sABEADsiUZUOYBg1UdDaWkEdJYkTSZD68214m8Q1fbrP5AptaUfCl8KYKFMNoAJRBXn9FbE6q6VBzghHXj/rSnA8WPnkbaEWR7xltOqzB1yHpCQ1l8xSfH5N02DMUBSRtD/rOYsBKbaJcOgW0K21sX+BecMY/AI2yADvCJEjhVKrjR9yfRX+NQEhDcbXUFRGt9ZT+TI5yT4xcwbvvTu7aFUR/dH7+wjrQ7lzoGlZGFFrQXSs2WI0WaYHWDeCwymtohXryF8lcWQkhH8UhfNJVBJFgCY8Q6UHkZG0FxMu8xnIDBMjBmSZKwKQn0nwzwM2afskZEnmNPYDI8nuNsSZBZSAw+ThhkdCZHZZRwzmjzyRuLLVFpOj3XryXwZcSefNMPDkZAuWWzPYjxS80cm2hG1WfqrG0Gl8+iX69cbQchb7gbEb0RtqNskTo9DDmO0bNKNnMbzmIJ3/rTbSahKSwtewklqSP/01o0WKZiy+n/RAkUKOFBprjJtWOZkc8SPXV/rnoS2dWsJWQZhuPPtv3tefdDiEyp7ePrfgfKxuHpZES0IZRiFI4J/nAUP5bix+srcIxOVqAam68CbAlPvWTivRUMRVbKjJiGXIOJ78wAMjqPg3QIC0GQ0EPAWwAOzzpdgbnG7TCQetaVV8rSYCuirlPYN+bJIwBtkOC9SWLoPMVZTwQARAQABtC5GbGF0aHViIFJlcG8gU2lnbmluZyBLZXkgPGZsYXRodWJAZmxhdGh1Yi5vcmc+iQJUBBMBCAA+FiEEblwF2XnHba+TwIE1QYTdTZB6fK4FAllD2sACGwMFCRLMAwAFCwkIBwIGFQgJCgsCBBYCAwECHgECF4AACgkQQYTdTZB6fK5RJQ/+Ptd4sWxaiAW91FFk7+wmYOkEe1NY2UDNJjEEz34PNP/1RoxveHDt43kYJQ23OWaPJuZAbu+fWtjRYcMBzOsMCaFcRSHFiDIC9aTp4ux/mo+IEeyarYt/oyKb5t5lta6xaAqg7rwt65jW5/aQjnS4h7eFZ+dAKta7Y/fljNrOznUp81/SMcx4QA5G2Pw0hs4Xrxg59oONOTFGBgA6FF8WQghrpR7SnEe0FSEOVsAjwQ13Cfkfa7b70omXSWp7GWfUzgBKyoWxKTqzMN3RQHjjhPJcsQnrqH5enUu4Pcb2LcMFpzimHnUgb9ft72DP5wxfzHGAWOUiUXHbAekfq5iFks8cha/RST6wkxG3Rf44Zn09aOxh1btMcGL+5xb1G0BuCQnA0fP/kDYIPwh9z22EqwRQOspIcvGeLVkFeIfubxpcMdOfQqQnZtHMCabV5Q/Rk9K1ZGc8M2hlg8gHbXMFch2xJ0Wu72eXbA/UY5MskEeBgawTQnQOK/vNm7t0AJMpWK26Qg6178UmRghmeZDj9uNRc3EI1nSbgvmGlpDmCxaAGqaGL1zW4KPW5yN25/qeqXcgCvUjZLI9PNq3Kvizp1lUrbx7heRiSoazCucvHQ1VHUzcPVLUKKTkoTP8okThnRRRsBcZ1+jI4yMWIDLOCT7IW3FePr+3xyuy5eEo9a25Ag0EWUPa7AEQALT/CmSyZ8LWlRYQZKYw417p7Z2hxqd6TjwkwM3IQ1irumkWcTZBZIbBgrSOg6CcXD2oWydCQHWi9qaxhuhEl2bJL5LskmBcMxVdQeD0LLHd8QUnbnnIby8ocvWN1alPfvJFjCUTrmD22U1ycOzRw2lIe4kiQONbOZtdWrVImQQSndjFlisitbmlWHvHm2lOOYy8+GJB7YffVV193hmnBSJffCy4bvkuLxsI+n1DhOzc7MPV3z6HGk4HiEcF0yyt9tCYhpsxHFdBoq2h771HfAcS0s98EVAqYMFnf9em+4cnYpdI6mhIfS1FQiKl6DBAYA8tT3ggla00DurPo0JwX/zN+PaO5h/6O9aCZwV7G6rbkgMuqMergXaf8oP38gr0z+MqWnkfM63Bodq68GP4l4hd02BoFBbDf38TMuGQB14+twJMdfbAxo2MbgluvQgfwHfZ2ca6gyEY+9s/YD1gugLjV+S6CB51WkFNe1z4tAPgJZNxUcKCbeaHNbthl8Hks/pY9RCEseX/EdfzF18epbSjJMPh4DPQXbUoFwmyuYcoBOPmvZHNl9hK7B/1RP8w1ZrXk8qdupC0SNbafX7270B7lMMVImzZetGsM9ypXJ6llhp3FwW09iseNyGJGPsr/dvTMGDXqOPfU/9SAS1LSTY4K9PbRtdrBE318YX8mIk5ABEBAAGJBHIEGAEIACYWIQRuXAXZecdtr5PAgTVBhN1NkHp8rgUCWUPa7AIbAgUJEswDAAJACRBBhN1NkHp8rsF0IAQZAQgAHRYhBFSmzd2JGfsgQgDYrFYnAunj7X7oBQJZQ9rsAAoJEFYnAunj7X7oR6AP/0KYmiAFeqx14Z43/6s2gt3VhxlSd8bmcVV7oJFbMhdHBIeWBp2BvsUf00I0Zl14ZkwCKfLwbbORC2eIxvzJ+QWjGfPhDmS4XUSmhlXxWnYEveSek5Tde+fmu6lqKM8CHg5BNx4GWIX/vdLi1wWJZyhrUwwICAxkuhKxuP2Z1An48930eslTD2GGcjByc27+9cIZjHKa07I/aLffo04V+oMT9/tgzoquzgpVV4jwekADo2MJjhkkPveSNI420bgT+Q7Fi1l0X1aFUniBvQMsaBa27PngWm6xE2ZYvh7nWCdd5g0c0eLIHxWwzV1lZ4Ryx4ITO/VL25ItECcjhTRdYa64sA62MYSaB0x3eR+SihpgP3wSNPFu3MJo6FKTFdi4CBAEmpWHFW7FcRmd+cQXeFrHLN3iNVWryy0HK/CUEJmiZEmpNiXecl4vPIIuyF0zgSCztQtKoMr+injpmQGC/rF/ELBVZTUSLNB350S0Ztvw0FKWDAJSxFmoxt3xycqvvt47rxTrhi78nkk6jATKGyvP55sO+K7Q7Wh0DXA69hvPrYW2eu8jGCdVGxi6HX7L1qcfEd0378S71dZ3g9o6KKl1OsDWWQ6MJ6FGBZedl/ibRfs8p5+sbCX3lQSjEFy3rx6n0rUrXx8U2qb+RCLzJlmC5MNBOTDJwHPcX6gKsUcXZrEQALmRHoo3SrewO41RCr+5nUlqiqV3AohBMhnQbGzyHf2+drutIaoh7Rj80XRh2bkkuPLwlNPf+bTXwNVGse4bej7B3oV6Ae1N7lTNVF4Qh+1OowtGjmfJPWo0z1s6HFJVxoIof9z58Msvgao0zrKGqaMWaNQ6LUeC9g9Aj/9Uqjbo8X54aLiYs8Z1WNc06jKP+gv8AWLtv6CR+l2kLez1YMDucjm7v6iuCMVAmZdmxhg5I/X2+OM3vBsqPDdQpr2TPDLX3rCrSBiS0gOQ6DwN5N5QeTkxmY/7QO8bgLo/Wzu1iilH4vMKW6LBKCaRx5UEJxKpL4wkgITsYKneIt3NTHo5EOuaYk+y2+Dvt6EQFiuMsdbfUjs3seIHsghX/cbPJa4YUqZAL8C4OtVHaijwGo0ymt9MWvS9yNKMyT0JhN2/BdeOVWrHk7wXXJn/ZjpXilicXKPx4udCF76meE+6N2u/T+RYZ7fP1QMEtNZNmYDOfA6sViuPDfQSHLNbauJBo/n1sRYAsL5mcG22UDchJrlKvmK3EOADCQg+myrm8006LltubNB4wWNzHDJ0Ls2JGzQZCd/xGyVmUiidCBUrD537WdknOYE4FD7P0cHaM9brKJ/M8LkEH0zUlo73bY4XagbnCqve6PvQb5G2Z55qhWphd6f4B6DGed86zJEa/RhS
REPO
if ! flatpak remote-list --user --columns=name 2>/dev/null | grep -qx flathub; then
if ! flatpak remote-list --columns=name 2>/dev/null | grep -qx flathub; then
out=$(flatpak remote-add --user --if-not-exists flathub "$WORK/flathub.flatpakrepo" 2>&1)
rc=$?
echo "$out"
@@ -107,6 +107,15 @@ def godot_sentry(game):
return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off"
@fix
def d3dgear_hook(game):
"""D3DGear's capture DLL left beside a game (The Crew 2) is loaded by it and hooks the DXGI swapchain;
under Wine the hook faults over a thousand times within seconds and the game never presents again:
black screen while the sound keeps playing."""
if "d3dgear64.dll" in game.files:
return {"WINEDLLOVERRIDES": "d3dgear64=d"}, [], "D3DGear capture hook off (it stops the game drawing)"
@fix
def deep_rock_gdk_raytracing(game):
if game.stem == "fsd-wingdk-shipping" and not any(game.has_arg(arg) for arg in ("-raytracing", "-noraytracing")):
@@ -122,6 +131,12 @@ def arkham_city_x87(game):
@fix
def teardown_vsync(game):
if game.stem == "teardown":
return {"vblank_mode": "2"}, [], "Teardown: OpenGL keeps the game's own vsync"
@fix
def protonfixes_off(game):
if game.stem in ("blackops3", "darksoulsremastered"):
@@ -142,6 +157,12 @@ def robocop_rogue_city_feature_level(game):
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "RoboCop: Rogue City: D3D12 feature level 12_1"
@fix
def reskate_feature_level(game):
if "skate.exe" in game.files and "reskate.dll" in game.files:
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "ReSkate (skate.): D3D12 feature level 12_1"
@fix
def cyberpunk_feature_level(game):
if game.stem == "cyberpunk2077" or (
@@ -254,7 +275,10 @@ def engine_fixes(exe, args):
for check in FIXES:
found = check(game)
if found:
env.update(found[0])
for name, value in found[0].items():
if name == "WINEDLLOVERRIDES" and env.get(name):
value = env[name] + ";" + value
env[name] = value
extra += found[1]
notes.append(found[2])
return env, extra, notes
@@ -339,6 +363,99 @@ def game_cores(env):
print("droiddeck-game-env: could not use game cores %r (%s)" % (text, error), file=sys.stderr)
def core_speeds(cores, root="/sys/devices/system/cpu"):
"""Each core's capacity, else its top clock; None when some core reports neither."""
for name in ("cpu_capacity", "cpufreq/cpuinfo_max_freq"):
speeds = {}
for core in cores:
try:
with open("%s/cpu%d/%s" % (root, core, name)) as f:
speeds[core] = int(f.read().strip())
except (OSError, ValueError):
break
else:
return speeds
return None
def fastest_first(cores):
"""The cores, fastest first; cores of equal or unknown speed keep their numeric order."""
cores = sorted(cores)
speeds = core_speeds(cores)
return sorted(cores, key=lambda core: -speeds[core]) if speeds else cores
def proton_cpu_limit(command, env):
"""This game's entry in Proton's own default_cpu_limit list: a core count, another value such as "P" as text, or None."""
app_id = env.get("SteamGameId", "")
if not command or not app_id.isdigit():
return None
try:
if os.path.getsize(command[0]) > 4 * 1024 * 1024:
return None
with open(command[0], encoding="utf-8", errors="replace") as f:
text = f.read()
except OSError:
return None
table = re.search(r"^default_cpu_limit = \{(.*?)^\}", text, re.M | re.S)
match = table and re.search(r'^\s*"%s"\s*:\s*"?(\w+)' % app_id, table.group(1), re.M)
if not match:
return None
value = match.group(1)
return int(value) if value.isdigit() else value
def cpu_topology(env, command=()):
"""Windows sees the game's cores fastest first, so a thread a game pins to CPU 0 runs on the fastest core."""
if "PROTON_CPU_TOPOLOGY" in env:
return
if "WINE_CPU_TOPOLOGY" in env:
if env["WINE_CPU_TOPOLOGY"]:
env["PROTON_CPU_TOPOLOGY"] = env["WINE_CPU_TOPOLOGY"]
return
picked = bool(env.get("DROIDDECK_GAME_CORES", "").strip() or env.get("BL_GAME_CPUS", "").strip())
fastest = env.get("DROIDDECK_FASTEST_CORES", "").strip() != "0" and game_id(env) is not None
if not (picked or fastest):
return
try:
cores = sorted(os.sched_getaffinity(0))
except OSError:
return
online = online_cores()
if not cores or cores[-1] >= len(online):
return
picked = picked and not set(cores) >= online
if fastest:
limit = None if picked else proton_cpu_limit(command, env)
if isinstance(limit, str):
return
cores = fastest_first(cores)[:limit or None]
elif set(cores) >= online:
return
if cores == sorted(online):
return
env["WINE_CPU_TOPOLOGY"] = env["PROTON_CPU_TOPOLOGY"] = "%d:%s" % (len(cores), ",".join(map(str, cores)))
print("droiddeck-game-env: Windows sees %d cores (%s)" % (len(cores), env["WINE_CPU_TOPOLOGY"]), file=sys.stderr)
def gl_vsync(env):
"""OpenGL stops waiting for each screen refresh; Steam's Frame Limit still holds the game through gamescope."""
# Wine asks for interval 1 on every GL window, and WineD3D's front-buffer drawing (DirectDraw,
# Direct3D 1-7) never lowers it, so those games ran at the refresh rate with no limit set.
if "vblank_mode" in env or game_id(env) is None:
return False
env["vblank_mode"] = "0"
return True
def game_images(env):
if game_id(env) is None:
return False
env.setdefault("GAMESCOPE_WSI_MIN_IMAGE_COUNT", "8")
env.setdefault("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT", "1")
return True
def apply_config(env, config, app_id, fixes=None):
if config.get("version") != 1:
raise ValueError("unsupported environment configuration")
@@ -379,6 +496,59 @@ def bridge_feature_level(env):
return "Mali bridge: VKD3D_FEATURE_LEVEL %s capped at 12_0 (no ray tracing or mesh shaders)" % was
GAME_DEBUG_CHANNELS = (
"timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree",
)
WINE_DEBUG_SELECTOR = re.compile(r"(?:(trace|warn|err|fixme))?([+-])([A-Za-z_][A-Za-z0-9_]*)")
def game_debug_channels(*values):
"""Normalize Wine selectors, retaining custom channels before required diagnostics."""
selectors = {}
for value in values:
if not isinstance(value, str) or "\0" in value or len(value) > 8192:
continue
for part in value.split(","):
part = part.strip()
match = WINE_DEBUG_SELECTOR.fullmatch(part)
if match is None:
continue
key = (match[1] or "", match[3])
# Move the last value to the end: global +/-all and per-class selectors
# have ordered semantics, so replacing a value in its old position is wrong.
selectors.pop(key, None)
selectors[key] = part
for channel in GAME_DEBUG_CHANNELS:
key = ("", channel)
selectors.pop(key, None)
selectors[key] = "+" + channel
formatted = ",".join(selectors.values())
if len(formatted) > 8192:
formatted = ",".join("+" + channel for channel in GAME_DEBUG_CHANNELS)
return formatted
def apply_game_debug_logs(env, config, debug_dir):
"""Apply app-owned diagnostics to a real game, without editing its launch command."""
if not isinstance(config, dict) or config.get("version") != 1 or config.get("gameDebugLogs") is not True:
return env
if (not isinstance(debug_dir, str) or "\0" in debug_dir or len(debug_dir) > 8192
or not os.path.isabs(debug_dir) or not os.path.isdir(debug_dir)):
print("droiddeck-game-env: game debug logs skipped; session log directory unavailable", file=sys.stderr)
return env
result = dict(env)
result.update({
"PROTON_LOG": "1",
"PROTON_LOG_DIR": debug_dir,
"PROTON_CRASH_REPORT_DIR": debug_dir,
"DXVK_LOG_PATH": debug_dir,
"DXVK_LOG_LEVEL": "debug",
"VKD3D_DEBUG": "info",
"WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
})
return result
def sync_config(config, app_id):
games = config.get("games", {})
return {
@@ -580,6 +750,7 @@ def main():
return 2
env = game_gpu(os.environ.copy())
mic_enabled = env.get("BL_MIC_ENABLED")
debug_dir = env.get("BL_DEBUG_DIR", "")
scripts = mark_install_scripts(command, env)
if scripts and install_scripts_done(scripts, env):
print("droiddeck-game-env: install scripts already run in this prefix; evaluator skipped", file=sys.stderr)
@@ -590,12 +761,17 @@ def main():
digest = None
app_id = game_id(env)
if app_id:
gl_default = gl_vsync(env)
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
if waiting:
game_images(env)
fixes = {}
if waiting:
command = skip_red_launcher(command)
ubisoft_overlay_off(env)
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
if not gl_default:
fixes.pop("vblank_mode", None)
for note in notes:
print("droiddeck-game-env: " + note, file=sys.stderr)
command += extra
@@ -604,10 +780,13 @@ def main():
own = fixes.get("WINEDLLOVERRIDES")
fixes["WINEDLLOVERRIDES"] = components + ";" + own if own else components
path = Path.home() / ".config/droiddeck/game-environment.json"
config = {}
try:
with path.open(encoding="utf-8") as source:
config = json.load(source)
if waiting:
if "vblank_mode" in config.get("shared", {}):
fixes.pop("vblank_mode", None)
env = apply_config(env, config, app_id, fixes)
else:
env = apply_config(env, sync_config(config, app_id), app_id)
@@ -616,6 +795,13 @@ def main():
env = apply_config(env, {"version": 1}, app_id, fixes)
except (OSError, ValueError, TypeError, AttributeError):
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
if waiting:
before_debug = env
env = apply_game_debug_logs(env, config, debug_dir)
if env is not before_debug:
print("droiddeck-game-env: game debug logs enabled for this launch", file=sys.stderr)
if gl_default and env.get("vblank_mode") == "0":
print("droiddeck-game-env: OpenGL does not wait for the screen refresh (vblank_mode=0)", file=sys.stderr)
if app_id and len(command) > 1 and command[1] == "waitforexitandrun":
command = offline_without_anticheat(command, env)
if mic_enabled == "0":
@@ -626,6 +812,7 @@ def main():
print("droiddeck-game-env: " + note, file=sys.stderr)
env = force_ssbs(command, env)
game_cores(env)
cpu_topology(env, command)
try:
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
except Exception as error:
@@ -0,0 +1,344 @@
#!/usr/bin/python3
"""GOG patch installers and the lease shared by maintenance and game launches."""
import fcntl
import errno
import json
import os
from pathlib import Path
import runpy
import subprocess
import sys
import tempfile
import time
BIN = Path(__file__).resolve().parent
IDLE = {"wineserver", "services.exe", "winedevice.exe", "explorer.exe", "rpcss.exe", "plugplay.exe",
"conhost.exe", "lsass.exe", "svchost.exe", "steam.exe", "wineboot.exe", "winemenubuilder.exe"}
def control(folder):
folder = Path(folder).resolve(strict=True)
root = folder / ".droiddeck-gog"
if root.is_symlink():
raise ValueError("GOG control directory is a symbolic link")
root.mkdir(exist_ok=True)
return root
def read(path):
if path.is_symlink():
raise ValueError("GOG metadata is a symbolic link")
return json.loads(path.read_text(encoding="utf-8"))
def write(path, value):
if path.is_symlink():
raise ValueError("GOG metadata is a symbolic link")
descriptor, name = tempfile.mkstemp(prefix=path.name + ".", suffix=".new", dir=path.parent)
temporary = Path(name)
try:
with os.fdopen(descriptor, "w") as stream:
json.dump(value, stream)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
try:
os.fsync(directory)
except OSError as error:
if error.errno not in (errno.EINVAL, errno.ENOTSUP):
raise
finally:
os.close(directory)
finally:
temporary.unlink(missing_ok=True)
def lock_file(root):
return os.fdopen(os.open(root / "lease", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600), "r+")
def generation(pid):
try:
return Path("/proc/%s/stat" % pid).read_text().rsplit(")", 1)[1].split()[19]
except (OSError, IndexError):
return None
def lease(folder, owner):
root = control(folder)
with lock_file(root) as stream:
fcntl.lockf(stream, fcntl.LOCK_SH | fcntl.LOCK_NB)
sidecar = read(Path(folder) / ".droiddeck-store.json")
if sidecar.get("state", "installed") != "installed":
raise ValueError("Resume or recover the GOG update before playing")
journal = root / "operation.json"
if journal.exists() and read(journal).get("phase") != "download":
raise ValueError("GOG maintenance is incomplete")
start = generation(owner)
if start is None:
raise ValueError("Game launcher has exited")
print("ready", flush=True)
sys.stdout.close()
while generation(owner) == start:
time.sleep(0.25)
return 0
def desktop_environment(base, proc=Path("/proc")):
env = dict(base)
if env.get("DROIDDECK_GOG_DESKTOP") != "1":
return env
deadline = time.monotonic() + 45
while True:
for entry in proc.iterdir():
if not entry.name.isdigit():
continue
try:
command = (entry / "cmdline").read_bytes().split(b"\0")[0]
if command != b"/usr/bin/plasmashell":
continue
values = dict(os.fsdecode(item).split("=", 1) for item in (entry / "environ").read_bytes().split(b"\0") if b"=" in item)
if values.get("BL_DESKTOP") != "1" or values.get("XDG_RUNTIME_DIR") != env.get("XDG_RUNTIME_DIR"):
continue
if not values.get("DISPLAY") or values.get("WAYLAND_DISPLAY") == env.get("WAYLAND_DISPLAY"):
continue
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "BL_DESKTOP"):
if key in values:
env[key] = values[key]
return env
except (OSError, ValueError):
continue
if time.monotonic() >= deadline:
raise ValueError("The desktop display is not ready; resume the Linux session and verify recovery before retrying")
time.sleep(0.25)
def target_for(folder, appid, game):
run = runpy.run_path(str(BIN / "droiddeck-proton-run"))["main"].__globals__
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or run["STEAM_ROOT"]
target = run["shortcut_target"](str(int(appid) & 0xffffffff), str(game), str(folder), root)
target.install = str(folder)
return run, root, target
def runner(folder, appid, game, graphical=False):
run, root, target = target_for(folder, appid, game)
available = run["tools"](root)
name, _ = run["choose_tool"](target.appid, run["mapping"](root), available)
if name is None:
raise ValueError("No Proton tool is installed for this game")
tool, command = available[name]
base = desktop_environment(os.environ) if graphical else dict(os.environ)
env = run["environment"](base, target, tool, root, window=base.get("BL_DESKTOP") == "1")
env["DROIDDECK_GOG_MAINTENANCE"] = "1"
# Installer copy routines use x87 integer loads/stores; reduced precision corrupts paths (FEX #5827).
env["FEX_X87REDUCEDPRECISION"] = "0"
env.pop("BL_STORE_EXIT", None)
return str(Path(tool) / command), env, target.compatdata
def active(prefix, proc=Path("/proc")):
result = []
prefix = os.path.realpath(os.path.join(prefix, "pfx"))
for entry in proc.iterdir():
if not entry.name.isdigit():
continue
try:
env = dict(part.split(b"=", 1) for part in (entry / "environ").read_bytes().split(b"\0") if b"=" in part)
if os.path.realpath(os.fsdecode(env.get(b"WINEPREFIX", b""))) != prefix:
continue
args = (entry / "cmdline").read_bytes().split(b"\0")
name = os.fsdecode(args[0]).replace("\\", "/").rsplit("/", 1)[-1].lower()
if name not in IDLE:
result.append(int(entry.name))
except (OSError, ValueError):
continue
return result
def idle(folder, appid, game):
_, _, target = target_for(folder, appid, game)
if active(target.compatdata):
raise ValueError("Close the GOG game before maintenance")
return 0
def validate_installer(folder, installer):
root = control(folder)
path = Path(installer)
if path.is_symlink() or not path.resolve(strict=True).is_relative_to(root / "downloads") or path.suffix.lower() != ".exe":
raise ValueError("The patch executable is outside GOG download storage")
with path.open("rb") as stream:
if stream.read(2) != b"MZ":
raise ValueError("The GOG patch is not a Windows executable")
return path
def installer_arguments(path):
with path.open("rb") as stream:
data = stream.read(4 * 1024 * 1024)
return ["/NOGUI"] if b"Inno Setup Setup Data" in data else []
def start(folder, appid, installer, game):
root = control(folder)
validate_installer(folder, installer)
with lock_file(root) as stream:
fcntl.lockf(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
journal = read(root / "operation.json")
if journal.get("phase") != "patch-ready":
raise ValueError("The patch must be selected again before it can run")
idle(folder, appid, game)
journal["phase"] = "patch-starting"
write(root / "operation.json", journal)
write(root / "patch-status.json", {"state": "starting", "startedAt": time.time()})
with (root / "patch.log").open("ab") as log:
subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "run", folder, appid, installer, game],
stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True)
return 0
def status(folder):
root = control(folder)
path = root / "patch-status.json"
result = read(path)
ended = result.get("state") == "running" and generation(result.get("pid")) != result.get("generation")
abandoned = result.get("state") == "starting" and time.time() - result.get("startedAt", 0) > 60
if ended or abandoned:
result = {"state": "uncertain", "reason": "The patch helper ended without a confirmed result; verify recovery before retrying"}
write(path, result)
journal = read(root / "operation.json")
journal["phase"] = "patch-uncertain"
write(root / "operation.json", journal)
print(json.dumps(result), flush=True)
return 0
def run_patch(folder, appid, installer, game):
root = control(folder)
try:
with lock_file(root) as stream:
fcntl.lockf(stream, fcntl.LOCK_EX)
path = validate_installer(folder, installer)
command, env, prefix = runner(folder, appid, game, True)
if active(prefix):
raise ValueError("Close the GOG game before applying the patch")
journal = read(root / "operation.json")
if journal.get("phase") != "patch-starting":
raise ValueError("The patch is already running or needs recovery")
journal["phase"] = "patch-applying"
write(root / "operation.json", journal)
sidecar_path = Path(folder) / ".droiddeck-store.json"
sidecar = read(sidecar_path)
sidecar["state"] = "updating"
write(sidecar_path, sidecar)
installed_path = root / "installed.json"
if installed_path.is_file():
installed = read(installed_path)
installed.update(verified=False, manifest={}, files=[])
write(installed_path, installed)
write(root / "patch-status.json", {"state": "running", "pid": os.getpid(), "generation": generation(os.getpid())})
os.makedirs(prefix, exist_ok=True)
setup = runpy.run_path(str(BIN / "droiddeck-store-launch"))["main"].__globals__
previous = dict(os.environ)
try:
os.environ.update(env)
pfx = Path(prefix) / "pfx"
if not (pfx / "system.reg").is_file() or not (pfx / "drive_c/windows/system32/reg.exe").is_file():
subprocess.run([command, "run", "wineboot.exe", "-u"], env=env, timeout=90, check=True)
if not (pfx / "drive_c/windows/system32/reg.exe").is_file():
raise ValueError("Proton did not initialize the game's registry tool")
result = setup["apply_gog_registry"](Path(folder), prefix, command, installation=journal.get("before"))
if not result.startswith(("ready", "written=")):
raise ValueError("GOG registry preparation failed; the patch was not applied")
prepare_setup(folder, command, env)
finally:
os.environ.clear(); os.environ.update(previous)
proc = subprocess.Popen([command, "run", str(path), *installer_arguments(path)], cwd=str(path.parent), env=env)
code = proc.wait()
quiet_at = time.monotonic()
while True:
if active(prefix):
quiet_at = time.monotonic()
elif time.monotonic() - quiet_at >= 2:
break
time.sleep(0.25)
journal["phase"] = "patch-uncertain"
write(root / "operation.json", journal)
if code:
raise ValueError("GOG patch installer exited with code %d; inspect patch.log" % code)
write(root / "patch-status.json", {"state": "done", "exitCode": code})
return 0
except Exception as error:
write(root / "patch-status.json", {"state": "failed", "reason": str(error)})
return 1
def prepare_setup(folder, command, env):
root = control(folder)
record_path = root / "installed.json"
if not record_path.is_file():
return
journal = read(root / "operation.json")
record = journal.get("before") or read(record_path)
manifest = record.get("manifest", {})
if not record.get("build"):
return
info_path = Path(folder) / ("goggame-%s.info" % record["id"])
language = read(info_path).get("language", "") if info_path.is_file() else ""
legacy = manifest.get("product", {})
products = manifest.get("products", []) if not legacy else [
{"productId": str(item["gameID"]), "temp_executable": item["executable"].lstrip("/\\")}
for item in legacy.get("support_commands", [])
if "Neutral" in item.get("languages", []) or record.get("language") in item.get("languages", []) or language in item.get("languages", [])]
for product in products:
if str(product.get("productId")) not in record.get("products", []):
continue
program = None
if manifest.get("scriptInterpreter"):
if not (Path(folder) / ("goggame-%s.script" % product["productId"])).is_file():
continue
program = Path(folder) / "support/__redist/ISI/scriptinterpreter.exe"
elif product.get("temp_executable"):
relative = product["temp_executable"].replace("\\", "/")
for candidate in (Path(folder) / "support" / str(product["productId"]) / relative, Path(folder) / relative):
if candidate.is_file():
program = candidate
break
if program is None:
continue
if not program.resolve(strict=True).is_relative_to(Path(folder).resolve()):
raise ValueError("GOG setup executable leaves the installation")
windows = "Z:" + str(Path(folder).resolve()).replace("/", "\\")
args = ["/VERYSILENT", "/DIR=" + windows, "/ProductId=" + str(product["productId"]),
"/galaxyclient", "/buildId=" + str(legacy.get("timestamp", record["build"])), "/versionName=" + record.get("version", ""),
"/lang-code=" + record.get("language", "en-US"), "/supportDir=" + windows + "\\support", "/nodesktopshortcut"]
if language:
args += ["/Language=" + language, "/LANG=" + language.lower()]
result = subprocess.run([command, "run", str(program), *args], env=env, cwd=folder, timeout=120)
if result.returncode:
raise ValueError("GOG installation setup failed; the patch was not applied")
def main(argv):
if len(argv) == 3 and argv[0] == "lease":
return lease(argv[1], int(argv[2]))
if len(argv) == 4 and argv[0] == "idle":
return idle(*argv[1:])
if len(argv) == 2 and argv[0] == "status":
return status(argv[1])
if len(argv) == 5 and argv[0] == "start":
return start(*argv[1:])
if len(argv) == 5 and argv[0] == "run":
return run_patch(*argv[1:])
raise ValueError("Invalid GOG maintenance command")
if __name__ == "__main__":
try:
sys.exit(main(sys.argv[1:]))
except Exception as error:
print("GOG maintenance: " + str(error), file=sys.stderr)
sys.exit(1)
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env python3
import json
import os
import select
import socket
import struct
import sys
import time
DISPLAY_ID = 1
REGISTRY_ID = 2
METHOD_ID = 3
SETTLE = 0.15
def wl_string(value):
data = value.encode() + b"\0"
return struct.pack("<I", len(data)) + data + b"\0" * (-len(data) % 4)
def read_string(payload, offset):
(length,) = struct.unpack_from("<I", payload, offset)
start = offset + 4
text = payload[start:start + length - 1].decode(errors="replace")
return text, start + length + (-length % 4)
class Connection:
def __init__(self, sock):
self.sock = sock
self.buffer = b""
def send(self, obj, opcode, payload=b""):
self.sock.sendall(struct.pack("<II", obj, ((8 + len(payload)) << 16) | opcode) + payload)
def messages(self, timeout):
ready, _, _ = select.select([self.sock], [], [], timeout)
if not ready:
return []
data, _, _, _ = self.sock.recvmsg(65536, socket.CMSG_SPACE(16 * 4))
if not data:
raise EOFError
self.buffer += data
out = []
while len(self.buffer) >= 8:
obj, word = struct.unpack_from("<II", self.buffer)
size = word >> 16
if size < 8 or len(self.buffer) < size:
break
out.append((obj, word & 0xFFFF, self.buffer[8:size]))
self.buffer = self.buffer[size:]
return out
class Report:
def __init__(self, directory):
self.directory = directory
self.seq = 0
self.sent = None
def write(self, field, hint=0, purpose=0):
state = (field, purpose)
if state == self.sent or not self.directory:
return
self.sent = state
self.seq += 1
os.makedirs(self.directory, exist_ok=True)
target = os.path.join(self.directory, "ime.json")
temp = target + ".tmp"
fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as handle:
json.dump({"textField": field, "hint": hint, "purpose": purpose, "seq": self.seq}, handle)
os.replace(temp, target)
print(f"droiddeck-ime: text field {'focused' if field else 'left'}", file=sys.stderr, flush=True)
def connect():
fd = os.environ.pop("WAYLAND_SOCKET", "")
if fd.isdigit():
return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, fileno=int(fd))
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(os.path.join(os.environ["XDG_RUNTIME_DIR"], os.environ.get("WAYLAND_DISPLAY", "wayland-0")))
return sock
def main():
launch = os.environ.get("BL_LAUNCH_DIR", "")
report = Report(os.path.join(launch, "agent") if launch else "")
conn = Connection(connect())
conn.send(DISPLAY_ID, 1, struct.pack("<I", REGISTRY_ID))
contexts = {}
current = None
pending = None
while True:
timeout = None if pending is None else max(0.0, pending - time.monotonic())
try:
batch = conn.messages(timeout)
except (EOFError, ConnectionError):
report.write(False)
return 0
for obj, opcode, payload in batch:
if obj == DISPLAY_ID and opcode == 0:
_, code = struct.unpack_from("<II", payload)
message, _ = read_string(payload, 8)
print(f"droiddeck-ime: protocol error {code}: {message}", file=sys.stderr, flush=True)
report.write(False)
return 1
if obj == REGISTRY_ID and opcode == 0:
(name,) = struct.unpack_from("<I", payload)
interface, offset = read_string(payload, 4)
(version,) = struct.unpack_from("<I", payload, offset)
if interface == "zwp_input_method_v1":
conn.send(REGISTRY_ID, 0, struct.pack("<I", name) + wl_string(interface)
+ struct.pack("<II", min(version, 1), METHOD_ID))
elif obj == METHOD_ID and opcode == 0:
(context,) = struct.unpack_from("<I", payload)
contexts[context] = [0, 0]
current = context
pending = None
report.write(True)
elif obj == METHOD_ID and opcode == 1:
(context,) = struct.unpack_from("<I", payload)
contexts.pop(context, None)
conn.send(context, 0)
if context == current:
current = None
pending = time.monotonic() + SETTLE
elif obj in contexts and opcode == 2:
hint, purpose = struct.unpack_from("<II", payload)
contexts[obj] = [hint, purpose]
if obj == current:
report.write(True, hint, purpose)
if pending is not None and time.monotonic() >= pending:
pending = None
if current is None:
report.write(False)
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,93 @@
#!/usr/bin/python3
import os
import re
import stat
import sys
HOME = os.environ.get("HOME", "/root")
STEAM = os.path.join(HOME, ".local/share/Steam")
STORES = os.environ.get("DROIDDECK_STORES_ROOT", "/mnt/droiddeck-stores")
TOOLS = re.compile(r"^(Proton |Proton$|SteamLinuxRuntime|Steamworks Shared$)")
def libraries():
paths = [STEAM]
try:
with open(os.path.join(STEAM, "steamapps/libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
paths += [p.replace("\\\\", "\\") for p in re.findall(r'"path"\s+"([^"]+)"', f.read())]
except OSError:
pass
seen = []
for path in paths:
real = os.path.realpath(path)
if real not in seen:
seen.append(real)
return seen
def roots():
found = []
for library in libraries():
for name in ("common", "compatdata"):
found.append((os.path.join(library, "steamapps", name), name == "common"))
found.append((os.path.join(HOME, "Games"), False))
try:
found += [(entry.path, False) for entry in os.scandir(STORES) if entry.is_dir(follow_symlinks=False)]
except OSError:
pass
return [(path, skip_tools) for path, skip_tools in found if os.path.isdir(path)]
def fix(path, st, wanted):
if st.st_uid != os.geteuid() or st.st_mode & wanted == wanted:
return 0
try:
os.chmod(path, stat.S_IMODE(st.st_mode) | wanted)
return 1
except OSError:
return 0
def walk(top, skip_tools):
fixed = 0
stack = [(top, True)]
while stack:
directory, first = stack.pop()
try:
entries = list(os.scandir(directory))
except OSError:
continue
for entry in entries:
if first and skip_tools and TOOLS.match(entry.name):
continue
try:
st = entry.stat(follow_symlinks=False)
except OSError:
continue
if stat.S_ISDIR(st.st_mode):
fixed += fix(entry.path, st, stat.S_IRWXU)
stack.append((entry.path, False))
elif stat.S_ISREG(st.st_mode):
fixed += fix(entry.path, st, stat.S_IRUSR | stat.S_IWUSR)
return fixed
def main():
try:
os.nice(19)
except OSError:
pass
total = 0
for top, skip_tools in roots():
try:
fixed = fix(top, os.stat(top), stat.S_IRWXU) + walk(top, skip_tools)
except OSError:
continue
if fixed:
print(f"droiddeck-library-perms: {top}: {fixed} made writable")
total += fixed
print(f"droiddeck-library-perms: {total} files and folders made writable")
if __name__ == "__main__":
sys.exit(main())
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/python3
import array
import json
import os
import signal
import socket
import struct
import sys
SOCKET_FILE = "/etc/droiddeck/root-socket"
def socket_name():
name = os.environ.get("DROIDDECK_ROOT_SOCKET", "")
if not name:
try:
with open(SOCKET_FILE, encoding="utf-8") as f:
name = f.read().strip()
except OSError:
pass
return "\0" + (name or "com.droiddeck.launcher.root")
def frame(sock, kind, payload):
sock.sendall(kind.encode() + struct.pack(">i", len(payload)) + payload)
def read_exact(sock, n):
data = b""
while len(data) < n:
chunk = sock.recv(n - len(data))
if not chunk:
return None
data += chunk
return data
def main(argv):
if len(argv) < 2 or argv[1] in ("-h", "--help"):
print("usage: droiddeck-root [--check] command [arg ...]", file=sys.stderr)
return 2
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(socket_name())
except OSError as e:
print(f"droiddeck-root: DroidDeck's root service is not reachable: {e}", file=sys.stderr)
return 126
if argv[1] == "--check":
return 0
env = dict(os.environ)
for name in ("LD_PRELOAD", "PROOT_FASTPATH", "DROIDDECK_ROOT_SOCKET"):
env.pop(name, None)
for name in [k for k in env if k.startswith("PROOT_")]:
env.pop(name, None)
try:
cwd = os.getcwd()
except OSError:
cwd = "/root"
body = json.dumps({"argv": argv[1:], "env": env, "cwd": cwd}).encode()
fds = array.array("i", [0, 1, 2])
sock.sendmsg([b"R" + struct.pack(">i", len(body))], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
sock.sendall(body)
def forward(signum, _frame):
try:
frame(sock, "S", str(signum).encode())
except OSError:
pass
for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2):
signal.signal(signum, forward)
signal.signal(signal.SIGTSTP, signal.SIG_IGN)
status = 1
while True:
try:
head = read_exact(sock, 5)
except InterruptedError:
continue
except OSError:
break
if head is None:
break
kind = chr(head[0])
payload = read_exact(sock, struct.unpack(">i", head[1:])[0]) or b""
if kind == "E":
print("droiddeck-root: " + payload.decode(errors="replace"), file=sys.stderr)
elif kind == "X":
status = int(payload.decode() or "1")
break
return status
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -14,22 +14,59 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
mv -f "$BL_LOG" "$BL_LOG.1"
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
dd=$(command -v gnudd || echo dd)
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:-?} 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
sync_timezone() {
local zone=${TZ:-}
case "$zone" in ''|/*|*..*) return 0 ;; esac
[ -f "/usr/share/zoneinfo/$zone" ] || return 0
if [ "$(readlink /etc/localtime 2>/dev/null)" != "/usr/share/zoneinfo/$zone" ]; then
ln -sfn "/usr/share/zoneinfo/$zone" /etc/localtime.droiddeck && mv -Tf /etc/localtime.droiddeck /etc/localtime || return 0
fi
[ "$(cat /etc/timezone 2>/dev/null)" = "$zone" ] || printf '%s\n' "$zone" > /etc/timezone
} 2>/dev/null
sync_timezone
write_system_bus_config() {
mkdir -p /run/dbus /usr/local/share/droiddeck
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>system</type>
<listen>unix:path=/run/dbus/system_bus_socket</listen>
<auth>EXTERNAL</auth>
<servicedir>/usr/share/droiddeck/system-services</servicedir>
<policy context="default">
<allow user="*"/>
<allow own="*"/>
<allow send_destination="*"/>
<allow receive_sender="*"/>
</policy>
</busconfig>
BUSCONF
rm -f /run/dbus/system_bus_socket
}
prepare_locale() {
local dir=/usr/lib/locale stamp=/usr/lib/locale/.droiddeck-archive want have= pkg
pkg=(/var/lib/pacman/local/glibc-[0-9]*)
want=${pkg[0]##*/}
if [ -d /var/lib/pacman/local ]; then
pkg=(/var/lib/pacman/local/glibc-[0-9]*)
want=${pkg[0]##*/}
else
want=libc6-$(dpkg-query -W -f='${Version}' libc6 2>/dev/null)
fi
[ -f "$stamp" ] && read -r have < "$stamp"
[ "$have" = "$want" ] && [ -f "$dir/locale-archive" ] && [ ! "$dir/locale-archive" -nt "$stamp" ] && return 0
[ -d "$dir/C.utf8" ] && command -v localedef >/dev/null 2>&1 || return 0
DROIDDECK_LINK_RENAME=1 localedef --add-to-archive --replace "$dir/C.utf8" >/dev/null 2>&1 || return 0
rm -f /usr/lib/gconv/gconv-modules.cache
rm -f /usr/lib/gconv/gconv-modules.cache /usr/lib/aarch64-linux-gnu/gconv/gconv-modules.cache
command -v iconvconfig >/dev/null 2>&1 && iconvconfig >/dev/null 2>&1
printf '%s\n' "$want" > "$stamp"
echo "== locale archive built for $want"
@@ -64,8 +101,33 @@ if [ -z "${BL_INSIDE:-}" ]; then
if [ "${BL_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.bl-zram; else rm -f /tmp/.bl-zram; fi
fi
steam_devtools() {
_bl_cdp=()
if [ -f "$steam_root/.cef-enable-remote-debugging" ]; then
if timeout 5 python3 -c 'import socket, sys
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", int(sys.argv[1])))' "$1" 2>/dev/null; then
BL_CDP_PORT=$1
return 0
fi
echo "== steam: port $1 is held by another app; Decky cannot load this session and Steam's devtools use another port"
fi
BL_CDP_PORT=$((20000 + RANDOM % 30000))
_bl_cdp=(-cef-enable-debugging -devtools-port "$BL_CDP_PORT")
}
steam_update_stuck() {
[ "$1" -lt 60 ] || steam_updates=0
local stamp
stamp=$(stat -c '%n %Y %s' "${steam_root:-}"/package/*.installed 2>/dev/null)
if [ "$1" -ge 60 ]; then
steam_updates=0
steam_installs=0
elif [ "$stamp" != "${steam_update_stamp-$stamp}" ] && [ "${steam_installs:-0}" -lt 5 ]; then
steam_updates=0
steam_installs=$((${steam_installs:-0} + 1))
fi
steam_update_stamp=$stamp
steam_updates=$((steam_updates + 1))
[ "$steam_updates" -ge 3 ]
}
@@ -210,6 +272,7 @@ rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-remote-play"
/usr/local/bin/droiddeck-steamvr unregister >/dev/null 2>&1 || true
if [ "$mode" = lxqt ] || [ "$mode" = desktop ]; then
/usr/local/bin/droiddeck-desktop-bookmarks || true
/usr/local/bin/droiddeck-downloads || true
fi
export FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap
export XDG_DATA_DIRS=$XDG_DATA_HOME/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}
@@ -277,6 +340,20 @@ if [ -z "${BL_INSIDE:-}" ]; then
step "starting the desktop"
start_agent --no-focus
[ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; }
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
write_system_bus_config
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
for _ in $(seq 1 50); do
[ -S /run/dbus/system_bus_socket ] && break
nap 0.1
done
if [ -S /run/dbus/system_bus_socket ]; then
droiddeck-login1 --with-netmanager &
echo "== desktop: system bus up, network and power services running"
else
echo "== desktop: the system bus did not come up"
fi
fi
cores=$(program_cores)
if [ -n "$cores" ]; then
echo "== desktop cores: $cores (the desktop and every program started from it)"
@@ -321,6 +398,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
fi
if [ "${BL_REFRESH:-0}" -gt 0 ]; then
args+=(-r "$BL_REFRESH")
# -r is the starting rate; gamescope follows the panel when it switches modes later.
export GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST=1
fi
[ "$mode" = steam ] && [ "${BL_STEAM_UI:-}" != desktop ] && args+=(-e)
if [ "$mode" = steam ] && [ "${BL_XWAYLAND_COUNT:-2}" -gt 1 ]; then
@@ -338,6 +417,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
args+=(--mangoapp)
echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)"
fi
# gamescope writes the frame times the app's HUD shows here (patch 0125).
mkdir -p /run/droiddeck-hud && export DROIDDECK_HUD_FRAMES=/run/droiddeck-hud/frames
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-*
@@ -540,7 +621,7 @@ 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_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam and the hidden Epic Games Launcher are not compressed while games run (turned off in Performance)"
_bl_ram_cap=0
case ${BL_RAM_CAP_MB:-} in
''|0) ;;
@@ -550,16 +631,16 @@ case $mode in
(
bl_zram_scan() {
_bl_game=0 _bl_pids=() _bl_others=() _bl_apps=
local _d _c _args _name _a _id
local _d _c _args _name _a _id _fex
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
[ "${#_args[@]}" -gt 0 ] || continue
_name=${_args[0]}
_name=${_args[0]} _fex=0
if [ "${#_args[@]}" -gt 1 ]; then
case ${_name##*/} in FEX|FEXInterpreter) _name=${_args[1]} ;; esac
case ${_name##*/} in FEX|FEXInterpreter) _name=${_args[1]} _fex=1 ;; esac
fi
case ${_name##*/} in
reaper)
@@ -574,7 +655,13 @@ case $mode in
done
;;
steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;;
*) _bl_others+=("${_d##*/}") ;;
*)
if [ "$_fex" = 1 ] && grep -qz '^DROIDDECK_EPIC_HIDDEN=1$' "$_d/environ" 2>/dev/null; then
_bl_pids+=("${_d##*/}")
else
_bl_others+=("${_d##*/}")
fi
;;
esac
done
}
@@ -921,23 +1008,7 @@ case $mode in
set -- "$@" "$_bl_url"
fi
if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then
mkdir -p /run/dbus /usr/local/share/droiddeck
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>system</type>
<listen>unix:path=/run/dbus/system_bus_socket</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow user="*"/>
<allow own="*"/>
<allow send_destination="*"/>
<allow receive_sender="*"/>
</policy>
</busconfig>
BUSCONF
rm -f /run/dbus/system_bus_socket
write_system_bus_config
dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork --nopidfile &
system_bus=$!
for _ in $(seq 1 50); do
@@ -1011,14 +1082,9 @@ BUSCONF
echo "== Decky: installed loader architecture is unsupported by this guest; not starting"
fi
fi
_bl_cdp=()
if [ -f "$steam_root/.cef-enable-remote-debugging" ]; then
export BL_CDP_PORT=8080
else
export BL_CDP_PORT=$((20000 + RANDOM % 30000))
_bl_cdp=(-cef-enable-debugging -devtools-port "$BL_CDP_PORT")
fi
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ]; then
steam_devtools 8080
export BL_CDP_PORT
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ] && [ ${#_bl_cdp[@]} = 0 ]; then
echo "== steam: devtools port $BL_CDP_PORT left open for the x86_64 Decky loader"
else
export BL_CDP_GUARD=$BL_CDP_PORT
@@ -1099,6 +1165,8 @@ BUSCONF
fi
echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*$([ "$steam_x64" = 1 ] && echo ' (x86-64 client under FEX)')"
steam_updates=0
steam_installs=0
steam_update_stamp=$(stat -c '%n %Y %s' "$steam_root"/package/*.installed 2>/dev/null)
rm -f "$HOME/.bl-stop-requested" "$STEAMOS_STEAM_SHUTDOWN_SENTINEL" "$STEAMOS_STEAM_REBOOT_SENTINEL"
steam_other_game_running() {
local line value n open
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
[ "${1:-}" = run ] || exec /usr/bin/snap "$@"
shift
while [ $# -gt 0 ]; do
case $1 in
--) shift; break ;;
-*) shift ;;
*) break ;;
esac
done
target=${1:?usage: snap run <snap>[.<app>] [args...]}
shift
name=${target%%.*}
app=${target#*.}
exec /usr/local/bin/droiddeck-snap-run "$name" "$app" "$@"
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
while [ $# -gt 0 ]; do
case $1 in
--classic) shift ;;
--base) shift 2 ;;
--*) shift ;;
*) break ;;
esac
done
tag=${1:?security tag}
shift
[ "${1##*/}" = snap-exec ] && shift
app=${1:-}
shift
name=${tag#snap.}
name=${name%%.*}
app=${app#*.}
[ -n "$app" ] || app=$name
exec /usr/local/bin/droiddeck-snap-run "$name" "$app" "$@"
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/python3
import os
import re
import shlex
import sys
import yaml
SNAP_DIR = "/snap"
HOST_DIRS = ("/etc", "/home", "/root", "/tmp", "/run", "/var/snap", "/var/lib/snapd", "/var/tmp", "/var/log",
"/media", "/mnt", "/snap", "/usr/src", "/lib/modules")
def load(name):
with open(f"{SNAP_DIR}/{name}/current/meta/snap.yaml") as f:
return yaml.safe_load(f) or {}
def expand(value, env):
return re.sub(r"\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?", lambda m: env.get(m.group(1), ""), str(value))
def provider_path(path, provider, revision):
snap = f"{SNAP_DIR}/{provider}/{revision}"
for var, value in (("$SNAP_DATA", f"/var/snap/{provider}/{revision}"),
("$SNAP_COMMON", f"/var/snap/{provider}/common"), ("$SNAP", snap)):
if path == var or path.startswith(var + "/"):
return os.path.normpath(value + path[len(var):])
return os.path.normpath(f"{snap}/{path}")
def content_binds(name, meta, env):
out = []
for plug_name, plug in (meta.get("plugs") or {}).items():
if not isinstance(plug, dict) or plug.get("interface") != "content" or not plug.get("target"):
continue
provider = (plug.get("default-provider") or "").split(":")[0]
if not provider or not os.path.isdir(f"{SNAP_DIR}/{provider}/current"):
continue
try:
slots = load(provider).get("slots") or {}
except OSError:
continue
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{provider}/current"))
target = expand(plug["target"], env)
for slot_name, slot in slots.items():
if not isinstance(slot, dict) or slot.get("interface") != "content":
continue
if slot.get("content", slot_name) != plug.get("content", plug_name):
continue
nested = "source" in slot
reads = (slot.get("source") or {}).get("read") if nested else slot.get("read")
for path in reads or []:
source = provider_path(str(path), provider, revision)
out.append((plug_name, source, os.path.join(target, os.path.basename(source)) if nested else target))
if not nested:
break
break
return out
def main(argv):
if len(argv) < 3:
print("usage: droiddeck-snap-run SNAP APP [ARG...]", file=sys.stderr)
return 2
name, app, args = argv[1], argv[2], argv[3:]
meta = load(name)
spec = (meta.get("apps") or {}).get(app)
if spec is None:
print(f"error: snap \"{name}\" has no app \"{app}\"", file=sys.stderr)
return 1
revision = os.path.basename(os.path.realpath(f"{SNAP_DIR}/{name}/current"))
home = os.environ.get("HOME", "/root")
snap = f"{SNAP_DIR}/{name}/{revision}"
env = dict(os.environ)
for k in ("LD_PRELOAD", "LD_LIBRARY_PATH"):
env.pop(k, None)
env.update({
"SNAP": snap, "SNAP_NAME": name, "SNAP_INSTANCE_NAME": name, "SNAP_INSTANCE_KEY": "",
"SNAP_REVISION": revision, "SNAP_VERSION": str(meta.get("version", "")), "SNAP_ARCH": "arm64",
"SNAP_LIBRARY_PATH": "/var/lib/snapd/lib/gl:/var/lib/snapd/lib/gl32:/var/lib/snapd/void",
"SNAP_DATA": f"/var/snap/{name}/{revision}", "SNAP_COMMON": f"/var/snap/{name}/common",
"SNAP_USER_DATA": f"{home}/snap/{name}/{revision}", "SNAP_USER_COMMON": f"{home}/snap/{name}/common",
"SNAP_REAL_HOME": home, "SNAP_UID": str(os.getuid()), "SNAP_EUID": str(os.geteuid()),
"SNAP_COOKIE": "", "SNAP_CONTEXT": "", "SNAP_REEXEC": "0",
})
for d in (env["SNAP_USER_DATA"], env["SNAP_USER_COMMON"], env["SNAP_DATA"], env["SNAP_COMMON"]):
os.makedirs(d, exist_ok=True)
current = f"{home}/snap/{name}/current"
if os.path.realpath(current) != env["SNAP_USER_DATA"]:
try:
os.unlink(current)
except OSError:
pass
os.symlink(revision, current)
confinement = meta.get("confinement", "strict")
if confinement != "classic":
env["HOME"] = env["SNAP_USER_DATA"]
env["PATH"] = ":".join([f"{snap}/usr/sbin", f"{snap}/usr/bin", f"{snap}/sbin", f"{snap}/bin",
"/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin", "/usr/games"])
env["LD_LIBRARY_PATH"] = env["SNAP_LIBRARY_PATH"]
for scope in (meta.get("environment") or {}, spec.get("environment") or {}):
for k, v in scope.items():
env[k] = expand(v, env)
command = shlex.split(expand(spec.get("command", ""), env))
if command and not command[0].startswith("/"):
command[0] = f"{snap}/{command[0]}"
chain = [c if c.startswith("/") else f"{snap}/{c}" for c in (meta.get("command-chain") or []) + (spec.get("command-chain") or [])]
program = chain + command + args
if confinement == "classic":
os.execvpe(program[0], program, env)
base = meta.get("base") or "core"
root = f"{SNAP_DIR}/{base}/current"
if not os.path.isdir(root):
print(f"error: the base snap \"{base}\" is not installed; run: snap install {base}", file=sys.stderr)
return 1
bwrap = ["/usr/local/bin/droiddeck-bwrap", "--bind", root, "/", "--dev-bind", "/dev", "/dev", "--proc", "/proc",
"--bind", "/sys", "/sys"]
for d in HOST_DIRS:
if os.path.isdir(d):
bwrap += ["--bind", d, d]
bwrap += ["--bind", "/", "/var/lib/snapd/hostfs"]
bwrap += ["--bind", "/dev/null", "/etc/ld.so.preload"]
binds = content_binds(name, meta, env)
for _, source, target in binds:
if os.path.isdir(source):
bwrap += ["--bind", source, target]
content = {k for k, v in (meta.get("plugs") or {}).items() if isinstance(v, dict) and v.get("interface") == "content"}
plugs = (set(meta.get("plugs") or {}) | set(spec.get("plugs") or [])) - content | {plug for plug, _, _ in binds}
env["DROIDDECK_SNAP_PLUGS"] = " ".join(sorted(plugs))
bwrap += ["--bind", "/usr/local/bin/droiddeck-snapctl", "/usr/lib/snapd/snapctl"]
bwrap += ["--chdir", os.getcwd() if os.path.isdir(os.getcwd()) else env["HOME"], "--clearenv"]
for k, v in env.items():
bwrap += ["--setenv", k, v]
os.execv(bwrap[0], bwrap + ["--"] + program)
if __name__ == "__main__":
sys.exit(main(sys.argv))
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
case $1 in
is-connected)
shift
while [ $# -gt 1 ]; do shift; done
case " $DROIDDECK_SNAP_PLUGS " in
*" ${1:-} "*) exit 0 ;;
esac
exit 1
;;
esac
exit 0
+542
View File
@@ -0,0 +1,542 @@
#!/usr/bin/python3
import datetime
import hashlib
import http.server
import json
import os
import re
import shutil
import socketserver
import subprocess
import sys
import threading
import urllib.parse
import urllib.request
STORE = "https://api.snapcraft.io/v2"
ARCH = "arm64"
SNAP_DIR = "/snap"
BIN_DIR = "/snap/bin"
LIB = "/var/lib/snapd"
STATE = LIB + "/droiddeck-state.json"
DESKTOP_DIR = LIB + "/desktop/applications"
SOCKETS = ("/run/snapd.socket", "/run/snapd-snap.socket")
FIND_FIELDS = ("title,summary,description,version,revision,confinement,base,publisher,license,contact,website,"
"media,categories,store-url,download,type,channel,common-ids,links")
INFO_FIELDS = ("title,summary,description,version,revision,confinement,base,publisher,license,contact,website,"
"media,categories,snap-id,store-url,download,type,channel-map,common-ids,links,created-at")
HEADERS = {"Snap-Device-Series": "16", "Snap-Device-Architecture": ARCH, "User-Agent": "snapd/2.70 droiddeck"}
lock = threading.RLock()
install_lock = threading.Lock()
changes = {}
change_seq = [0]
def now():
return datetime.datetime.now(datetime.timezone.utc).isoformat()
def load_state():
try:
with open(STATE) as f:
return json.load(f)
except (OSError, ValueError):
return {"snaps": {}}
def save_state(state):
tmp = STATE + ".tmp"
with open(tmp, "w") as f:
json.dump(state, f, indent=1)
os.replace(tmp, STATE)
def store_get(path, params=None):
url = STORE + path + ("?" + urllib.parse.urlencode(params) if params else "")
req = urllib.request.Request(url, headers=HEADERS)
with urllib.request.urlopen(req, timeout=60) as r:
return json.load(r)
def publisher(p):
p = p or {}
return {"id": p.get("id", ""), "username": p.get("username", ""), "display-name": p.get("display-name", ""),
"validation": p.get("validation", "unproven")}
def media_of(snap):
out = []
for m in snap.get("media") or []:
if m.get("type") in ("icon", "screenshot", "banner") and m.get("url"):
item = {"type": m["type"], "url": m["url"]}
if m.get("width"):
item["width"] = m["width"]
item["height"] = m.get("height", 0)
out.append(item)
return out
def icon_of(media):
return next((m["url"] for m in media if m["type"] == "icon"), "")
def from_store(name, snap, revision=None, channel=None):
media = media_of(snap)
rev = revision or snap.get("revision") or {}
out = {
"id": snap.get("snap-id", ""), "name": name, "title": snap.get("title") or name,
"summary": snap.get("summary", ""), "description": snap.get("description", ""),
"type": rev.get("type") or snap.get("type") or "app", "version": rev.get("version", ""),
"revision": str(rev.get("revision", "")), "channel": channel or "stable",
"confinement": rev.get("confinement") or "strict", "base": rev.get("base") or "",
"publisher": publisher(snap.get("publisher")), "developer": (snap.get("publisher") or {}).get("username", ""),
"license": snap.get("license", ""), "contact": snap.get("contact", ""), "website": snap.get("website", ""),
"media": media, "icon": icon_of(media), "store-url": snap.get("store-url", ""),
"download-size": (rev.get("download") or {}).get("size", 0), "status": "available",
"categories": [{"name": c.get("name", ""), "featured": bool(c.get("featured"))} for c in snap.get("categories") or []],
"common-ids": rev.get("common-ids") or snap.get("common-ids") or [],
"private": False, "devmode": False, "jailmode": False, "trymode": False, "apps": [],
}
return out
def installed_snap(name, entry):
snap = dict(entry["info"])
snap["status"] = "active"
snap["install-date"] = entry.get("installed", now())
snap["installed-size"] = entry.get("size", 0)
snap["revision"] = str(entry["revision"])
snap["version"] = entry.get("version", snap.get("version", ""))
snap["tracking-channel"] = entry.get("channel", "latest/stable")
snap["channel"] = entry.get("channel", "latest/stable")
snap["mounted-from"] = f"{LIB}/snaps/{name}_{entry['revision']}.snap"
snap["apps"] = [{"name": a, "snap": name, "desktop-file": f"{DESKTOP_DIR}/{name}_{a}.desktop"} for a in entry.get("apps", [])]
return snap
def find(query, section=None, name_exact=False):
if name_exact:
try:
info = store_get(f"/snaps/info/{query}", {"architecture": ARCH, "fields": INFO_FIELDS})
except Exception:
return []
rev = next((c for c in info.get("channel-map", []) if c["channel"]["architecture"] == ARCH
and c["channel"]["risk"] == "stable"), None)
if not rev:
return []
return [from_store(info["name"], dict(info["snap"], **{"snap-id": info.get("snap-id", "")}), rev, "stable")]
params = {"architecture": ARCH, "fields": FIND_FIELDS}
if query:
params["q"] = query
if section:
params["category"] = section
if not query and not section:
params["featured"] = "true"
result = store_get("/snaps/find", params)
out = []
state = load_state()
for r in result.get("results", []):
snap = from_store(r["name"], dict(r.get("snap", {}), **{"snap-id": r.get("snap-id", "")}), r.get("revision"))
if r["name"] in state["snaps"]:
snap["status"] = "active"
snap["installed-size"] = state["snaps"][r["name"]].get("size", 0)
out.append(snap)
return out
def new_change(kind, summary, snaps):
with lock:
change_seq[0] += 1
cid = str(change_seq[0])
changes[cid] = {"id": cid, "kind": kind, "summary": summary, "status": "Doing", "ready": False,
"spawn-time": now(), "tasks": [{"id": cid + "-1", "kind": kind, "summary": summary, "status": "Doing",
"progress": {"label": "", "done": 0, "total": 1},
"spawn-time": now()}],
"data": {"snap-names": snaps}}
return cid
def progress(cid, label, done, total):
with lock:
task = changes[cid]["tasks"][0]
task["progress"] = {"label": label, "done": done, "total": max(total, 1)}
task["summary"] = changes[cid]["summary"]
def finish(cid, err=None):
with lock:
c = changes[cid]
c["status"] = "Error" if err else "Done"
c["ready"] = True
c["ready-time"] = now()
c["tasks"][0]["status"] = c["status"]
if err:
c["err"] = err
def root_run(argv):
if os.getuid() == 0:
return subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
return subprocess.run(["/usr/local/bin/droiddeck-root"] + argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True)
def snap_yaml(path):
try:
import yaml
with open(path) as f:
return yaml.safe_load(f) or {}
except Exception:
return {}
def download(cid, name, url, sha3, size, target):
tmp = target + ".partial"
h = hashlib.sha3_384()
req = urllib.request.Request(url, headers=HEADERS)
with urllib.request.urlopen(req, timeout=120) as r, open(tmp, "wb") as out:
done = 0
while True:
chunk = r.read(1 << 20)
if not chunk:
break
out.write(chunk)
h.update(chunk)
done += len(chunk)
progress(cid, f"Download snap \"{name}\"", done, size)
if sha3 and h.hexdigest() != sha3:
os.unlink(tmp)
raise RuntimeError(f"{name}: downloaded snap does not match the store's sha3-384")
os.replace(tmp, target)
def write_desktop(name, rev, meta):
os.makedirs(DESKTOP_DIR, exist_ok=True)
gui = f"{SNAP_DIR}/{name}/{rev}/meta/gui"
apps = (meta.get("apps") or {})
for app, spec in apps.items():
source = os.path.join(gui, f"{app}.desktop")
if (spec or {}).get("daemon") or not os.path.isfile(source):
continue
command = name if app == name else f"{name}.{app}"
out = []
with open(source, encoding="utf-8", errors="replace") as f:
for line in f:
if line.startswith("Exec="):
args = line[5:].strip().split(" ", 1)
rest = (" " + args[1]) if len(args) > 1 else ""
line = f"Exec={BIN_DIR}/{command}{rest}\n"
elif line.startswith("Icon="):
line = "Icon=" + line[5:].replace("${SNAP}", f"{SNAP_DIR}/{name}/current")
out.append(line)
out.append(f"X-SnapInstanceName={name}\n")
target = f"{DESKTOP_DIR}/{name}_{app}.desktop"
with open(target + ".tmp", "w", encoding="utf-8") as f:
f.writelines(out)
os.replace(target + ".tmp", target)
subprocess.run(["update-desktop-database", DESKTOP_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def link_bins(name, meta):
os.makedirs(BIN_DIR, exist_ok=True)
apps = []
for app, spec in (meta.get("apps") or {}).items():
if (spec or {}).get("daemon"):
continue
command = name if app == name else f"{name}.{app}"
path = os.path.join(BIN_DIR, command)
with open(path + ".tmp", "w") as f:
f.write(f"#!/bin/sh\nexec /usr/local/bin/droiddeck-snap-run {name} {app} \"$@\"\n")
os.chmod(path + ".tmp", 0o755)
os.replace(path + ".tmp", path)
apps.append(app)
return apps
def remove_tree(top):
if os.path.isdir(top) and not os.path.islink(top):
os.chmod(top, 0o700)
for root, dirs, _ in os.walk(top):
for d in dirs:
path = os.path.join(root, d)
if not os.path.islink(path):
os.chmod(path, 0o700)
shutil.rmtree(top, ignore_errors=True)
def install_one(cid, name, channel, state, parents=()):
if name in state["snaps"] or name in parents:
return
info = store_get(f"/snaps/info/{name}", {"architecture": ARCH, "fields": INFO_FIELDS})
risk = channel.split("/")[-1] if channel else "stable"
track = channel.split("/")[0] if channel and "/" in channel else "latest"
rev = next((c for c in info.get("channel-map", []) if c["channel"]["architecture"] == ARCH
and c["channel"]["risk"] == risk and c["channel"]["track"] == track), None)
if not rev:
raise RuntimeError(f"snap \"{name}\" has no {track}/{risk} release for {ARCH}")
number = rev["revision"]
os.makedirs(f"{LIB}/snaps", exist_ok=True)
blob = f"{LIB}/snaps/{name}_{number}.snap"
d = rev.get("download") or {}
with lock:
changes[cid]["summary"] = f"Install \"{name}\" snap"
download(cid, name, d["url"], d.get("sha3-384"), d.get("size", 0), blob)
progress(cid, f"Unpack snap \"{name}\"", 0, 1)
target = f"{SNAP_DIR}/{name}/{number}"
remove_tree(target)
os.makedirs(os.path.dirname(target), exist_ok=True)
r = root_run(["unsquashfs", "-q", "-n", "-no-xattrs", "-f", "-excludes", "-d", target, blob, "dev"])
if r.returncode != 0:
raise RuntimeError(f"cannot unpack {name}: {r.stdout.strip()[-400:]}")
os.makedirs(f"{target}/dev", exist_ok=True)
current = f"{SNAP_DIR}/{name}/current"
if os.path.islink(current):
os.unlink(current)
os.symlink(str(number), current)
for sub in (f"/var/snap/{name}/{number}", f"/var/snap/{name}/common"):
os.makedirs(sub, exist_ok=True)
cur = f"/var/snap/{name}/current"
if os.path.islink(cur):
os.unlink(cur)
os.symlink(str(number), cur)
meta = snap_yaml(f"{target}/meta/snap.yaml")
entry = {"revision": number, "version": rev.get("version", ""), "channel": f"{track}/{risk}",
"installed": now(), "size": d.get("size", 0), "info": from_store(name, dict(info["snap"], **{"snap-id": info.get("snap-id", "")}), rev, f"{track}/{risk}"),
"base": meta.get("base") or ("core" if (meta.get("type") or "app") == "app" else ""), "apps": []}
base = meta.get("base")
if (meta.get("type") or "app") == "app":
install_one(cid, base or "core", "latest/stable", state, parents + (name,))
for plug in (meta.get("plugs") or {}).values():
if isinstance(plug, dict) and plug.get("interface") == "content" and plug.get("default-provider"):
provider = plug["default-provider"].split(":")[0]
install_one(cid, provider, "latest/stable", state, parents + (name,))
entry["apps"] = link_bins(name, meta)
write_desktop(name, number, meta)
state["snaps"][name] = entry
save_state(state)
def remove_one(name, state):
entry = state["snaps"].pop(name, None)
if not entry:
raise RuntimeError(f"snap \"{name}\" is not installed")
for app in entry.get("apps", []):
command = name if app == name else f"{name}.{app}"
try:
os.unlink(os.path.join(BIN_DIR, command))
except OSError:
pass
if os.path.isdir(DESKTOP_DIR):
for f in os.listdir(DESKTOP_DIR):
if f.startswith(name + "_") and f.endswith(".desktop"):
os.unlink(os.path.join(DESKTOP_DIR, f))
subprocess.run(["update-desktop-database", DESKTOP_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
remove_tree(f"{SNAP_DIR}/{name}")
for f in os.listdir(f"{LIB}/snaps"):
if f.startswith(name + "_"):
os.unlink(os.path.join(f"{LIB}/snaps", f))
save_state(state)
def run_change(cid, action, names, channel):
with install_lock:
apply_change(cid, action, names, channel)
def apply_change(cid, action, names, channel):
try:
state = load_state()
for name in names:
if action == "install":
install_one(cid, name, channel or "latest/stable", state)
elif action == "remove":
remove_one(name, state)
elif action == "refresh":
old = state["snaps"].get(name)
if old:
remove_one(name, state)
install_one(cid, name, old.get("channel", "latest/stable"), state)
else:
raise RuntimeError(f"unsupported action {action}")
finish(cid)
except Exception as e:
finish(cid, str(e))
SECTIONS = ["featured", "art-and-design", "books-and-reference", "development", "devices-and-iot", "education",
"entertainment", "finance", "games", "health-and-fitness", "music-and-audio", "news-and-weather",
"personalisation", "photo-and-video", "productivity", "science", "security", "server-and-cloud",
"social", "utilities"]
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *args):
pass
def address_string(self):
return "snapd"
def reply(self, body, code=200, kind="sync"):
payload = {"type": kind, "status-code": code, "status": http.client.responses.get(code, "")}
payload.update(body)
data = json.dumps(payload).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def ok(self, result):
self.reply({"result": result})
def error(self, code, message, kind=""):
self.reply({"result": {"message": message, "kind": kind}}, code, "error")
def body(self):
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b"{}"
try:
return json.loads(raw or b"{}")
except ValueError:
return {}
def do_GET(self):
url = urllib.parse.urlsplit(self.path)
q = urllib.parse.parse_qs(url.query)
path = url.path
try:
if path == "/v2/system-info":
return self.ok({"series": "16", "version": "2.70+droiddeck", "build-id": "droiddeck", "os-release": {"id": "ubuntu", "version-id": "26.04"},
"on-classic": True, "managed": False, "kernel-version": os.uname().release,
"locations": {"snap-mount-dir": SNAP_DIR, "snap-bin-dir": BIN_DIR},
"refresh": {"timer": "00:00~24:00/4"}, "confinement": "partial",
"sandbox-features": {}, "architecture": ARCH})
if path == "/v2/snaps":
state = load_state()
wanted = (q.get("snaps", [""])[0] or "").split(",")
snaps = [installed_snap(n, e) for n, e in state["snaps"].items() if not wanted[0] or n in wanted]
return self.ok(snaps)
m = re.fullmatch(r"/v2/snaps/([^/]+)", path)
if m:
state = load_state()
if m.group(1) in state["snaps"]:
return self.ok(installed_snap(m.group(1), state["snaps"][m.group(1)]))
return self.error(404, f"snap not installed", "snap-not-found")
if path == "/v2/find":
name = q.get("name", [None])[0]
query = name or q.get("q", [""])[0]
section = q.get("section", [None])[0] or q.get("category", [None])[0]
if section == "featured":
section = None
select = q.get("select", [""])[0]
if select == "refresh":
return self.ok([])
if select == "private":
return self.ok([])
return self.ok(find(query, section, bool(name)))
if path in ("/v2/sections",):
return self.ok(SECTIONS)
if path == "/v2/categories":
return self.ok([{"name": s} for s in SECTIONS if s != "featured"])
m = re.fullmatch(r"/v2/changes/([^/]+)", path)
if m:
with lock:
c = changes.get(m.group(1))
c = json.loads(json.dumps(c)) if c else None
return self.ok(c) if c else self.error(404, "cannot find change", "")
if path == "/v2/changes":
with lock:
return self.ok([json.loads(json.dumps(c)) for c in changes.values()])
m = re.fullmatch(r"/v2/icons/([^/]+)/icon", path)
if m:
return self.icon(m.group(1))
if path == "/v2/apps":
state = load_state()
apps = [{"snap": n, "name": a, "desktop-file": f"{DESKTOP_DIR}/{n}_{a}.desktop"}
for n, e in state["snaps"].items() for a in e.get("apps", [])]
return self.ok(apps)
if path in ("/v2/connections", "/v2/interfaces"):
return self.ok({"established": [], "plugs": [], "slots": []})
if path in ("/v2/aliases", "/v2/users", "/v2/notices", "/v2/assertions/model"):
return self.ok({} if path == "/v2/aliases" else [])
return self.error(404, f"not found: {path}")
except Exception as e:
return self.error(500, str(e))
def icon(self, name):
state = load_state()
entry = state["snaps"].get(name)
if not entry:
return self.error(404, "not installed", "snap-not-found")
for candidate in ("meta/gui/icon.png", "meta/gui/icon.svg"):
path = f"{SNAP_DIR}/{name}/current/{candidate}"
if os.path.isfile(path):
with open(path, "rb") as f:
data = f.read()
self.send_response(200)
self.send_header("Content-Type", "image/svg+xml" if path.endswith("svg") else "image/png")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
return
return self.error(404, "no icon", "")
def do_POST(self):
path = urllib.parse.urlsplit(self.path).path
body = self.body()
m = re.fullmatch(r"/v2/snaps/([^/]+)", path)
if m or path == "/v2/snaps":
names = [m.group(1)] if m else body.get("snaps") or []
action = body.get("action", "")
channel = body.get("channel") or ""
if channel and "/" not in channel:
channel = "latest/" + channel
if action not in ("install", "remove", "refresh"):
return self.error(400, f"unsupported action \"{action}\"")
cid = new_change(f"{action}-snap", f"{action.capitalize()} {', '.join(names)}", names)
threading.Thread(target=run_change, args=(cid, action, names, channel), daemon=True).start()
return self.reply({"change": cid}, 202, "async")
m = re.fullmatch(r"/v2/changes/([^/]+)", path)
if m:
return self.error(400, "changes cannot be aborted")
if path in ("/v2/login", "/v2/logout", "/v2/snapctl"):
return self.error(400, "not supported by DroidDeck's snap service")
return self.error(404, f"not found: {path}")
def do_PUT(self):
return self.do_POST()
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
daemon_threads = True
def get_request(self):
conn, _ = self.socket.accept()
return conn, ("snapd", 0)
def serve(path):
try:
os.unlink(path)
except OSError:
pass
server = Server(path, Handler)
os.chmod(path, 0o666)
server.serve_forever()
def main():
for d in (LIB, SNAP_DIR, BIN_DIR, DESKTOP_DIR, LIB + "/snaps"):
os.makedirs(d, exist_ok=True)
threads = [threading.Thread(target=serve, args=(p,), daemon=True) for p in SOCKETS]
for t in threads:
t.start()
for t in threads:
t.join()
if __name__ == "__main__":
sys.exit(main())
@@ -23,15 +23,20 @@ BRIGHTNESS_JS = r"""
if (window.__droiddeckBrightness) return "present";
const display = SteamClient.System?.Display;
if (!display?.RegisterForBrightnessChanges || !display?.SetBrightness) return "unavailable";
const self = { expected: null, updating: true, revision: 0 };
const self = { expected: null, updating: true, revision: 0, localAt: -Infinity };
// A held stick steps Steam faster than Android's readback returns; those stale readbacks would snap the slider back.
const HOLD_MS = 750;
// Returns "held" while a readback is being ignored, so the caller retries it after the hold.
self.set = value => {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return;
if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return;
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) return true;
if (performance.now() - self.localAt < HOLD_MS) return "held";
if (!self.updating && self.expected !== null && Math.abs(value - self.expected) < 0.0001) return true;
self.expected = value;
self.updating = true;
const revision = ++self.revision;
setTimeout(() => { if (self.revision === revision) self.updating = false; }, 500);
display.SetBrightness(value);
return true;
};
self.subscription = display.RegisterForBrightnessChanges(state => {
const value = state?.flBrightness;
@@ -39,6 +44,7 @@ BRIGHTNESS_JS = r"""
if (Math.abs(value - self.expected) < 0.0001) { self.updating = false; return; }
if (self.updating) { self.updating = false; return; }
self.expected = value;
self.localAt = performance.now();
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(value));
});
window.__droiddeckBrightness = self;
@@ -241,6 +247,74 @@ TOUR_JS = r"""
return "off";
})()
"""
# Steam keeps the Quick Access Frame Limit as the client setting gamescope_app_target_framerate
# (CMsgClientSettings field 21002) and offers the values gamescope's display state lists in
# active_display_info.supported_frame_rates. When the panel's refresh rate changes, a remembered
# limit that is not one of the new values leaves the slider on its first value while the game runs
# at the old limit. The limit is kept when it is still offered and moved to the highest value
# otherwise. Choices are read once they have been unchanged for a moment, since a mode switch can
# report a passing rate first.
FRAME_LIMIT_JS = r"""
(() => {
if (window.__droiddeckFrameLimit) return "present";
const settings = window.settingsStore;
let service = null;
try {
// Steam's webpack does not expose its module cache; the gamescope service client is found by
// the calls its module makes and loaded by id.
let require;
window.webpackChunksteamui.push([[Symbol("droiddeck-frame-limit")], {}, r => { require = r; }]);
for (const id of Object.keys(require.m || {})) {
const source = String(require.m[id]);
if (!source.includes("SetBlurParams") || !source.includes("RegisterForNotifyStateChanged")) continue;
let exports;
try { exports = require(id); } catch (e) { continue; }
if (!exports || typeof exports !== "object") continue;
service = Object.values(exports).find(value => value && typeof value.GetState === "function" &&
typeof value.RegisterForNotifyStateChanged === "function" && typeof value.SetBlurParams === "function");
if (service) break;
}
} catch (e) {
service = null;
}
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)));
};
self.check = async () => {
let rates;
try {
const reply = await service.GetState({});
if (!reply.BSuccess()) return;
rates = reply.Body().toObject().state?.active_display_info?.supported_frame_rates;
} catch (e) {
return;
}
if (!Array.isArray(rates) || rates.length === 0) return;
const current = settings.clientSettings;
if (!current.gamescope_enable_app_target_framerate || rates.includes(current.gamescope_app_target_framerate)) return;
try {
await write(Math.max(...rates));
} catch (e) {
}
};
self.schedule = () => {
clearTimeout(self.timer);
self.timer = setTimeout(self.check, 1500);
};
self.subscription = service.RegisterForNotifyStateChanged(self.schedule);
self.interval = setInterval(self.schedule, 5000);
self.schedule();
window.__droiddeckFrameLimit = self;
return "installed";
})()
"""
FILE_BINDING = "droiddeckOpenFileDialog"
FILE_JS = r"""
(() => {
@@ -680,6 +754,8 @@ class Helper:
self.chooser = None
self.controls_state = None
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
def sync_controls(self):
try:
@@ -694,14 +770,28 @@ class Helper:
if not self.controls_installed:
return
if state != self.controls_state:
if self.page.evaluate("!!window.__droiddeckBrightness && (window.__droiddeckBrightness.set(%s), true)" % json.dumps(value)) is True:
applied = self.page.evaluate("window.__droiddeckBrightness ? window.__droiddeckBrightness.set(%s) : false" % json.dumps(value))
if applied is True:
self.controls_state = state
else:
elif applied != "held":
self.controls_installed = False
self.controls_state = None
except (OSError, ValueError, TypeError):
pass
def sync_frame_limit(self):
# Steam can still be loading its settings and gamescope state when the helper attaches.
if self.frame_limit_state in ("installed", "present") or time.monotonic() < self.frame_limit_retry:
return
try:
state = self.page.evaluate(FRAME_LIMIT_JS)
except RuntimeError as e:
state = "failed (%s)" % e
if state != self.frame_limit_state:
say("frame limit sync: %s" % state)
self.frame_limit_state = state
self.frame_limit_retry = time.monotonic() + 10
def open_chooser(self, payload):
try:
request = json.loads(payload)
@@ -801,6 +891,8 @@ class Helper:
self.page = page
self.controls_state = None
self.controls_installed = False
self.frame_limit_state = None
self.frame_limit_retry = 0
self.sync_controls()
return True
@@ -956,6 +1048,7 @@ class Helper:
self.ensure_tools()
while True:
self.sync_controls()
self.sync_frame_limit()
sources = [self.page.ws] + ([watcher] if watcher.fileno() >= 0 else [])
if self.chooser is not None:
sources.append(self.chooser[1].stdout)
@@ -14,6 +14,7 @@ import urllib.parse
import urllib.request
STATE = ".droiddeck-games.json"
TRIED = ".droiddeck-import-tried.json"
WINNATIVE = ".winnative-steam/steamapps"
LIBRARY = "/mnt/droiddeck-sd"
LEGACY_LIBRARY = "/mnt/bannerlator-sd"
@@ -179,10 +180,44 @@ def request_restart(steam_root):
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
def ask_restart(names, timeout=600, clock=None, sleep=None):
"""The app asks whether to restart the client now; anything but "now" leaves the import to the next start."""
clock, sleep = clock or time.monotonic, sleep or time.sleep
folder = Path(os.environ.get("HOME", "/root"), ".cache/droiddeck")
ask, answer = folder / "steam-import.json", folder / "steam-import.answer"
token = str(time.time_ns())
answer.unlink(missing_ok=True)
save_json(ask, {"token": token, "games": names})
try:
deadline = clock() + timeout
while clock() < deadline:
reply = read_json(answer, None)
if isinstance(reply, dict) and reply.get("token") == token:
return reply.get("choice") == "now"
sleep(1)
return False
finally:
ask.unlink(missing_ok=True)
answer.unlink(missing_ok=True)
def unimported(steam_root, snapshot, candidates):
routes = read_json(Path(steam_root) / "userdata" / snapshot["account"] / "config/.droiddeck-routes.json", {})
config = Path(steam_root) / "userdata" / snapshot["account"] / "config"
routes = read_json(config / ".droiddeck-routes.json", {})
routed = set(routes.values()) if isinstance(routes, dict) else set()
return sorted({appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True} - routed)
tried = read_json(config / TRIED, [])
tried = {appid for appid in tried if isinstance(appid, int)} if isinstance(tried, list) else set()
owned = {appid for appid in candidates.values() if snapshot["owned"].get(str(appid)) is True}
if tried - routed != tried:
save_json(config / TRIED, sorted(tried - routed))
return sorted(owned - routed - tried)
def remember_tried(steam_root, account, appids):
config = Path(steam_root) / "userdata" / account / "config"
tried = read_json(config / TRIED, [])
tried = {appid for appid in tried if isinstance(appid, int)} if isinstance(tried, list) else set()
save_json(config / TRIED, sorted(tried | set(appids)))
def watch(steam_root, listing):
@@ -193,7 +228,7 @@ def watch(steam_root, listing):
next_lookup = 0
last_status = None
probed, next_probe, failures = None, 0, 0
pending, requested = [], []
pending, requested, account = [], [], None
while True:
now = time.monotonic()
for game in games:
@@ -233,6 +268,7 @@ def watch(steam_root, listing):
snapshot["sources"] = sources
save_json(Path(steam_root) / "userdata" / snapshot["account"] / "config" / STATE, snapshot)
pending = unimported(steam_root, snapshot, candidates)
account = snapshot["account"]
status = "matched %d/%d games; %d owned" % (len(candidates), len(games), sum(snapshot["owned"].values()))
except (OSError, ValueError, KeyError, StopIteration, subprocess.TimeoutExpired) as error:
status = "ownership check unavailable: " + str(error)
@@ -242,9 +278,14 @@ def watch(steam_root, listing):
status = last_status
if pending and pending != requested and not game_running() and downloads_idle(steam_root):
requested = pending
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
names = sorted({game["name"] for game in games if candidates.get(game["folder"]) in pending})
try:
request_restart(steam_root)
remember_tried(steam_root, account, pending)
if ask_restart(names) and not game_running() and downloads_idle(steam_root):
print("droiddeck-steam-games: restarting the client once to import %s" % pending, flush=True)
request_restart(steam_root)
else:
print("droiddeck-steam-games: %s will be imported the next time the client starts" % pending, flush=True)
except (OSError, subprocess.TimeoutExpired) as error:
print("droiddeck-steam-games: restart unavailable: %s" % error, flush=True)
if status != last_status:
@@ -436,6 +477,7 @@ def route(steam_root, acct, games):
if seed_install(steam_root, game, appid):
routes[str(game["appid"])] = appid
continue
print(f"droiddeck-steam-games: {game.get('name', appid)} stays a shortcut this session: it could not be linked as Steam app {appid}")
except OSError as error:
print(f"droiddeck-steam-games: import unavailable ({error})")
elif isinstance(appid, int) and 0 < appid < 0x80000000 and seeded(steamapps, game, appid):
@@ -39,6 +39,7 @@ if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then
echo "droiddeck-steam-launch: the desktop client did not become ready" >&2
exit 69
fi
[ "$url" = steam://exit ] && exit 0
export BL_INSIDE=1 BL_STEAM_UI=desktop
exec /usr/local/bin/droiddeck-session steam "${url:-steam://open/library}"
fi
@@ -6,6 +6,7 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then
for arg in "$@"; do
case $arg in
steam://*) url=$arg ;;
-shutdown) url=steam://exit ;;
-gamepadui|-bigpicture) ui=bigpicture ;;
esac
done
@@ -799,13 +799,25 @@ x64_gpu_watch() {
x64_gpu_probe
}
x64_arm_webhelper_cpu_supported() {
local status=0
# Valve's native ARM web helper contains LSE atomics; missing CPU data cannot establish incompatibility.
awk -F: '
$1 ~ /^[[:space:]]*Features[[:space:]]*$/ {
if ($2 !~ /(^|[[:space:]])atomics([[:space:]]|$)/) unsupported = 1
}
END { exit unsupported ? 1 : 0 }
' /proc/cpuinfo 2>/dev/null || status=$?
[ "$status" != 1 ]
}
x64_exec() {
x64_env
cd "$STEAM_X64"
# The client checksums its files at start and reinstalls over edited ones, so the session shim (preload/net.c)
# swaps the web helper at exec. The arm64 helper only comes up against a client of the same build.
if [ "${BL_X64_X86_WEBHELPER:-0}" != 1 ] && [ -x /usr/local/bin/droiddeck-x64-arm-webhelper ] &&
[ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ]; then
[ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ] && x64_arm_webhelper_cpu_supported; then
local chan x86_build arm_build
chan=$(cat "$STEAM_X64/package/beta" 2>/dev/null || echo "$X64_CHANNEL")
x86_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$STEAM_X64/package/steam_client_${chan}_steamrt64.manifest" 2>/dev/null || true)
@@ -1049,4 +1061,4 @@ for attempt in 1 2 3 4 5; do
( x64_exec -clientbeta "$X64_CHANNEL" -no-cef-sandbox "${cef[@]}" "$@" ) >>"$LOG" 2>&1 || rc=$?
step "client exited rc=$rc"
[ "$rc" = 42 ] || break
done
done
@@ -40,6 +40,7 @@ import time
import subprocess
import tempfile
import hashlib
import threading
from pathlib import Path
LAUNCHER = ".droiddeck-launch.bat"
@@ -494,8 +495,27 @@ def gog_registry(folder):
return entries, skipped
def apply_gog_registry(folder, compat_data, proton, timeout=90):
def apply_gog_registry(folder, compat_data, proton, timeout=90, installation=None):
entries, skipped = gog_registry(folder)
if installation:
product = str(installation["id"])
if not product.isdigit():
raise ValueError("Invalid GOG product identifier")
values = {"PATH": windows_path(str(folder))}
identity = Path(folder) / ("goggame-%s.id" % product)
if identity.is_file():
actual = json.loads(identity.read_text(encoding="utf-8-sig")).get("buildId")
if actual and installation.get("build") and str(actual) != str(installation["build"]):
raise ValueError("GOG build metadata changed before patch setup")
if installation.get("build"):
values["BUILDID"] = installation["build"]
if installation.get("version"):
values["VER"] = installation["version"]
for key, value in values.items():
entry = gog_entry({"root": "HKLM", "subkey": "Software\\GOG.com\\Games\\" + product,
"valueName": key, "valueData": value, "valueType": "string"}, {})
if entry:
entries.append(entry)
note = " skipped=%d" % skipped if skipped else ""
if not entries:
return "none" + note
@@ -512,7 +532,8 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90):
with tempfile.TemporaryDirectory(prefix="droiddeck-gog-") as tmp:
source = Path(tmp) / "registry.reg"
source.write_bytes(b"\xff\xfe" + text.encode("utf-16-le"))
run = subprocess.run([proton, "run", "reg.exe", "import", windows_path(str(source)), "/reg:32"],
executable = pfx / "drive_c/windows/system32/reg.exe"
run = subprocess.run([proton, "run", str(executable) if executable.is_file() else "reg.exe", "import", windows_path(str(source)), "/reg:32"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
if run.returncode or not (pfx / "system.reg").is_file():
return "import-failed" + note
@@ -525,6 +546,8 @@ def apply_gog_registry(folder, compat_data, proton, timeout=90):
def main(argv):
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
return 0
if argv and argv[0] == "--exited":
rest, code = argv[1:], 0
if rest[:1] == ["--code"] and len(rest) > 1:
@@ -543,6 +566,18 @@ def main(argv):
return 0
folder, sidecar = found
store, game = str(sidecar.get("store")), str(sidecar.get("id"))
if store == "gog":
helper = Path(__file__).resolve().with_name("droiddeck-gog-maintenance")
if helper.is_file():
child = subprocess.Popen([sys.executable, str(helper), "lease", str(folder), str(os.getppid())],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
start_new_session=True)
ready = child.stdout.readline().decode().strip()
child.stdout.close()
threading.Thread(target=child.wait, daemon=True).start()
if ready != "ready":
log("gog: close or recover the maintenance operation before playing")
return RAN_FAILED
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("BL_LAUNCH_DIR", "")
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/python3
import os
import sys
REAL = "/usr/bin/systemd-run"
VALUED = {"-u", "--unit", "-p", "--property", "--description", "--slice", "-E", "--setenv",
"--working-directory", "--uid", "--gid", "--nice", "-H", "--host", "-M", "--machine",
"--on-active", "--on-boot", "--on-startup", "--on-unit-active", "--on-unit-inactive",
"--on-calendar", "--path-property", "--socket-property", "--timer-property", "--service-type",
"--shell", "--slice-inherit"}
def main(argv):
args = argv[1:]
if "--user" not in args:
os.execv(REAL, [REAL] + args)
env = dict(os.environ)
cwd = None
foreground = False
i = 0
while i < len(args):
a = args[i]
if a == "--":
i += 1
break
if not a.startswith("-"):
break
name, _, inline = a.partition("=")
value = inline if inline else (args[i + 1] if name in VALUED and i + 1 < len(args) else "")
if name in ("-E", "--setenv") and "=" in value:
k, _, v = value.partition("=")
env[k] = v
elif name == "--working-directory":
cwd = value
elif name in ("--scope", "--wait", "-W", "--pipe", "-P", "-t", "--pty"):
foreground = True
i += 1 if inline or name not in VALUED else 2
command = args[i:]
if not command:
os.execv(REAL, [REAL] + args)
if cwd:
os.chdir(cwd)
if foreground:
os.execvpe(command[0], command, env)
if os.fork() == 0:
os.setsid()
null = os.open(os.devnull, os.O_RDWR)
os.dup2(null, 0)
try:
os.execvpe(command[0], command, env)
except OSError:
os._exit(127)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
key=$1
shift
line=$(grep -m1 "^$key=" /etc/droiddeck/strings 2>/dev/null)
text=${line#*=}
[ -n "$line" ] || text=$key
printf "$text\n" "$@"
@@ -101,16 +101,18 @@ def registry_values(root):
return good
def expand(store, ids):
def expand(store, ids, saved=None):
"""The picks with everything they bundle, each once, a bundle's parts before it."""
out, seen = [], set()
saved = saved if isinstance(saved, dict) else {}
def visit(cid, depth):
if cid in seen or depth > 8:
return
seen.add(cid)
found = component(store, cid)
for dep in (found[2] if found else []):
parts = found[2] if found else [d for d in saved.get(cid, []) if valid_id(d)]
for dep in parts:
visit(dep, depth + 1)
out.append(cid)
@@ -444,7 +446,7 @@ def list_line(name, current, item, separator, add, at_end=True):
return reg_value_line(name, "expand_sz" if expand else "sz", separator.join(items))
def apply_registry(pfx, values, state):
def apply_registry(pfx, values, state, held=()):
"""Writes the picked components' registry values into the prefix and takes out the ones of
components turned off: a value goes back to what it was before, an entry added to a list such
as PATH just leaves the list. Returns (values written, notes)."""
@@ -478,6 +480,9 @@ def apply_registry(pfx, values, state):
for ident, record in old.items():
if ident in keep or not isinstance(record, dict) or not isinstance(record.get("key"), str):
continue
if record.get("cid") in held:
keep[ident] = record
continue
reg = files.get(record.get("hive"))
if reg is None:
keep[ident] = record
@@ -555,14 +560,44 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
copied = 0
installed = []
values = []
for cid in expand(store, ids):
held = set()
saved_overrides = state.get("overrides") if isinstance(state.get("overrides"), dict) else {}
saved_requires = state.get("requires") if isinstance(state.get("requires"), dict) else {}
recorded = [c for c in state.get("components", []) if isinstance(c, str) and valid_id(c)]
owners = set(state["files"].values())
registry_owners = {r.get("cid") for r in (state.get("registry") or {}).values() if isinstance(r, dict)}
inferred = set()
guessed = set(state.get("guessed") or []) if "requires" in state else set(ids)
loose = [c for c in recorded if c not in ids and (c in owners or c in registry_owners)]
for cid in ids:
if cid in guessed and component(store, cid) is None and cid in recorded:
saved_requires = dict(saved_requires, **{cid: loose})
inferred.add(cid)
kept_overrides, kept_requires = {}, {}
for cid in expand(store, ids, saved_requires):
found = component(store, cid)
if found is None:
notes.append("%s is not installed; skipped" % cid)
if cid in saved_requires or cid in recorded or cid in owners or cid in registry_owners:
held.add(cid)
if cid in saved_overrides:
names = [n for n in saved_overrides.get(cid, []) if isinstance(n, str)]
else:
names = sorted({Path(rel).stem.lower() for rel, owner in state["files"].items()
if owner == cid and rel.lower().endswith(".dll")})
overrides += names
kept_overrides[cid] = names
if isinstance(saved_requires.get(cid), list) and cid not in inferred:
kept_requires[cid] = saved_requires[cid]
notes.append("%s is not in the store; kept the files it placed until it is installed again" % cid)
else:
notes.append("%s is not installed; skipped" % cid)
continue
installed.append(cid)
names, files, _, registry = found
names, files, requires, registry = found
overrides += names
kept_overrides[cid] = list(names)
if requires:
kept_requires[cid] = list(requires)
values += [(cid, value) for value in registry]
for rel, src in files:
if place(src, pfx / rel, None if rel in state["files"] else compat / BACKUP / rel):
@@ -572,6 +607,9 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
for rel, cid in state["files"].items():
if rel in keep:
continue
if cid in held:
keep[rel] = cid
continue
path = existing(pfx / rel)
saved = compat / BACKUP / rel
if saved.is_file():
@@ -587,10 +625,13 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
except FileNotFoundError:
pass
compat.mkdir(parents=True, exist_ok=True)
new_state = {"files": keep, "components": installed, "registry": state.get("registry", {})}
new_state = {"files": keep, "components": installed + sorted(held), "overrides": kept_overrides,
"requires": kept_requires, "registry": state.get("registry", {})}
if inferred:
new_state["guessed"] = sorted(inferred)
written = 0
if values or new_state["registry"]:
written, registry_notes = apply_registry(pfx, values, new_state)
written, registry_notes = apply_registry(pfx, values, new_state, held)
notes += registry_notes
save_state(compat, new_state)
if copied or removed or restored or written:
@@ -151,13 +151,13 @@ def view_drive(prefix, exe):
if os.path.lexists(link) and (os.path.exists(link) or not os.readlink(link).startswith(str(view.parent.parent) + '/')):
continue
devices.mkdir(parents=True, exist_ok=True)
staged.symlink_to(view)
staged.symlink_to(view.parent)
os.replace(staged, link)
except OSError:
if os.path.lexists(staged):
staged.unlink()
continue
return letter.upper() + ':\\' + str(path.relative_to(view)).replace('/', '\\'), link
return letter.upper() + ':\\' + str(path.relative_to(view.parent)).replace('/', '\\'), link
return exe, None
@@ -276,6 +276,18 @@ bl_vacdiag() {
}
"""
# Steam's shader pre-caching runs its D3D driver query through every Proton tool at each start, as
# "run <client>/bin/d3ddriverquery64.exe" in compatdata/0. Here it has never succeeded (exit 1 every time), and each
# run started Wine in compatdata/0, where the two Protons upgrade the prefix back and forth for many seconds while the
# game starts. Steam gets the same failure without starting Wine; other verbs and prefixes are left alone.
BL_DRIVER_QUERY_SKIP = """
case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in
run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0)
echo "droiddeck-proton: Steam's D3D driver query is not run (it fails here and would start Wine in compatdata/0)" >&2
exit 1 ;;
esac
"""
BL_DIRECTAUDIO_SETUP = """
bl_is_steam_installscript_target() {
local target=${1:-}
@@ -408,7 +420,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_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
"verb=$1; shift", "verb=$1; shift\n" + BL_DRIVER_QUERY_SKIP + 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)
@@ -455,6 +467,15 @@ bl_store_launch "$@"
BL_STORE_ARGS=("$@")
bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$BL_STORE_PROTON" "$verb" "$@" "${BL_EXTRA_ARGS[@]}"
"""
def extra_wrapper_sh(entry_point):
return (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + BL_DRIVER_QUERY_SKIP + 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)
EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools"
{
"compat_tools"
@@ -678,11 +699,7 @@ def adopt_extras(tools):
name = first_key(compat_vdf, ["compatibilitytools", "compat_tools"]) or entry
wrapper = os.path.join(tool_dir, EXTRA_WRAPPER)
try:
body = (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'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(wrapper, extra_wrapper_sh(entry_point), 0o755)
write_changed(manifest, EXTRA_MANIFEST_VDF)
write_changed(compat_vdf, EXTRA_COMPAT_TOOL_VDF % (name, display_name(entry)))
legacy_wrapper = os.path.join(tool_dir, LEGACY_EXTRA_WRAPPER)