mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 04:46:08 +00:00
Merge upstream main while preserving PowerVR integration
This commit is contained in:
commit
03bf84f12a
108 files changed
+9859
-2070
No files matched your search
@@ -453,6 +453,34 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
|
||||
ws.close()
|
||||
|
||||
|
||||
def steam_selection(agent_dir, timeout=5):
|
||||
result = cdp_eval(
|
||||
agent_dir,
|
||||
"""(() => {
|
||||
let node = document.activeElement;
|
||||
while (node) {
|
||||
for (const name of ["data-id", "data-appid"]) {
|
||||
const value = node.getAttribute?.(name);
|
||||
if (/^[1-9][0-9]{0,9}$/.test(value || "")) {
|
||||
const appId = Number(value);
|
||||
if (Number.isSafeInteger(appId) && appId <= 4294967295) return value;
|
||||
}
|
||||
}
|
||||
node = node.parentElement;
|
||||
}
|
||||
return null;
|
||||
})()""",
|
||||
target="Steam Big Picture Mode",
|
||||
timeout=timeout,
|
||||
)
|
||||
value = result.get("value")
|
||||
if value is None:
|
||||
return {"appId": None}
|
||||
if not isinstance(value, str) or not value.isdigit() or not 0 < int(value) <= 4294967295:
|
||||
raise AgentError("INVALID_SELECTION", "Steam returned an invalid selected app id")
|
||||
return {"appId": int(value)}
|
||||
|
||||
|
||||
# --- Game processes ------------------------------------------------------------------------------
|
||||
|
||||
def game_pids(app_id):
|
||||
@@ -624,6 +652,8 @@ def handle(agent_dir, req):
|
||||
raise AgentError("INVALID_REQUEST", "cdp eval needs an expression")
|
||||
return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)),
|
||||
request_timeout(req, 15))
|
||||
if kind == "steam-selection":
|
||||
return steam_selection(agent_dir, request_timeout(req, 5))
|
||||
if kind == "quit":
|
||||
return quit_game(agent_dir, req.get("appId"), request_timeout(req, 15))
|
||||
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
|
||||
|
||||
@@ -168,7 +168,10 @@ def apply_config(env, config, app_id, fixes=None):
|
||||
raise ValueError("invalid environment value")
|
||||
# The app's texture filtering (Display page), as DXVK options appended after the profiles so
|
||||
# a DXVK_CONFIG entry of the user's keeps its own.
|
||||
dxvk = config.get("dxvkConfig")
|
||||
game_dxvk = config.get("dxvkConfigGames", {})
|
||||
if not isinstance(game_dxvk, dict):
|
||||
raise ValueError("invalid game dxvk configuration")
|
||||
dxvk = game_dxvk.get(app_id, config.get("dxvkConfig"))
|
||||
if dxvk is not None:
|
||||
if not isinstance(dxvk, str) or "\0" in dxvk or len(dxvk) > 8192:
|
||||
raise ValueError("invalid dxvk configuration")
|
||||
@@ -255,8 +258,9 @@ EVALUATOR_SCRIPT = re.compile(r"(?:^|[\\/])evaluatorscript_[0-9]+\.vdf$", re.IGN
|
||||
|
||||
def mark_install_scripts(command, env):
|
||||
"""The client is about to run a game's install scripts (iscriptevaluator.exe): mark every process
|
||||
in them as already run first, so no redistributable installer starts - on first launch the
|
||||
shared ones may still be downloading, and on ARM64 Proton the VC++ ones stop with an error."""
|
||||
in them but a Vulkan runtime installer as already run first, so no redistributable installer
|
||||
starts - on first launch the shared ones may still be downloading, and on ARM64 Proton the VC++
|
||||
ones stop with an error."""
|
||||
if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command):
|
||||
return
|
||||
root = env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/python3
|
||||
"""Holds a game launcher's hidden web interface on one slow core while something else has focus.
|
||||
|
||||
Rockstar's launcher keeps drawing its Chromium interface (SocialClubHelper.exe: a renderer, and a
|
||||
GPU process compositing through DXVK) for as long as it runs, hidden behind the game too, and at a
|
||||
higher priority than the game's (Wine passes Chromium's on: the GPU process ran at nice -10). With
|
||||
Red Dead Redemption 2 in front on the RedMagic that was 1.3 to 2.5 cores under FEX, on a phone
|
||||
already held back by its temperature, for a page nobody sees. Held, riding at the throttle limit
|
||||
went from 46.5 to 48.7 fps, 1% lows from 27.5 to 32.6. So while the focused window belongs to
|
||||
anything but the launcher, every helper thread runs on one core of the slowest cluster at nice 19;
|
||||
when the launcher's own window has focus again (signing in, the game closed) each thread gets its
|
||||
own mask and priority back. Stopping the helpers instead would not hold: proot, the tracer of every
|
||||
guest process, resumes a stopped tracee.
|
||||
|
||||
Focus comes from droiddeck-agent's focus.json (the path is the argument), which the agent rewrites
|
||||
whenever gamescope's focus changes. droiddeck-session starts this for Steam sessions;
|
||||
BL_LAUNCHER_CORES=0 leaves the launchers alone."""
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# Image paths (lower case, backslashes), matched at the end: the helpers held back, and the
|
||||
# programs whose window having focus means the user is looking at the launcher.
|
||||
HELPERS = ("\\rockstar games\\social club\\socialclubhelper.exe",)
|
||||
FRONTS = HELPERS + ("\\rockstar games\\launcher\\launcher.exe",)
|
||||
NICE = 19
|
||||
POLL = 2.0
|
||||
# How often a held launcher is looked over again: for a helper the unheld Launcher.exe started
|
||||
# since, and for threads the program has moved back.
|
||||
RESCAN = 10.0
|
||||
STEAM_CLIENT = 769
|
||||
|
||||
|
||||
def log(message):
|
||||
print("droiddeck-launcher-cores: " + message, flush=True)
|
||||
|
||||
|
||||
def image(proc, pid):
|
||||
"""A process's program as Wine names it (argv[0]), lower case with backslashes, or None."""
|
||||
try:
|
||||
with open(proc / str(pid) / "cmdline", "rb") as stream:
|
||||
first = stream.read(4096).split(b"\0", 1)[0]
|
||||
except OSError:
|
||||
return None
|
||||
return first.decode("utf-8", "replace").lower().replace("/", "\\")
|
||||
|
||||
|
||||
def is_one_of(path, suffixes):
|
||||
return path is not None and path.endswith(suffixes)
|
||||
|
||||
|
||||
def tasks(proc, pid):
|
||||
try:
|
||||
return [int(tid) for tid in os.listdir(proc / str(pid) / "task") if tid.isdigit()]
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
class Cores:
|
||||
"""The kernel calls, apart so a test can stand in for them."""
|
||||
|
||||
def own(self):
|
||||
return os.sched_getaffinity(0)
|
||||
|
||||
def get(self, tid):
|
||||
return os.sched_getaffinity(tid), os.getpriority(os.PRIO_PROCESS, tid)
|
||||
|
||||
def set(self, tid, cpus, nice):
|
||||
try:
|
||||
os.sched_setaffinity(tid, cpus)
|
||||
except OSError:
|
||||
# A mask outside the app's cpuset now (Android shrinks it in the background) is
|
||||
# EINVAL; the session's own is always allowed.
|
||||
os.sched_setaffinity(tid, self.own())
|
||||
os.setpriority(os.PRIO_PROCESS, tid, nice)
|
||||
|
||||
|
||||
class Holder:
|
||||
def __init__(self, proc=Path("/proc"), cpufreq=Path("/sys/devices/system/cpu"), cores=None):
|
||||
self.proc = proc
|
||||
self.cpufreq = cpufreq
|
||||
self.cores = cores or Cores()
|
||||
self.held = {} # pid -> {tid: (cpus, nice) before the hold}
|
||||
self.core = None
|
||||
|
||||
def slow_core(self):
|
||||
"""The last core of the slowest cluster the session has - not of the game's cores, which
|
||||
the launcher inherits when BL_GAME_CPUS is set: the core the game misses least."""
|
||||
def top(cpu):
|
||||
try:
|
||||
return int((self.cpufreq / f"cpu{cpu}/cpufreq/cpuinfo_max_freq").read_text())
|
||||
except (OSError, ValueError):
|
||||
return 0
|
||||
cpus = self.cores.own()
|
||||
slowest = min(top(cpu) for cpu in cpus)
|
||||
return max(cpu for cpu in cpus if top(cpu) == slowest)
|
||||
|
||||
def helpers(self):
|
||||
for name in os.listdir(self.proc):
|
||||
if name.isdigit() and is_one_of(image(self.proc, name), HELPERS):
|
||||
yield int(name)
|
||||
|
||||
def hold(self):
|
||||
"""Every helper thread onto the slow core at NICE: new ones, and held ones the program has
|
||||
moved since (Chromium sets its threads' priorities, and Wine passes that on)."""
|
||||
if self.core is None:
|
||||
self.core = self.slow_core()
|
||||
hold = ({self.core}, NICE)
|
||||
for pid in self.helpers():
|
||||
before = self.held.setdefault(pid, {})
|
||||
for tid in tasks(self.proc, pid):
|
||||
try:
|
||||
now = self.cores.get(tid)
|
||||
if now != hold:
|
||||
self.cores.set(tid, *hold)
|
||||
except OSError:
|
||||
continue # the thread ended
|
||||
if tid not in before:
|
||||
# A thread that already has the hold inherited it from a held parent: it gets
|
||||
# what its process had, or the helpers' first.
|
||||
before[tid] = now if now != hold else before.get(pid) or self.first() or now
|
||||
for pid in [pid for pid in self.held if not (self.proc / str(pid)).exists()]:
|
||||
del self.held[pid]
|
||||
|
||||
def first(self):
|
||||
for before in self.held.values():
|
||||
for state in before.values():
|
||||
if state != ({self.core}, NICE):
|
||||
return state
|
||||
return None
|
||||
|
||||
def release(self):
|
||||
"""Every held thread back to its own mask and priority; one started during the hold gets
|
||||
what its process had."""
|
||||
for pid, before in self.held.items():
|
||||
default = before.get(pid) or self.first()
|
||||
for tid in tasks(self.proc, pid):
|
||||
state = before.get(tid, default)
|
||||
if state is None:
|
||||
continue
|
||||
try:
|
||||
self.cores.set(tid, *state)
|
||||
except OSError:
|
||||
pass
|
||||
self.held.clear()
|
||||
|
||||
|
||||
def focused(snapshot):
|
||||
"""(app id, pid) of the window gamescope has focused, from droiddeck-agent's snapshot."""
|
||||
window = snapshot.get("focusedWindow")
|
||||
for entry in snapshot.get("focusableWindows") or []:
|
||||
if entry.get("window") == window:
|
||||
return snapshot.get("focusedApp"), entry.get("pid")
|
||||
return snapshot.get("focusedApp"), None
|
||||
|
||||
|
||||
class Governor:
|
||||
def __init__(self, focus_path, holder=None, clock=time.monotonic):
|
||||
self.focus_path = Path(focus_path)
|
||||
self.holder = holder or Holder()
|
||||
self.clock = clock
|
||||
self.seen = None
|
||||
self.app = self.pid = None
|
||||
self.scanned = None
|
||||
self.reported = None
|
||||
|
||||
def read_focus(self):
|
||||
try:
|
||||
stamp = self.focus_path.stat().st_mtime_ns
|
||||
except OSError:
|
||||
return False
|
||||
if stamp == self.seen:
|
||||
return False
|
||||
try:
|
||||
self.app, self.pid = focused(json.loads(self.focus_path.read_text()))
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return False
|
||||
self.seen = stamp
|
||||
return True
|
||||
|
||||
def tick(self):
|
||||
changed = self.read_focus()
|
||||
if self.pid is None:
|
||||
return
|
||||
launcher_in_front = is_one_of(image(self.holder.proc, self.pid), FRONTS)
|
||||
if launcher_in_front:
|
||||
if self.holder.held:
|
||||
self.holder.release()
|
||||
self.report("released: the launcher has focus")
|
||||
return
|
||||
# Nothing to look for until a game has had focus: launchers only run for one, and a launcher
|
||||
# left running after its game stays held through the Steam client's own focus.
|
||||
if self.app in (None, 0, STEAM_CLIENT) and not self.holder.held:
|
||||
return
|
||||
now = self.clock()
|
||||
if changed or self.scanned is None or now - self.scanned >= RESCAN:
|
||||
self.scanned = now
|
||||
self.holder.hold()
|
||||
if self.holder.held:
|
||||
self.report(f"{len(self.holder.held)} SocialClubHelper process(es) on core {self.holder.core} "
|
||||
f"at nice {NICE} while the launcher is hidden")
|
||||
|
||||
def report(self, message):
|
||||
if message != self.reported:
|
||||
self.reported = message
|
||||
log(message)
|
||||
|
||||
def stop(self, *_):
|
||||
self.holder.release()
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 1:
|
||||
print("usage: droiddeck-launcher-cores <agent focus.json>", file=sys.stderr)
|
||||
return 2
|
||||
governor = Governor(argv[0])
|
||||
signal.signal(signal.SIGTERM, governor.stop)
|
||||
signal.signal(signal.SIGHUP, governor.stop)
|
||||
signal.signal(signal.SIGINT, governor.stop)
|
||||
while True:
|
||||
governor.tick()
|
||||
time.sleep(POLL)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -4,14 +4,15 @@
|
||||
#
|
||||
# droiddeck-proton-extra <steam root> ge [--tag GE-Proton11-7]
|
||||
# droiddeck-proton-extra <steam root> cachyos [--tag cachyos-11.0-20260703-slr]
|
||||
# droiddeck-proton-extra <steam root> droiddeck [--tag DroidDeck-Proton-11-7.5]
|
||||
# droiddeck-proton-extra <steam root> <url of an aarch64 tarball>
|
||||
# droiddeck-proton-extra <steam root> /path/to/an/aarch64/tarball
|
||||
# droiddeck-proton-extra <steam root> --list what is installed now
|
||||
#
|
||||
# Both projects publish native ARM64 builds - GloriousEggroll as "*-aarch64.tar.gz", CachyOS as
|
||||
# "*-arm64.tar.xz" - and both are ordinary Proton trees: a python entry point beside a files/
|
||||
# directory holding Wine, DXVK and VKD3D. That is the same shape as the depot the Steam client
|
||||
# downloads, so the runtime can run them the same way.
|
||||
# All three projects publish native ARM64 builds - GloriousEggroll and DroidDeck-Proton as
|
||||
# "*-aarch64.tar.gz", CachyOS as "*-arm64.tar.xz" - and all are ordinary Proton trees: a python
|
||||
# entry point beside a files/ directory holding Wine, DXVK and VKD3D. That is the same shape as the
|
||||
# depot the Steam client downloads, so the runtime can run them the same way.
|
||||
#
|
||||
# What it cannot use is their toolmanifest. Like Valve's ARM64 depot they declare
|
||||
# require_tool_appid, which makes Steam stack pressure-vessel underneath - and pressure-vessel
|
||||
@@ -30,11 +31,12 @@ import urllib.request
|
||||
|
||||
RELEASES = "https://api.github.com/repos/%s/releases"
|
||||
# Each source: the GitHub repo, and how its ARM64 asset is named. Ordered newest-release-first by
|
||||
# the API, so "latest usable" is the first release that actually carries an ARM64 asset - the
|
||||
# the API, so "latest usable" is the first full release that actually carries an ARM64 asset - the
|
||||
# projects do not build one for every tag.
|
||||
SOURCES = {
|
||||
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
||||
"cachyos": ("CachyOS/proton-cachyos", re.compile(r"arm64\.tar\.(gz|xz)$")),
|
||||
"droiddeck": ("The412Banner/DroidDeck-Proton", re.compile(r"aarch64\.tar\.(gz|xz)$")),
|
||||
}
|
||||
USER_AGENT = "droiddeck-proton-extra"
|
||||
# Room for the tarball and the tree it unpacks to. GE-Proton's aarch64 build is ~650 MB packed and
|
||||
@@ -54,10 +56,10 @@ def fetch_json(url):
|
||||
|
||||
|
||||
def pick_asset(source):
|
||||
"""(release tag, asset url, sha512 url or None) for the newest release with an ARM64 build."""
|
||||
"""(release tag, asset url, sha512 url or None) for the newest full release with an ARM64 build."""
|
||||
repo, pattern = SOURCES[source]
|
||||
for release in fetch_json(RELEASES % repo + "?per_page=15"):
|
||||
if release.get("draft"):
|
||||
if release.get("draft") or release.get("prerelease"):
|
||||
continue
|
||||
assets = {a["name"]: a["browser_download_url"] for a in release.get("assets", ())}
|
||||
for name in sorted(assets):
|
||||
@@ -144,7 +146,7 @@ def installed(tools):
|
||||
def main():
|
||||
argv = sys.argv[1:]
|
||||
if not argv:
|
||||
raise SystemExit(__doc__ or "usage: droiddeck-proton-extra <steam root> ge|cachyos|<url>")
|
||||
raise SystemExit(__doc__ or "usage: droiddeck-proton-extra <steam root> ge|cachyos|droiddeck|<url>")
|
||||
steam_root = argv.pop(0)
|
||||
tools = os.path.join(steam_root, "compatibilitytools.d")
|
||||
os.makedirs(tools, exist_ok=True)
|
||||
@@ -176,7 +178,7 @@ def main():
|
||||
log("using %s" % what)
|
||||
else:
|
||||
raise SystemExit(
|
||||
"droiddeck-proton-extra: expected ge, cachyos, a URL or a tarball path, got %r" % what)
|
||||
"droiddeck-proton-extra: expected ge, cachyos, droiddeck, a URL or a tarball path, got %r" % what)
|
||||
|
||||
free = shutil.disk_usage(tools).free
|
||||
if free < NEED_BYTES:
|
||||
|
||||
@@ -17,6 +17,11 @@
|
||||
# 2015-2022 runtime is recorded as installed the way Microsoft's installers look for it: on ARM64
|
||||
# Proton the x64 bundle otherwise stops with "Microsoft Visual C++ 2015-2022 Redistributable (arm64)
|
||||
# is required", while Proton's own msvcp140/vcruntime140 already serve the game.
|
||||
#
|
||||
# A Vulkan runtime installer is the one left to run. Proton has no stand-in for it: for a game whose
|
||||
# Steam compat config says nativevulkanloader (Red Dead Redemption 2) it loads vulkan-1.dll native
|
||||
# only, and Khronos' loader is in the prefix only once that installer has run - without it the game
|
||||
# exits with STATUS_DLL_NOT_FOUND before it opens a window. The installer finishes in a second.
|
||||
set -u
|
||||
steam_root=${1:?steam root}
|
||||
LIBRARIES=${DROIDDECK_LIBRARIES-/mnt/droiddeck /mnt/droiddeck-sd}
|
||||
@@ -25,14 +30,15 @@ redist="$steam_root/steamapps/common/Steamworks Shared/_CommonRedist"
|
||||
|
||||
# Every process an install script would run, as the registry key and value the client writes once
|
||||
# it has run it. Names sit one level inside "Run Process", the key they share a level further in.
|
||||
read_scripts() { xargs -0 -r awk '
|
||||
# "read_scripts vulkan" lists only the Vulkan runtime installers, which the plain call leaves out.
|
||||
read_scripts() { xargs -0 -r awk -v want="${1:-redists}" '
|
||||
# A block whose HasRunKey is set is one process; its name is the key the block opened under, at
|
||||
# whatever depth - an install script nests it under "Run Process", the client'"'"'s evaluator script
|
||||
# for a game wraps the same blocks once more.
|
||||
FNR == 1 { depth = 0; pending = "" }
|
||||
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; pending = ""; next }
|
||||
/^[[:space:]]*\{/ { depth++; name[depth] = pending; key[depth] = ""; vulkan[depth] = 0; pending = ""; next }
|
||||
/^[[:space:]]*\}/ {
|
||||
if (depth > 0 && key[depth] != "" && name[depth] != "")
|
||||
if (depth > 0 && key[depth] != "" && name[depth] != "" && vulkan[depth] == (want == "vulkan"))
|
||||
printf "%s\t%s\n", key[depth], name[depth]
|
||||
if (depth > 0) depth--
|
||||
next
|
||||
@@ -40,6 +46,12 @@ read_scripts() { xargs -0 -r awk '
|
||||
{
|
||||
n = split($0, part, "\"")
|
||||
if (n >= 5 && tolower(part[2]) == "hasrunkey") { key[depth] = part[4]; next }
|
||||
if (n >= 5 && tolower(part[2]) ~ /^process [0-9]+$/) {
|
||||
program = tolower(part[4])
|
||||
sub(/.*[\\\/]/, "", program)
|
||||
if (program ~ /vulkan/) vulkan[depth] = 1
|
||||
next
|
||||
}
|
||||
if (n == 3) pending = part[2]
|
||||
}
|
||||
'; }
|
||||
@@ -84,13 +96,17 @@ if [ "$(head -n 1 "$cache" 2>/dev/null)" != "$sig" ]; then
|
||||
done <<<"$libraries" | sort -u
|
||||
} >"$cache.tmp" && mv -f "$cache.tmp" "$cache"
|
||||
fi
|
||||
game_pairs=$(tail -n +2 "$cache" 2>/dev/null | tr '\n' '\0' | read_scripts)
|
||||
# DROIDDECK_SEED_SCRIPTS: more scripts, one path a line - droiddeck-game-env passes the client's
|
||||
# evaluator script for the game about to run its installers, read before the client looks.
|
||||
if [ -n "${DROIDDECK_SEED_SCRIPTS:-}" ]; then
|
||||
game_pairs=$(printf '%s\n%s\n' "$game_pairs" "$(printf '%s\n' "$DROIDDECK_SEED_SCRIPTS" | tr '\n' '\0' | read_scripts)")
|
||||
fi
|
||||
game_scripts() { { tail -n +2 "$cache" 2>/dev/null; printf '%s\n' "${DROIDDECK_SEED_SCRIPTS:-}"; } | sed '/^$/d' | tr '\n' '\0'; }
|
||||
game_pairs=$(game_scripts | read_scripts)
|
||||
[ -n "$(printf '%s' "$game_pairs" | tr -d '[:space:]')" ] && pairs=$(printf '%s\n%s\n' "$pairs" "$game_pairs" | sort -u | sed '/^$/d')
|
||||
# A Vulkan runtime installer marked as run by an earlier seeding still has its marker: those come out
|
||||
# again below, so the client runs the installer on the game's next launch.
|
||||
declare -A vulkan=()
|
||||
while IFS= read -r line; do
|
||||
[[ $line == *$'\t'* ]] && vulkan[$line]=1
|
||||
done < <(game_scripts | read_scripts vulkan)
|
||||
|
||||
# The VC++ 2015-2022 runtime as its installers check for it, for each architecture and both registry
|
||||
# views. The version is the newest the scripts above know, so any 2015-2022 bundle finds itself
|
||||
@@ -138,6 +154,38 @@ block_for() { printf '%s\n' "$@" | awk -F'\t' -v now="$now" '
|
||||
for line; do [[ $line == vcrt$'\t'* ]] && vcrt "$now"; done
|
||||
}
|
||||
|
||||
# Takes the given markers out of a registry file again, in both views, keeping its date.
|
||||
unseed() {
|
||||
local reg=$1 out
|
||||
shift
|
||||
out=$(mktemp "${reg%/*}/.system.reg.XXXXXX") || return 1
|
||||
if printf '%s\n' "$@" | awk -F'\t' '
|
||||
NR == FNR {
|
||||
path = $1
|
||||
sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path)
|
||||
if (path == $1)
|
||||
next
|
||||
path = tolower(path)
|
||||
drop["[" path "]" SUBSEP tolower($2)] = 1
|
||||
if (substr(path, 1, 10) == "software\\\\")
|
||||
drop["[software\\\\wow6432node\\\\" substr(path, 11) "]" SUBSEP tolower($2)] = 1
|
||||
next
|
||||
}
|
||||
/^\[/ { section = tolower(substr($0, 1, index($0, "]"))) }
|
||||
/^"/ {
|
||||
value = substr($0, 2)
|
||||
value = tolower(substr(value, 1, index(value, "\"=") - 1))
|
||||
if ((section SUBSEP value) in drop)
|
||||
next
|
||||
}
|
||||
{ print }
|
||||
' - "$reg" >"$out" && touch -r "$reg" "$out" && mv -f "$out" "$reg"; then
|
||||
return 0
|
||||
fi
|
||||
rm -f "$out"
|
||||
return 1
|
||||
}
|
||||
|
||||
# Proton builds a new prefix from its template, and the client runs the install scripts in that
|
||||
# prefix moments later, so the template carries the markers too. Its date is kept: Proton reads a
|
||||
# changed one as a new template and upgrades every prefix made from the old.
|
||||
@@ -158,6 +206,16 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
|
||||
if [ -f "$seeded" ]; then
|
||||
while IFS= read -r line; do [[ $line == *$'\t'* ]] && had[$line]=1; done <"$seeded"
|
||||
fi
|
||||
stale=() kept=()
|
||||
for line in "${!had[@]}"; do
|
||||
if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi
|
||||
done
|
||||
if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then
|
||||
had=()
|
||||
for line in "${kept[@]}"; do had[$line]=1; done
|
||||
printf '%s\n' "${kept[@]}" >"$seeded"
|
||||
echo "== took Vulkan runtime markers out of $reg"
|
||||
fi
|
||||
missing=()
|
||||
for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done
|
||||
[ ${#missing[@]} -eq 0 ] && continue
|
||||
|
||||
@@ -50,6 +50,37 @@ prepare_locale() {
|
||||
}
|
||||
[ -z "${BL_INSIDE:-}" ] && prepare_locale
|
||||
|
||||
# What earlier sessions left in /tmp. The guest's /tmp is a directory in the rootfs, never emptied
|
||||
# by a boot, and Android ends sessions by killing them: each left its mangoapp config, the client's
|
||||
# temporary directories and shared-memory sockets, Chromium's singleton directory (the web
|
||||
# helper's, an Electron app's), a session bus socket per run and a run's start stamp - 1,400
|
||||
# entries on a device after a few weeks. Each kind is swept while nothing that could own one runs,
|
||||
# with one find for the lot.
|
||||
clear_stale_tmp() {
|
||||
local running names=() n
|
||||
running=$(pgrep -af 'steamwebhelper|steamrtarm64/steam|--type=|droiddeck-appimage-run|dbus-run-session|dbus-daemon.*--session|dbus-launch|kwin|plasmashell' 2>/dev/null)
|
||||
case $running in
|
||||
*steamwebhelper* | *steamrtarm64/steam*) ;;
|
||||
*) names+=(-o -name 'mangohud.????????' -o -name '.com.valvesoftware.Steam.??????'
|
||||
-o -name 'steam_chrome_shmem_uid*' -o \( -type d -empty -name 'steam??????' \)) ;;
|
||||
esac
|
||||
case $running in *--type=*) ;; *) names+=(-o \( -type d -name 'scoped_dir??????' \)) ;; esac
|
||||
case $running in *droiddeck-appimage-run*) ;; *) names+=(-o -name 'droiddeck-appimage.??????') ;; esac
|
||||
case $running in
|
||||
*dbus-run-session* | *dbus-daemon*--session* | *dbus-launch*) ;;
|
||||
*) names+=(-o \( -type s -name 'dbus-??????????' \)) ;;
|
||||
esac
|
||||
case $running in
|
||||
*kwin* | *plasmashell*) ;;
|
||||
*) names+=(-o \( -type d -empty -name 'plasma-csd-generator.??????' \)) ;;
|
||||
esac
|
||||
[ ${#names[@]} -gt 0 ] || return 0
|
||||
n=$(find /tmp -mindepth 1 -maxdepth 1 \( "${names[@]:1}" \) -print -exec rm -rf {} + 2>/dev/null | wc -l)
|
||||
[ "$n" -gt 0 ] && echo "== /tmp: cleared $n entries earlier sessions left"
|
||||
return 0
|
||||
}
|
||||
[ -z "${BL_INSIDE:-}" ] && clear_stale_tmp
|
||||
|
||||
# Until the runtime is stable, Steam's own logs are copied beside the session log at exit so a
|
||||
# failed launch can be handed over as one folder.
|
||||
collect_steam_logs() {
|
||||
@@ -277,7 +308,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
# BL_MANGOAPP=0 turns it off (one community build found Valve's mangoapp crashing on Turnip).
|
||||
if [ "$mode" = steam ] && [ "${BL_MANGOAPP:-1}" = 1 ] \
|
||||
&& [ "${BL_STEAM_UI:-}" != desktop ] && command -v mangoapp >/dev/null 2>&1; then
|
||||
MANGOHUD_CONFIGFILE=$(mktemp /tmp/mangohud.XXXXXXXX)
|
||||
# One fixed file, rewritten each session: a mktemp name per session was never removed.
|
||||
MANGOHUD_CONFIGFILE=/tmp/droiddeck-mangohud.conf
|
||||
echo no_display > "$MANGOHUD_CONFIGFILE"
|
||||
export MANGOHUD_CONFIGFILE STEAM_USE_MANGOAPP=1 STEAM_MANGOAPP_PRESETS_SUPPORTED=1 STEAM_MANGOAPP_HORIZONTAL_SUPPORTED=1
|
||||
args+=(--mangoapp)
|
||||
@@ -382,9 +414,9 @@ case $mode in
|
||||
# its main library already - and the ARM64 Proton that lets it launch the Windows ones.
|
||||
# A request left in ~/.bl-proton-extra installs a third-party Proton before the client starts,
|
||||
# so it is in the Compatibility dropdown the first time the user looks. One per line, each the
|
||||
# arguments to droiddeck-proton-extra: "ge", "cachyos", "ge --tag GE-Proton11-7", or a URL.
|
||||
# Hundreds of megabytes each, so it is only ever done on request, and the line is dropped once
|
||||
# it has succeeded - a failed download stays and is retried next session.
|
||||
# arguments to droiddeck-proton-extra: "ge", "cachyos", "droiddeck", "ge --tag GE-Proton11-7",
|
||||
# or a URL. Hundreds of megabytes each, so it is only ever done on request, and the line is
|
||||
# dropped once it has succeeded - a failed download stays and is retried next session.
|
||||
if [ -s "$HOME/.bl-proton-extra" ]; then
|
||||
_bl_left=$HOME/.bl-proton-extra.left
|
||||
: > "$_bl_left"
|
||||
@@ -440,6 +472,13 @@ case $mode in
|
||||
done
|
||||
) &
|
||||
fi
|
||||
# Rockstar's launcher keeps drawing its hidden web interface for as long as a game of theirs
|
||||
# runs; droiddeck-launcher-cores holds it on one slow core while it is out of sight, from
|
||||
# gamescope's focus as the agent publishes it. BL_LAUNCHER_CORES=0 leaves launchers alone.
|
||||
if [ "${BL_LAUNCHER_CORES:-1}" != 0 ] && [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ] \
|
||||
&& [ "${BL_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then
|
||||
/usr/local/bin/droiddeck-launcher-cores "$BL_LAUNCH_DIR/agent/focus.json" 2>&1 &
|
||||
fi
|
||||
|
||||
step "registering the app's game library with Steam"
|
||||
droiddeck-steam-library "$steam_root" || true
|
||||
|
||||
@@ -447,10 +447,15 @@ class Helper:
|
||||
self.installed = installed
|
||||
picks = COMPAT["valve_picks"](self.steam_root)
|
||||
apps = sorted(set(installed) | set(picks) | set(state.get("auto", {})), key=COMPAT["app_order"])
|
||||
overrides = COMPAT["requested_games"](
|
||||
COMPAT["game_requests"](), catalog, [t["name"] for t in live])
|
||||
apps = sorted(set(apps) | set(overrides), key=COMPAT["app_order"])
|
||||
current = dict(page.compat("many(%s)" % json.dumps(apps)) or {})
|
||||
current["0"] = top["selected"]
|
||||
native = COMPAT["native_targets"](self.steam_root, installed)
|
||||
changes, auto = COMPAT["plan_mapping"](current, installed, [t["name"] for t in live], default, COMPAT["followers"](state, current), native, picks)
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
current, installed, [t["name"] for t in live], default,
|
||||
COMPAT["followers"](state, current), native, picks, overrides)
|
||||
for app, tool in sorted(changes.items(), key=lambda item: COMPAT["app_order"](item[0])):
|
||||
page.compat("set(%d, %s)" % (int(app), json.dumps(tool)))
|
||||
say("%s -> %s" % ("default" if app == "0" else "app %s" % app, tool))
|
||||
@@ -489,7 +494,7 @@ class Helper:
|
||||
if self.page.ws in ready:
|
||||
due = any(called(e, BINDING) for e in self.drain())
|
||||
if (watcher in ready or watcher.fileno() < 0) and watcher.changed():
|
||||
due = self.installed != COMPAT["installed_apps"](self.steam_root) or self.request_waiting()
|
||||
due = True
|
||||
if due:
|
||||
time.sleep(0.3)
|
||||
if watcher.fileno() >= 0 and select.select([watcher], [], [], 0)[0]:
|
||||
@@ -519,7 +524,8 @@ def main():
|
||||
say("no devtools port for this session; the client's mapping is kept through config.vdf")
|
||||
return 0
|
||||
os.makedirs(COMPAT["COMPAT_DIR"], exist_ok=True)
|
||||
watcher = Watcher([COMPAT["state_path"]("request.json")] + [os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
|
||||
watcher = Watcher([COMPAT["state_path"]("request.json"), COMPAT["state_path"]("games.json")] +
|
||||
[os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
|
||||
# The client has its own SteamOS manager when started as SteamOS (droiddeck-session's Deck mode).
|
||||
steamos = os.environ.get("BL_STEAMDECK") == "1" and os.environ.get("BL_STEAM_UI") != "desktop"
|
||||
helper = Helper(steam_root, port, steamos)
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
#!/usr/bin/python3
|
||||
"""Initialize Steam's own Gamescope display settings once; subsequent choices belong to Steam.
|
||||
"""Initialize Steam's own display settings once; subsequent choices belong to Steam.
|
||||
|
||||
The UI scale, and native resolution: the client treats our gamescope as an external display and,
|
||||
unless "Enable Native Resolution on External Displays" is on, draws itself at 1920x1080 on any
|
||||
larger output - a 2340x1080 session came up as 16:9 with bars. The session's size is already the
|
||||
user's Resolution choice, so the client should use all of it."""
|
||||
user's Resolution choice, so the client should use all of it.
|
||||
|
||||
And the screensaver over a running game. The client's defaults (steamui.so's settings descriptor)
|
||||
show screensavers while a game runs, after 300 s on AC power with no button pressed - and a stick or
|
||||
trigger held is no press. Red Dead Redemption 2's cutscenes run longer than that: the slideshow
|
||||
covered the game, and the button that woke it reached the game as well (B asked to quit to the
|
||||
desktop). Customization > Screensaver > "Show screensavers when playing a game" still turns it on."""
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -15,6 +21,8 @@ import tempfile
|
||||
|
||||
DISPLAY = "External: gamescope|||Windowed"
|
||||
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
|
||||
# screensaver_while_ingame: kept in config.vdf like the Gamescope settings, under this path.
|
||||
SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame")
|
||||
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
|
||||
|
||||
|
||||
@@ -108,25 +116,43 @@ def seed_text(text, scale):
|
||||
return text[:at] + insertion + text[at:], True
|
||||
|
||||
|
||||
def seed_native_resolution(text):
|
||||
def seed_value(text, path, value):
|
||||
"""InstallConfigStore/<path> = value, unless the client already has a value there (the
|
||||
user's), adding only the blocks that are missing."""
|
||||
root = parse(text).get('InstallConfigStore')
|
||||
if not isinstance(root, Block):
|
||||
raise ValueError("missing InstallConfigStore")
|
||||
gamescope = root.get('Gamescope')
|
||||
if gamescope is not None and not isinstance(gamescope, Block):
|
||||
raise ValueError("invalid Gamescope settings")
|
||||
if gamescope is not None and gamescope.get(NATIVE_RESOLUTION) is not None:
|
||||
*sections, name = path
|
||||
block, depth = root, 1
|
||||
while sections:
|
||||
child = block.get(sections[0])
|
||||
if child is None:
|
||||
break
|
||||
if not isinstance(child, Block):
|
||||
raise ValueError(f"invalid {sections[0]} settings")
|
||||
block, depth = child, depth + 1
|
||||
sections.pop(0)
|
||||
if not sections and block.get(name) is not None:
|
||||
return text, False
|
||||
entry = f'"{NATIVE_RESOLUTION}" "1"'
|
||||
if gamescope is not None:
|
||||
at, indent = gamescope.end, 2
|
||||
else:
|
||||
entry = '"Gamescope"\n{\n' + entry + '\n}'
|
||||
at, indent = root.end, 1
|
||||
insertion = '\n' + '\n'.join('\t' * indent + line for line in entry.splitlines()) + '\n'
|
||||
lines = [(len(sections), f'"{name}"\t\t"{value}"')]
|
||||
for level, section in reversed(list(enumerate(sections))):
|
||||
lines = [(level, f'"{section}"'), (level, '{')] + lines + [(level, '}')]
|
||||
insertion = ''.join('\t' * (depth + level) + line + '\n' for level, line in lines)
|
||||
# Before the line the block closes on, when it has one of its own; else beside the brace.
|
||||
at = text.rfind('\n', 0, block.end) + 1
|
||||
if text[at:block.end].strip():
|
||||
at, insertion = block.end, '\n' + insertion
|
||||
return text[:at] + insertion + text[at:], True
|
||||
|
||||
|
||||
def seed_native_resolution(text):
|
||||
return seed_value(text, ('Gamescope', NATIVE_RESOLUTION), '1')
|
||||
|
||||
|
||||
def seed_no_screensaver_in_game(text):
|
||||
return seed_value(text, SCREENSAVER_IN_GAME, '0')
|
||||
|
||||
|
||||
def atomic_write(path, text):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
|
||||
@@ -140,31 +166,36 @@ def atomic_write(path, text):
|
||||
|
||||
|
||||
def initialize(steam_root, width, height):
|
||||
scale = initial_scale(width, height)
|
||||
return seed_once(steam_root, 'droiddeck-ui-scale-initialized', lambda text: seed_text(text, scale),
|
||||
f'== steam: initial handheld UI scale {scale:.3f}')
|
||||
|
||||
|
||||
def seed_once(steam_root, marker_name, seed, message):
|
||||
"""Applies seed to config.vdf the first time only: the marker keeps a later choice - including
|
||||
a return to the client's own default, which the client may store by dropping the key - the
|
||||
user's."""
|
||||
config = Path(steam_root) / 'config/config.vdf'
|
||||
marker = config.with_name('droiddeck-ui-scale-initialized')
|
||||
marker = config.with_name(marker_name)
|
||||
if marker.exists():
|
||||
return False
|
||||
text = config.read_text() if config.exists() else '"InstallConfigStore"\n{\n}\n'
|
||||
updated, changed = seed_text(text, initial_scale(width, height))
|
||||
updated, changed = seed(text)
|
||||
if changed:
|
||||
atomic_write(config, updated)
|
||||
print(f'== steam: initial handheld UI scale {initial_scale(width, height):.3f}')
|
||||
print(message)
|
||||
atomic_write(marker, '1\n')
|
||||
return changed
|
||||
|
||||
|
||||
def initialize_native_resolution(steam_root):
|
||||
config = Path(steam_root) / 'config/config.vdf'
|
||||
marker = config.with_name('droiddeck-native-resolution-initialized')
|
||||
if marker.exists():
|
||||
return False
|
||||
text = config.read_text() if config.exists() else '"InstallConfigStore"\n{\n}\n'
|
||||
updated, changed = seed_native_resolution(text)
|
||||
if changed:
|
||||
atomic_write(config, updated)
|
||||
print('== steam: native resolution on the session display')
|
||||
atomic_write(marker, '1\n')
|
||||
return changed
|
||||
return seed_once(steam_root, 'droiddeck-native-resolution-initialized', seed_native_resolution,
|
||||
'== steam: native resolution on the session display')
|
||||
|
||||
|
||||
def initialize_screensaver(steam_root):
|
||||
return seed_once(steam_root, 'droiddeck-screensaver-initialized', seed_no_screensaver_in_game,
|
||||
'== steam: no screensaver over a running game')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -174,9 +205,10 @@ if __name__ == '__main__':
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr)
|
||||
status = 1
|
||||
try:
|
||||
initialize_native_resolution(sys.argv[1])
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
print('== steam: left native resolution unchanged: ' + str(error), file=sys.stderr)
|
||||
status = 1
|
||||
for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)):
|
||||
try:
|
||||
step(sys.argv[1])
|
||||
except (OSError, ValueError, RecursionError) as error:
|
||||
print(f'== steam: left {what} unchanged: {error}', file=sys.stderr)
|
||||
status = 1
|
||||
sys.exit(status)
|
||||
@@ -92,10 +92,12 @@ TOOL_MANIFEST_VDF = """"manifest"
|
||||
# relies on compatdata/0 itself. The launch-time check below is the protection instead.
|
||||
|
||||
# The Components page's choices, enforced in the one place every game launch passes: the app keeps
|
||||
# desired.tsv (tool dir, Proton build, component, file, sha256, source copy) and an unpacked copy of
|
||||
# each package in use. A file that no longer matches - whatever changed it - is put back before
|
||||
# Proton starts. Only for the Proton build the choice was made for: after a Steam update the build
|
||||
# differs and the Proton's own new files are left alone until the user chooses again.
|
||||
# desired.tsv (scope, tool dir, Proton build, component, file, sha256, source copy) and an unpacked
|
||||
# copy of each package in use. A game's rows replace General rows for that component. A `-` source
|
||||
# removes a managed file absent from the selected package, so one game's package cannot leak into
|
||||
# the next game. A file that no longer matches - whatever changed it - is put back before Proton
|
||||
# starts. Only the matching Proton build is changed; after a Steam update the build differs and the
|
||||
# Proton's own new files are left alone until the user chooses again.
|
||||
# A store game (GOG, Epic, Amazon) is started through the launcher .bat DroidDeck wrote beside it.
|
||||
# An Epic game needs a fresh sign-in code, which only the app can mint: droiddeck-store-launch asks
|
||||
# for it and the app writes it into the game's folder, so a launch from the client's own Play
|
||||
@@ -149,21 +151,59 @@ bl_components() {
|
||||
[ "${verb:-}" = waitforexitandrun ] || return 0
|
||||
case "${STEAM_COMPAT_DATA_PATH:-}" in ''|*/compatdata/0|*/compatdata/0/|*/compatdata/0-*) return 0 ;; esac
|
||||
[ -f "$cm_list" ] || return 0
|
||||
cm_app=${STEAM_COMPAT_DATA_PATH%/}
|
||||
cm_app=${STEAM_COMPAT_DATA_PATH}
|
||||
while [[ "$cm_app" == */ ]]; do cm_app=${cm_app%/}; done
|
||||
cm_app=${cm_app##*/}
|
||||
if [[ "$cm_app" =~ ^(-?)([0-9]+)$ ]]; then
|
||||
cm_sign=${BASH_REMATCH[1]}
|
||||
cm_digits=${BASH_REMATCH[2]}
|
||||
while [[ ${#cm_digits} -gt 1 && "$cm_digits" == 0* ]]; do cm_digits=${cm_digits#0}; done
|
||||
if [[ ${#cm_digits} -le 10 ]]; then
|
||||
cm_app=$((10#$cm_digits))
|
||||
[ "$cm_sign" = "-" ] && cm_app=$((-cm_app))
|
||||
if (( cm_app >= -2147483648 && cm_app <= 4294967295 && cm_app != 0 )); then
|
||||
(( cm_app < 0 )) && cm_app=$((cm_app + 4294967296))
|
||||
else
|
||||
cm_app=""
|
||||
fi
|
||||
else
|
||||
cm_app=""
|
||||
fi
|
||||
else
|
||||
cm_app=""
|
||||
fi
|
||||
if [ -z "$cm_app" ]; then
|
||||
echo "droiddeck-proton: components: invalid game prefix, left as it is" >&2
|
||||
return 0
|
||||
fi
|
||||
cm_tool=${base##*/}
|
||||
cm_build=$(awk 'NR == 1 { print $2 }' "$base/version" 2>/dev/null)
|
||||
cm_fixed=0
|
||||
cm_checked=0
|
||||
cm_selected=$(awk -F '\\t' -v app="$cm_app" -v tool="$cm_tool" -v build="$cm_build" '
|
||||
$2 == tool && $3 == build {
|
||||
rows[++count] = $0
|
||||
scopes[count] = $1
|
||||
comps[count] = $4
|
||||
if ($1 == app) specific[$4] = 1
|
||||
}
|
||||
END {
|
||||
for (i = 1; i <= count; i++)
|
||||
if (scopes[i] == app || (scopes[i] == "*" && !specific[comps[i]])) print rows[i]
|
||||
}
|
||||
' "$cm_list")
|
||||
# One sha256sum for every file: each program started here pays a dozen traced library lookups
|
||||
# under the game's search path before it does anything.
|
||||
local cm_rows=() cm_files=() row h p
|
||||
local -A cm_sums=()
|
||||
while IFS=$'\\t' read -r t want comp rel sum src; do
|
||||
[ "$t" = "$cm_tool" ] && [ "$want" = "$cm_build" ] || continue
|
||||
while IFS=$'\\t' read -r scope t want comp rel sum src; do
|
||||
[ -n "$scope" ] || continue
|
||||
# The selected system PowerVR runtime supplies DXVK at launch. Keep saved selections
|
||||
# for a later manual-driver session without rewriting this Proton's bundled files now.
|
||||
[ "$comp" = dxvk ] && [ -n "${DROIDDECK_POWERVR_RUNTIME:-}" ] && continue
|
||||
cm_rows+=("$comp"$'\\t'"$rel"$'\\t'"$sum"$'\\t'"$src")
|
||||
[ -f "$base/$rel" ] && cm_files+=("$base/$rel")
|
||||
done < "$cm_list"
|
||||
[ "$src" != "-" ] && [ -f "$base/$rel" ] && cm_files+=("$base/$rel")
|
||||
done <<< "$cm_selected"
|
||||
if [ ${#cm_files[@]} -gt 0 ]; then
|
||||
while read -r h p; do cm_sums["$p"]=$h; done < <(sha256sum -- "${cm_files[@]}" 2>/dev/null)
|
||||
fi
|
||||
@@ -171,6 +211,10 @@ bl_components() {
|
||||
IFS=$'\\t' read -r comp rel sum src <<< "$row"
|
||||
cm_checked=$((cm_checked + 1))
|
||||
f="$base/$rel"
|
||||
if [ "$src" = "-" ]; then
|
||||
if [ -e "$f" ]; then rm -f "$f" && cm_fixed=$((cm_fixed + 1)); fi
|
||||
continue
|
||||
fi
|
||||
if [ -f "$f" ] && [ "${cm_sums[$f]:-}" = "$sum" ]; then continue; fi
|
||||
if [ ! -f "$src" ]; then
|
||||
echo "droiddeck-proton: components: $comp source missing ($src), left as it is" >&2
|
||||
@@ -985,16 +1029,30 @@ def app_order(app):
|
||||
return (len(app), app)
|
||||
|
||||
|
||||
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=()):
|
||||
DEFERRED_GAME_TOOL = object()
|
||||
|
||||
|
||||
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=(), overrides=None):
|
||||
runnable = {n.lower() for n in runnable}
|
||||
installed = set(installed)
|
||||
picks = set(picks)
|
||||
native = native or {}
|
||||
overrides = overrides or {}
|
||||
changes, kept = {}, {}
|
||||
if current.get("0", "") != default:
|
||||
changes["0"] = default
|
||||
for app in sorted((set(current) | installed | picks | set(auto)) - {"0"}, key=app_order):
|
||||
for app in sorted((set(current) | installed | picks | set(auto) | set(overrides)) - {"0"}, key=app_order):
|
||||
name = current.get(app, "")
|
||||
if app in overrides:
|
||||
target = overrides[app]
|
||||
if target is DEFERRED_GAME_TOOL:
|
||||
continue
|
||||
target = target or default
|
||||
if name != target:
|
||||
changes[app] = target
|
||||
if overrides[app] is None:
|
||||
kept[app] = target
|
||||
continue
|
||||
mine = auto.get(app)
|
||||
target = native.get(app, default)
|
||||
stale = unrunnable(name, runnable) or (app in native and linux_runtime_tool(name))
|
||||
@@ -1053,6 +1111,34 @@ def requested_tool(request, catalog):
|
||||
return None
|
||||
|
||||
|
||||
def game_requests(directory=None):
|
||||
value = read_json(state_path("games.json", directory))
|
||||
if value.get("version") != 1 or not isinstance(value.get("games"), dict):
|
||||
return {}
|
||||
return value["games"]
|
||||
|
||||
|
||||
def requested_games(requests, catalog, runnable=None):
|
||||
"""App id -> requested tool, None for inherit, or DEFERRED_GAME_TOOL while unavailable."""
|
||||
runnable = None if runnable is None else set(runnable)
|
||||
resolved = {}
|
||||
for app, request in requests.items():
|
||||
if not isinstance(app, str) or not re.fullmatch(r"[1-9][0-9]*", app) or int(app) > 0xFFFFFFFF:
|
||||
continue
|
||||
if request is None:
|
||||
resolved[app] = None
|
||||
continue
|
||||
if (not isinstance(request, dict) or not isinstance(request.get("dir"), str) or
|
||||
not request["dir"] or not isinstance(request.get("valve"), bool)):
|
||||
continue
|
||||
tool = requested_tool(request, catalog)
|
||||
if tool is None or runnable is not None and tool not in runnable:
|
||||
resolved[app] = DEFERRED_GAME_TOOL
|
||||
else:
|
||||
resolved[app] = tool
|
||||
return resolved
|
||||
|
||||
|
||||
def now_ms():
|
||||
import time
|
||||
return int(time.time() * 1000)
|
||||
@@ -1174,7 +1260,9 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
|
||||
else:
|
||||
default = state.get("default") if state.get("default") in names else TOOL
|
||||
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
|
||||
changes, auto = plan_mapping(current, apps, names, default, followers(state, current), native_targets(steam_root, apps), picks)
|
||||
overrides = requested_games(game_requests(directory), catalog)
|
||||
changes, auto = plan_mapping(
|
||||
current, apps, names, default, followers(state, current), native_targets(steam_root, apps), picks, overrides)
|
||||
for app, tool in changes.items():
|
||||
set_mapping(tokens, mapping, app, tool)
|
||||
text = serialize(tokens)
|
||||
|
||||
@@ -208,6 +208,22 @@ class AgentTest(unittest.TestCase):
|
||||
missing = self.ask({"kind": "cdp", "expression": "1", "target": "Nope"})
|
||||
self.assertEqual("NO_TARGET", missing["error"]["code"])
|
||||
|
||||
def test_steam_selection(self):
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": "3180310"}) as evaluate:
|
||||
answer = self.ask({"kind": "steam-selection"})
|
||||
self.assertEqual(3180310, answer["appId"])
|
||||
self.assertIn("document.activeElement", evaluate.call_args.args[1])
|
||||
self.assertEqual("Steam Big Picture Mode", evaluate.call_args.kwargs["target"])
|
||||
|
||||
def test_steam_selection_allows_no_highlight(self):
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": None}):
|
||||
self.assertIsNone(self.ask({"kind": "steam-selection"})["appId"])
|
||||
|
||||
def test_steam_selection_rejects_invalid_app_id(self):
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": "4294967296"}):
|
||||
answer = self.ask({"kind": "steam-selection"})
|
||||
self.assertEqual("INVALID_SELECTION", answer["error"]["code"])
|
||||
|
||||
def test_cdp_exception(self):
|
||||
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
|
||||
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
|
||||
|
||||
@@ -746,6 +746,16 @@ class SelectTest(SyncTestCase):
|
||||
self.assertFalse((root / "wanted.tsv").exists())
|
||||
self.assertFalse((root / "dist").exists())
|
||||
|
||||
def test_droiddeck_proton_has_esync_built_in(self):
|
||||
root = self.store()
|
||||
tool = make_tool(self.tools, "DroidDeck-Proton 11-7.5", "1791000000 DroidDeck-Proton-11-7.5", builtin=True, ge=True, fsync=True)
|
||||
command, env, said = self.select(tool, self.env())
|
||||
self.assertEqual(command[0], str(tool / "proton"))
|
||||
self.assertNotIn("BL_SYNC_PACK", env)
|
||||
self.assertEqual(said, "droiddeck-esync: DroidDeck-Proton 11-7.5 has esync built in\n")
|
||||
self.assertFalse((root / "wanted.tsv").exists())
|
||||
self.assertFalse((root / "dist").exists())
|
||||
|
||||
def test_wanted_rows_are_deduplicated(self):
|
||||
root = self.store()
|
||||
tool = make_tool(self.tools, "GE-Proton11-7", GE_LINE, ge=True)
|
||||
@@ -906,6 +916,15 @@ class ReconcileTest(SyncTestCase):
|
||||
self.assertTrue(self.dist_of("ge-GE-Proton11-7-r1", ge).is_dir())
|
||||
self.assertIn("ge-GE-Proton11-7-r1", (root / "tools.tsv").read_text())
|
||||
|
||||
def test_droiddeck_proton_is_scanned_but_our_own_tools_are_not(self):
|
||||
steam = self.tmp / "steam"
|
||||
tools = steam / "compatibilitytools.d"
|
||||
ours = make_tool(tools, "DroidDeck-Proton 11-7.5", "1791000000 DroidDeck-Proton-11-7.5", salt=b"dd", builtin=True, ge=True)
|
||||
make_tool(tools, "droiddeck-proton-arm64", salt=b"own")
|
||||
make_tool(tools, "droiddeck-proton-11-arm64", salt=b"own11")
|
||||
with mock.patch.dict(GLOBALS, {"SD_LIBRARY": str(self.tmp / "sd")}):
|
||||
self.assertEqual(SYNC["find_tools"](str(steam)), [str(ours)])
|
||||
|
||||
def test_steam_compatibility_reports_sync(self):
|
||||
steam = self.tmp / "steam"
|
||||
make_tool(steam / "steamapps/common", "Proton Experimental (ARM64)")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
@@ -158,6 +159,121 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(env["REMOVE"], "inherited")
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared")
|
||||
|
||||
def test_component_profiles_override_general_and_restore_it_for_the_next_game(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
home = root / "home"
|
||||
component_dir = home / ".local/share/droiddeck-components"
|
||||
base = root / "proton"
|
||||
target = base / "files/lib/wine/dxvk/aarch64-windows/d3d11.dll"
|
||||
leftover = target.with_name("d3d8.dll")
|
||||
component_dir.mkdir(parents=True)
|
||||
target.parent.mkdir(parents=True)
|
||||
(base / "version").write_text("1 build-1\n")
|
||||
general = root / "general.dll"
|
||||
game = root / "game.dll"
|
||||
general.write_text("general")
|
||||
game.write_text("game")
|
||||
target.write_text("old")
|
||||
leftover.write_text("old")
|
||||
digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
(component_dir / "desired.tsv").write_text(
|
||||
"*\tproton\tbuild-1\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d11.dll\t%s\t%s\n"
|
||||
"42\tproton\tbuild-1\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d11.dll\t%s\t%s\n"
|
||||
"42\tproton\tbuild-1\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d8.dll\t-\t-\n"
|
||||
% (digest(general), general, digest(game), game)
|
||||
)
|
||||
script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n'
|
||||
env = dict(os.environ, HOME=str(home), STEAM_COMPAT_DATA_PATH="/steam/compatdata/42")
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
self.assertEqual(target.read_text(), "game")
|
||||
self.assertFalse(leftover.exists())
|
||||
|
||||
env["STEAM_COMPAT_DATA_PATH"] = "/steam/compatdata/43"
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
self.assertEqual(target.read_text(), "general")
|
||||
|
||||
def test_system_powervr_preserves_dxvk_profiles_without_applying_them(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
home = root / "home"
|
||||
component_dir = home / ".local/share/droiddeck-components"
|
||||
component_dir.mkdir(parents=True)
|
||||
base = root / "proton"
|
||||
paths = {
|
||||
"dxvk": "files/lib/wine/dxvk/aarch64-windows/d3d11.dll",
|
||||
"fex": "files/lib/wine/aarch64-windows/libarm64ecfex.dll",
|
||||
"vkd3d": "files/lib/wine/vkd3d-proton/aarch64-windows/d3d12.dll",
|
||||
}
|
||||
rows = []
|
||||
for comp, rel in paths.items():
|
||||
target = base / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text("bundled " + comp)
|
||||
for scope in ("*", "42"):
|
||||
source = root / (comp + ("-general" if scope == "*" else "-game"))
|
||||
source.write_text(source.name)
|
||||
rows.append("%s\tproton\tbuild-1\t%s\t%s\t%s\t%s\n" % (
|
||||
scope, comp, rel, hashlib.sha256(source.read_bytes()).hexdigest(), source,
|
||||
))
|
||||
leftover = (base / paths["dxvk"]).with_name("d3d8.dll")
|
||||
leftover.write_text("bundled d3d8")
|
||||
rows.append("42\tproton\tbuild-1\tdxvk\t%s\t-\t-\n" % leftover.relative_to(base))
|
||||
(base / "version").write_text("1 build-1\n")
|
||||
selection = component_dir / "desired.tsv"
|
||||
selection.write_text("".join(rows))
|
||||
saved = selection.read_bytes()
|
||||
script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n'
|
||||
env = dict(os.environ, HOME=str(home), STEAM_COMPAT_DATA_PATH="/steam/compatdata/42",
|
||||
DROIDDECK_POWERVR_RUNTIME="/system_vulkan/runtime")
|
||||
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
|
||||
self.assertEqual((base / paths["dxvk"]).read_text(), "bundled dxvk")
|
||||
self.assertEqual(leftover.read_text(), "bundled d3d8")
|
||||
for comp in ("fex", "vkd3d"):
|
||||
self.assertEqual((base / paths[comp]).read_text(), comp + "-game")
|
||||
self.assertEqual(selection.read_bytes(), saved)
|
||||
|
||||
# A subsequent manual-driver session still applies the saved per-game DXVK choice.
|
||||
env.pop("DROIDDECK_POWERVR_RUNTIME")
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True)
|
||||
self.assertEqual((base / paths["dxvk"]).read_text(), "dxvk-game")
|
||||
self.assertFalse(leftover.exists())
|
||||
self.assertEqual(selection.read_bytes(), saved)
|
||||
|
||||
def test_component_scope_matches_environment_scope_for_shortcut_ids(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
component_dir = root / ".local/share/droiddeck-components"
|
||||
base = root / "proton"
|
||||
target = base / "files/lib/wine/dxvk/aarch64-windows/d3d11.dll"
|
||||
component_dir.mkdir(parents=True)
|
||||
target.parent.mkdir(parents=True)
|
||||
(base / "version").write_text("1 build-1\n")
|
||||
rows = []
|
||||
for scope in ("*", "42", "4294967295", "2147483648"):
|
||||
source = root / ("default" if scope == "*" else scope)
|
||||
source.write_text(scope)
|
||||
rows.append("%s\tproton\tbuild-1\tdxvk\t%s\t%s\t%s\n" % (
|
||||
scope, target.relative_to(base),
|
||||
hashlib.sha256(source.read_bytes()).hexdigest(), source,
|
||||
))
|
||||
(component_dir / "desired.tsv").write_text("".join(rows))
|
||||
script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n'
|
||||
for value in (
|
||||
"42", "00042", "43", "-1", "-0001", "4294967295", "-2147483648",
|
||||
"2147483648", "-1///", "0", "-0", "000", "-2147483649", "4294967296",
|
||||
"999999999999999999999999999", "not-an-id", "1+1", "",
|
||||
):
|
||||
with self.subTest(prefix=value):
|
||||
env = dict(os.environ, HOME=str(root), STEAM_COMPAT_DATA_PATH="/steam/compatdata/" + value)
|
||||
target.write_text("untouched")
|
||||
subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True, capture_output=True)
|
||||
scope = MODULE["game_id"](env)
|
||||
expected = "untouched" if scope is None else scope if scope in {"42", "4294967295", "2147483648"} else "*"
|
||||
self.assertEqual(target.read_text(), expected)
|
||||
|
||||
def test_engine_fixes_follow_the_games_files(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
game = Path(tmp) / "Godot Game"
|
||||
@@ -215,6 +331,22 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
MODULE["apply_config"]({}, {**config, "dxvkConfig": bad}, "42")
|
||||
|
||||
def test_game_texture_filtering_overrides_default_without_leaking(self):
|
||||
default = "d3d9.samplerAnisotropy = 16"
|
||||
game = "d3d9.samplerAnisotropy = 4"
|
||||
config = {
|
||||
"version": 1,
|
||||
"shared": {},
|
||||
"games": {},
|
||||
"dxvkConfig": default,
|
||||
"dxvkConfigGames": {"42": game, "43": ""},
|
||||
}
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "42")["DXVK_CONFIG"], game)
|
||||
self.assertNotIn("DXVK_CONFIG", MODULE["apply_config"]({}, config, "43"))
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "44")["DXVK_CONFIG"], default)
|
||||
with self.assertRaises(ValueError):
|
||||
MODULE["apply_config"]({}, {**config, "dxvkConfigGames": []}, "42")
|
||||
|
||||
def test_game_ids_and_probes(self):
|
||||
for prefix in ("", "/compatdata/0", "/compatdata/0-123", "/compatdata/nope", "/compatdata/4294967296"):
|
||||
self.assertIsNone(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": prefix}))
|
||||
@@ -363,6 +495,40 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertIn('"$here/proton"', (extra / COMPAT["EXTRA_WRAPPER"]).read_text())
|
||||
self.assertIn("GE-Proton11-7", [entry["name"] for entry in COMPAT["tool_catalog"](str(home), None)])
|
||||
|
||||
def test_droiddeck_proton_is_adopted_and_labelled_like_any_other_extra(self):
|
||||
# Its folder has a space ("DroidDeck-Proton 11-7.5") and its internal name starts with
|
||||
# "DroidDeck-Proton-", which lower-cases to our own tools' prefix: neither may matter.
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
(home / "label").write_text("Compatible\n")
|
||||
COMPAT["display_name"].__globals__["LABEL_FILE"] = str(home / "label")
|
||||
tools = home / "compatibilitytools.d"
|
||||
extra = tools / "DroidDeck-Proton 11-7.5"
|
||||
extra.mkdir(parents=True)
|
||||
(extra / "proton").write_text("")
|
||||
(extra / "toolmanifest.vdf").write_text('"manifest" { "version" "2" "commandline" "/proton %verb%" "require_tool_appid" "4185400" }')
|
||||
(extra / "compatibilitytool.vdf").write_text(
|
||||
'"compatibilitytools" { "compat_tools" { "DroidDeck-Proton-11-7.5" { "install_path" "." '
|
||||
'"display_name" "DroidDeck-Proton 11-7.5" "from_oslist" "windows" "to_oslist" "linux" } } }')
|
||||
COMPAT["build_tool"](str(tools / COMPAT["TOOL"]), None)
|
||||
protect = COMPAT["adopt_extras"](str(tools))
|
||||
self.assertEqual(protect, {"DroidDeck-Proton-11-7.5": "DroidDeck-Proton 11-7.5"})
|
||||
compat = (extra / "compatibilitytool.vdf").read_text()
|
||||
self.assertIn('"DroidDeck-Proton-11-7.5"', compat)
|
||||
self.assertIn('"display_name" "DroidDeck-Proton 11-7.5 (Compatible)"', compat)
|
||||
self.assertNotIn("require_tool_appid", (extra / "toolmanifest.vdf").read_text())
|
||||
self.assertIn('"$here/proton"', (extra / COMPAT["EXTRA_WRAPPER"]).read_text())
|
||||
catalog = COMPAT["tool_catalog"](str(home), None)
|
||||
self.assertIn({"name": "DroidDeck-Proton-11-7.5", "display": "DroidDeck-Proton 11-7.5 (Compatible)",
|
||||
"dir": "DroidDeck-Proton 11-7.5", "valve": False}, catalog)
|
||||
config = home / "config.vdf"
|
||||
config.write_text(config_text([("0", COMPAT["TOOL"]), ("42", "DroidDeck-Proton-11-7.5")]))
|
||||
COMPAT["register_default"](str(config), ["42", "43"], protect=protect)
|
||||
self.assertEqual(mapping_of(config.read_text()), {"0": COMPAT["TOOL"], "42": "DroidDeck-Proton-11-7.5", "43": COMPAT["TOOL"]})
|
||||
# Once removed it is no longer runnable, and its games go back to the default.
|
||||
changes, _ = COMPAT["plan_mapping"]({"0": COMPAT["TOOL"], "42": "DroidDeck-Proton-11-7.5"}, ["42"], [COMPAT["TOOL"]], COMPAT["TOOL"], {})
|
||||
self.assertEqual(changes, {"42": COMPAT["TOOL"]})
|
||||
|
||||
def test_both_proton_wrappers_call_environment_launcher(self):
|
||||
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
|
||||
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
|
||||
@@ -425,6 +591,57 @@ class ProtonDefaultTest(unittest.TestCase):
|
||||
changes, auto = self.plan({"0": self.TOOL}, [], self.TOOL, {"10": self.TOOL})
|
||||
self.assertEqual((changes, auto), ({}, {}))
|
||||
|
||||
def test_per_game_proton_override_and_inherit_follow_steam_mappings(self):
|
||||
current = {"0": self.TOOL, "10": self.TOOL, "11": "GE-Proton11-7", "12": self.TOOL}
|
||||
overrides = {"10": "GE-Proton11-7", "11": None}
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
current, ["10", "11", "12"], self.NAMES, COMPAT["TOOL_11"],
|
||||
{"10": self.TOOL, "12": self.TOOL}, overrides=overrides)
|
||||
self.assertEqual(changes, {"0": COMPAT["TOOL_11"], "10": "GE-Proton11-7", "11": COMPAT["TOOL_11"], "12": COMPAT["TOOL_11"]})
|
||||
self.assertEqual(auto, {"11": COMPAT["TOOL_11"], "12": COMPAT["TOOL_11"]})
|
||||
|
||||
def test_per_game_requests_resolve_identity_and_defer_a_new_live_tool(self):
|
||||
requests = {
|
||||
"10": {"valve": False, "dir": "GE-Proton11-7"},
|
||||
"11": None,
|
||||
"12": {"valve": True, "dir": "Proton 11.0 (ARM64)"},
|
||||
"0": None,
|
||||
}
|
||||
self.assertEqual(
|
||||
COMPAT["requested_games"](requests, self.CATALOG),
|
||||
{"10": "GE-Proton11-7", "11": None, "12": COMPAT["TOOL_11"]},
|
||||
)
|
||||
self.assertEqual(
|
||||
COMPAT["requested_games"](requests, self.CATALOG, [self.TOOL, COMPAT["TOOL_11"]]),
|
||||
{"10": COMPAT["DEFERRED_GAME_TOOL"], "11": None, "12": COMPAT["TOOL_11"]},
|
||||
)
|
||||
|
||||
def test_missing_per_game_proton_is_preserved_during_default_registration(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = Path(tmp) / "config.vdf"
|
||||
config.write_text(config_text([
|
||||
("0", self.TOOL),
|
||||
("10", "GE-Proton9-1"),
|
||||
("11", self.TOOL),
|
||||
]))
|
||||
(Path(tmp) / "games.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"games": {
|
||||
"10": {"valve": False, "dir": "GE-Proton9-1"},
|
||||
},
|
||||
}))
|
||||
|
||||
COMPAT["register_default"](
|
||||
str(config), ["10", "11"], default=COMPAT["TOOL_11"],
|
||||
catalog=self.CATALOG, directory=tmp,
|
||||
)
|
||||
|
||||
self.assertEqual(mapping_of(config.read_text()), {
|
||||
"0": COMPAT["TOOL_11"],
|
||||
"10": "GE-Proton9-1",
|
||||
"11": COMPAT["TOOL_11"],
|
||||
})
|
||||
|
||||
def test_the_last_side_to_change_wins(self):
|
||||
state = {"default": self.TOOL, "applied": 5}
|
||||
default, state = COMPAT["choose_default"]("GE-Proton11-7", state, {"seq": 5, "dir": "Proton 11.0 (ARM64)", "valve": True}, self.CATALOG, now=100)
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
MODULE = runpy.run_path(str(BIN / 'droiddeck-launcher-cores'))
|
||||
Holder = MODULE['Holder']
|
||||
Governor = MODULE['Governor']
|
||||
NICE = MODULE['NICE']
|
||||
|
||||
HELPER = 'C:\\Program Files\\Rockstar Games\\Social Club\\SocialClubHelper.exe'
|
||||
LAUNCHER = 'C:\\Program Files\\Rockstar Games\\Launcher\\Launcher.exe'
|
||||
GAME = 'S:\\steamapps\\common\\Red Dead Redemption 2\\RDR2.exe'
|
||||
ALL = set(range(8))
|
||||
|
||||
|
||||
class FakeCores:
|
||||
"""Per-thread masks and priorities, with every change recorded."""
|
||||
|
||||
def __init__(self):
|
||||
self.state = {}
|
||||
self.calls = []
|
||||
|
||||
def own(self):
|
||||
return set(ALL)
|
||||
|
||||
def get(self, tid):
|
||||
if tid not in self.state:
|
||||
raise ProcessLookupError(tid)
|
||||
return self.state[tid]
|
||||
|
||||
def set(self, tid, cpus, nice):
|
||||
if tid not in self.state:
|
||||
raise ProcessLookupError(tid)
|
||||
self.calls.append((tid, set(cpus), nice))
|
||||
self.state[tid] = (set(cpus), nice)
|
||||
|
||||
|
||||
class LauncherCoresTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.proc = self.root / 'proc'
|
||||
self.proc.mkdir()
|
||||
cpufreq = self.root / 'cpu'
|
||||
for cpu in ALL: # 0-5 one cluster, 6-7 the fast one
|
||||
(cpufreq / f'cpu{cpu}/cpufreq').mkdir(parents=True)
|
||||
(cpufreq / f'cpu{cpu}/cpufreq/cpuinfo_max_freq').write_text('3532800\n' if cpu < 6 else '4320000\n')
|
||||
self.cores = FakeCores()
|
||||
self.holder = Holder(self.proc, cpufreq, self.cores)
|
||||
self.focus = self.root / 'focus.json'
|
||||
self.now = 0.0
|
||||
self.governor = Governor(self.focus, self.holder, clock=lambda: self.now)
|
||||
|
||||
def process(self, pid, argv0, threads=(), cpus=ALL, nice=0):
|
||||
directory = self.proc / str(pid)
|
||||
(directory / 'task').mkdir(parents=True)
|
||||
(directory / 'cmdline').write_bytes(argv0.encode() + b'\0--type=renderer\0')
|
||||
for tid in (pid, *threads):
|
||||
self.thread(pid, tid, cpus, nice)
|
||||
|
||||
def thread(self, pid, tid, cpus=ALL, nice=0):
|
||||
(self.proc / str(pid) / 'task' / str(tid)).mkdir()
|
||||
self.cores.state[tid] = (set(cpus), nice)
|
||||
|
||||
def end(self, pid):
|
||||
for tid in os.listdir(self.proc / str(pid) / 'task'):
|
||||
self.cores.state.pop(int(tid), None)
|
||||
(self.proc / str(pid) / 'task' / tid).rmdir()
|
||||
(self.proc / str(pid) / 'task').rmdir()
|
||||
(self.proc / str(pid) / 'cmdline').unlink()
|
||||
(self.proc / str(pid)).rmdir()
|
||||
|
||||
def focus_on(self, pid, app=1174180):
|
||||
stamp = getattr(self, 'stamp', 1_000_000_000) + 1_000_000_000
|
||||
self.stamp = stamp
|
||||
self.focus.write_text(json.dumps({
|
||||
'focusedApp': app, 'focusedWindow': 0x200001,
|
||||
'focusableWindows': [{'window': 0x100001, 'appId': 769, 'pid': 9},
|
||||
{'window': 0x200001, 'appId': app, 'pid': pid}]}))
|
||||
os.utime(self.focus, ns=(stamp, stamp))
|
||||
|
||||
def held(self, tid):
|
||||
return self.cores.state[tid] == ({5}, NICE)
|
||||
|
||||
def test_helpers_held_on_the_slow_clusters_last_core_while_the_game_has_focus(self):
|
||||
self.process(100, LAUNCHER, (101,))
|
||||
self.process(200, HELPER, (201, 202), nice=-2)
|
||||
self.process(300, HELPER, (301,))
|
||||
self.process(400, GAME, (401,))
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
for tid in (200, 201, 202, 300, 301):
|
||||
self.assertTrue(self.held(tid), tid)
|
||||
for tid in (100, 101, 400, 401):
|
||||
self.assertEqual((ALL, 0), self.cores.state[tid])
|
||||
|
||||
def test_launcher_focus_gives_each_thread_its_own_mask_and_priority_back(self):
|
||||
self.process(100, LAUNCHER)
|
||||
self.process(200, HELPER, (201,), cpus={0, 1, 2, 3}, nice=-2)
|
||||
self.cores.state[201] = ({6, 7}, 4)
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.assertTrue(self.held(201))
|
||||
self.focus_on(100)
|
||||
self.governor.tick()
|
||||
self.assertEqual(({0, 1, 2, 3}, -2), self.cores.state[200])
|
||||
self.assertEqual(({6, 7}, 4), self.cores.state[201])
|
||||
self.assertEqual({}, self.holder.held)
|
||||
|
||||
def test_nothing_is_touched_before_a_game_has_focus(self):
|
||||
self.process(100, LAUNCHER)
|
||||
self.process(200, HELPER)
|
||||
self.process(9, '/root/.local/share/Steam/steamrtarm64/steam')
|
||||
self.governor.tick() # no focus file yet
|
||||
self.focus_on(9, app=769)
|
||||
self.governor.tick()
|
||||
self.focus_on(100)
|
||||
self.governor.tick()
|
||||
self.assertEqual([], self.cores.calls)
|
||||
|
||||
def test_a_launcher_left_after_its_game_stays_held_behind_the_client(self):
|
||||
self.process(200, HELPER)
|
||||
self.process(400, GAME)
|
||||
self.process(9, '/root/.local/share/Steam/steamrtarm64/steam')
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.end(400)
|
||||
self.focus_on(9, app=769)
|
||||
self.governor.tick()
|
||||
self.assertTrue(self.held(200))
|
||||
|
||||
def test_a_thread_inheriting_the_hold_is_released_to_what_its_process_had(self):
|
||||
self.process(200, HELPER, cpus={0, 1, 2, 3, 4, 5}, nice=1)
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
# A new thread, and a new helper process the held one started: both born held.
|
||||
self.thread(200, 203, {5}, NICE)
|
||||
self.process(500, HELPER, (501,), cpus={5}, nice=NICE)
|
||||
self.now += 10
|
||||
self.governor.tick()
|
||||
self.focus_on(200)
|
||||
self.governor.tick()
|
||||
for tid in (200, 203, 500, 501):
|
||||
self.assertEqual(({0, 1, 2, 3, 4, 5}, 1), self.cores.state[tid], tid)
|
||||
|
||||
def test_a_held_thread_the_program_moves_back_is_held_again_on_the_next_look(self):
|
||||
self.process(200, HELPER, (201,))
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.cores.state[201] = (ALL, -5) # the program raised a thread's priority itself
|
||||
self.now += 5
|
||||
self.governor.tick()
|
||||
self.assertFalse(self.held(201)) # not looked at again before the rescan
|
||||
self.now += 5
|
||||
self.governor.tick()
|
||||
self.assertTrue(self.held(201))
|
||||
self.focus_on(200)
|
||||
self.governor.tick()
|
||||
self.assertEqual((ALL, 0), self.cores.state[201]) # its first state, not the program's
|
||||
|
||||
def test_a_steady_hold_is_not_rewritten(self):
|
||||
self.process(200, HELPER, (201,))
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
calls = len(self.cores.calls)
|
||||
for _ in range(5):
|
||||
self.now += 10
|
||||
self.governor.tick()
|
||||
self.assertEqual(calls, len(self.cores.calls))
|
||||
|
||||
def test_threads_that_end_are_skipped_and_ended_helpers_forgotten(self):
|
||||
self.process(200, HELPER, (201,))
|
||||
self.process(300, HELPER)
|
||||
self.process(400, GAME)
|
||||
del self.cores.state[201] # ended between the listing and the call
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.assertNotIn(201, self.holder.held[200])
|
||||
self.end(300)
|
||||
self.now += 10
|
||||
self.governor.tick()
|
||||
self.assertEqual([200], list(self.holder.held))
|
||||
|
||||
def test_stop_releases(self):
|
||||
self.process(200, HELPER)
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
with self.assertRaises(SystemExit):
|
||||
self.governor.stop()
|
||||
self.assertEqual((ALL, 0), self.cores.state[200])
|
||||
|
||||
def test_unreadable_focus_is_ignored(self):
|
||||
self.process(200, HELPER)
|
||||
self.focus.write_text('{"focusedApp": 1174')
|
||||
self.governor.tick()
|
||||
self.focus.write_text('[]')
|
||||
os.utime(self.focus, ns=(5, 5))
|
||||
self.governor.tick()
|
||||
self.assertEqual([], self.cores.calls)
|
||||
|
||||
def test_window_without_a_pid_is_left_alone(self):
|
||||
self.process(200, HELPER)
|
||||
self.focus.write_text(json.dumps({'focusedApp': 1174180, 'focusedWindow': 7, 'focusableWindows': []}))
|
||||
self.governor.tick()
|
||||
self.assertEqual([], self.cores.calls)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,107 @@
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
EXTRA = runpy.run_path(str(BIN / "droiddeck-proton-extra"))
|
||||
GLOBALS = EXTRA["pick_asset"].__globals__
|
||||
|
||||
|
||||
def asset(name):
|
||||
return {"name": name, "browser_download_url": "https://github.com/o/r/releases/download/t/" + name}
|
||||
|
||||
|
||||
def droiddeck_release(ver, prerelease=False, draft=False):
|
||||
stem = "DroidDeck-Proton-%s-aarch64" % ver
|
||||
return {"tag_name": "DroidDeck-Proton-" + ver, "prerelease": prerelease, "draft": draft,
|
||||
"assets": [asset(stem + ".build-info.json"), asset(stem + ".sha512sum"), asset(stem + ".tar.gz")]}
|
||||
|
||||
|
||||
class ProtonExtraTest(unittest.TestCase):
|
||||
def test_sources_and_their_arm64_assets(self):
|
||||
self.assertEqual(list(EXTRA["SOURCES"]), ["ge", "cachyos", "droiddeck"])
|
||||
repo, pattern = EXTRA["SOURCES"]["droiddeck"]
|
||||
self.assertEqual(repo, "The412Banner/DroidDeck-Proton")
|
||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
|
||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-8-aarch64.tar.xz"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.sha512sum"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.build-info.json"))
|
||||
|
||||
def test_the_newest_full_release_with_its_sha512_file(self):
|
||||
releases = [droiddeck_release("11-8", prerelease=True), droiddeck_release("11-7.9", draft=True), droiddeck_release("11-7.5")]
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: releases}):
|
||||
tag, url, sums = EXTRA["pick_asset"]("droiddeck")
|
||||
self.assertEqual(tag, "DroidDeck-Proton-11-7.5")
|
||||
self.assertTrue(url.endswith("/DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
|
||||
self.assertTrue(sums.endswith("/DroidDeck-Proton-11-7.5-aarch64.sha512sum"))
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: [droiddeck_release("11-8", prerelease=True)]}):
|
||||
self.assertEqual(EXTRA["pick_asset"]("droiddeck"), (None, None, None))
|
||||
|
||||
def test_a_tagged_release_is_fetched_by_its_tag(self):
|
||||
asked = []
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: asked.append(url) or droiddeck_release("11-7.5")}):
|
||||
tag, url, sums = EXTRA["release_asset"]("droiddeck", "DroidDeck-Proton-11-7.5")
|
||||
self.assertEqual(asked, ["https://api.github.com/repos/The412Banner/DroidDeck-Proton/releases/tags/DroidDeck-Proton-11-7.5"])
|
||||
self.assertTrue(url.endswith(".tar.gz") and sums.endswith(".sha512sum"))
|
||||
|
||||
def test_a_ge_style_sha512_file_verifies_the_download(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tarball = Path(tmp) / "DroidDeck-Proton-11-7.5-aarch64.tar.gz"
|
||||
tarball.write_bytes(b"tarball")
|
||||
line = "%s %s\n" % (hashlib.sha512(b"tarball").hexdigest(), tarball.name)
|
||||
|
||||
class Reply(io.BytesIO):
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
with mock.patch.object(GLOBALS["urllib"].request, "urlopen", lambda req, timeout: Reply(line.encode())), \
|
||||
contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
EXTRA["verify"](str(tarball), "https://example/sums")
|
||||
self.assertIn("checksum ok", said.getvalue())
|
||||
self.assertTrue(tarball.exists())
|
||||
bad = "%s %s\n" % ("0" * 128, tarball.name)
|
||||
with mock.patch.object(GLOBALS["urllib"].request, "urlopen", lambda req, timeout: Reply(bad.encode())), \
|
||||
contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit):
|
||||
EXTRA["verify"](str(tarball), "https://example/sums")
|
||||
self.assertFalse(tarball.exists())
|
||||
|
||||
def test_a_top_folder_with_a_space_is_installed_under_its_own_name(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "src" / "DroidDeck-Proton 11-7.5"
|
||||
(src / "files/bin").mkdir(parents=True)
|
||||
(src / "proton").write_text("#!/usr/bin/python3\n")
|
||||
(src / "toolmanifest.vdf").write_text('"manifest" { "commandline" "/proton %verb%" }')
|
||||
(src / "compatibilitytool.vdf").write_text(
|
||||
'"compatibilitytools" { "compat_tools" { "DroidDeck-Proton-11-7.5" { "install_path" "." '
|
||||
'"display_name" "DroidDeck-Proton 11-7.5" } } }')
|
||||
(src / "version").write_text("1791000000 DroidDeck-Proton-11-7.5\n")
|
||||
tarball = Path(tmp) / "DroidDeck-Proton-11-7.5-aarch64.tar.gz"
|
||||
with tarfile.open(tarball, "w:gz") as tar:
|
||||
tar.add(src, arcname=src.name)
|
||||
steam = Path(tmp) / "Steam"
|
||||
adopted = []
|
||||
real = subprocess.call
|
||||
# tar runs for real; steam-compatibility (the adoption step) is only recorded.
|
||||
fake = lambda args, **kw: adopted.append(args) or 0 if args[0] == "steam-compatibility" else real(args, **kw)
|
||||
with mock.patch.object(GLOBALS["subprocess"], "call", fake), contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
with mock.patch.object(GLOBALS["sys"], "argv", ["droiddeck-proton-extra", str(steam), str(tarball)]):
|
||||
EXTRA["main"]()
|
||||
tools = steam / "compatibilitytools.d"
|
||||
self.assertEqual(sorted(os.listdir(tools)), [".droiddeck-download", "DroidDeck-Proton 11-7.5"])
|
||||
self.assertTrue((tools / "DroidDeck-Proton 11-7.5" / "toolmanifest.vdf").is_file())
|
||||
self.assertEqual(adopted, [["steam-compatibility", str(steam)]])
|
||||
# The app reads the folder from this line, space and all.
|
||||
self.assertIn("droiddeck-proton-extra: installed DroidDeck-Proton 11-7.5\n", said.getvalue())
|
||||
self.assertEqual(EXTRA["installed"](str(tools)), ["DroidDeck-Proton 11-7.5"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -22,6 +22,30 @@ GAME_SCRIPT = r'''"InstallScript"
|
||||
}
|
||||
'''
|
||||
|
||||
# Red Dead Redemption 2's own script: Proton needs Khronos' vulkan-1.dll for it, which only the
|
||||
# Vulkan runtime installer puts in the prefix.
|
||||
VULKAN_SCRIPT = r'''"InstallScript"
|
||||
{
|
||||
"Run Process"
|
||||
{
|
||||
"Vulkan111080"
|
||||
{
|
||||
"HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\1174180"
|
||||
"process 1" "%INSTALLDIR%\\Redistributables\\VulkanRT-1.1.108.0-Installer.exe"
|
||||
"command 1" "/S"
|
||||
"NoCleanUp" "0"
|
||||
}
|
||||
"RockstarLauncher"
|
||||
{
|
||||
"HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Rockstar Games\\Steam\\Launcher"
|
||||
"process 1" "%INSTALLDIR%\\Redistributables\\Rockstar-Games-Launcher.exe"
|
||||
"command 1" "/s /t"
|
||||
"NoCleanUp" "0"
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class SeedRedistsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -91,6 +115,45 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.run_seed()
|
||||
self.assertEqual(int(self.reg.stat().st_mtime), 1_000_000_000)
|
||||
|
||||
def rdr2(self):
|
||||
path = self.steam / "steamapps/common/Red Dead Redemption 2/installscript.vdf"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(VULKAN_SCRIPT)
|
||||
(self.steam / "steamapps/appmanifest_1174180.acf").write_text('"AppState" { "installdir" "Red Dead Redemption 2" }')
|
||||
|
||||
def test_a_vulkan_runtime_installer_is_left_to_run(self):
|
||||
self.rdr2()
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
self.assertNotIn("Vulkan111080", reg)
|
||||
self.assertIn('"RockstarLauncher"=dword:00000001', reg)
|
||||
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
|
||||
def test_a_vulkan_marker_an_earlier_seeding_wrote_comes_out_once(self):
|
||||
self.rdr2()
|
||||
marker = "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180\tVulkan111080"
|
||||
self.reg.write_text(
|
||||
"WINE REGISTRY Version 2\n"
|
||||
"\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1791729070\n#time=1dd598d29161f72\n"
|
||||
'"Other"=dword:00000001\n"Vulkan111080"=dword:00000001\n'
|
||||
"\n[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1791729070\n"
|
||||
'"Vulkan111080"=dword:00000001\n'
|
||||
"\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\22380] 1791311644\n"
|
||||
'"Vulkan111080"=dword:00000001\n')
|
||||
(self.reg.parent / ".droiddeck-redists").write_text(marker + "\n")
|
||||
os.utime(self.reg, (1_000_000_000, 1_000_000_000))
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
self.assertEqual(reg.count('"Vulkan111080"'), 1, "only the other app's value stays")
|
||||
self.assertIn('"Other"=dword:00000001', reg)
|
||||
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
self.assertEqual(int(self.reg.stat().st_mtime), 1_000_000_000)
|
||||
# The client writes the marker itself once the installer has run; that one is left alone.
|
||||
with self.reg.open("a") as out:
|
||||
out.write('\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1791730000\n"Vulkan111080"=dword:00000001\n')
|
||||
self.run_seed()
|
||||
self.assertEqual(self.reg.read_text().count('"Vulkan111080"'), 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,95 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
STEAM = ["mangohud.Ab3dE6gH", ".com.valvesoftware.Steam.x1Y2z3/", "steam_chrome_shmem_uid10480_0", "steamADfAnd/"]
|
||||
CHROMIUM = ["scoped_dir3yu9Xt/SingletonSocket"]
|
||||
APPIMAGE = ["droiddeck-appimage.19PoOD"]
|
||||
BUS = ["dbus-1zWfOP1IaR="] # = a socket
|
||||
KDE = ["plasma-csd-generator.BVWIWA/"]
|
||||
STALE = STEAM + CHROMIUM + APPIMAGE + BUS + KDE
|
||||
KEPT = ["droiddeck-mangohud.conf", ".X11-unix/", "steamworks", "steamABCDEF/inside", "notes.txt",
|
||||
"mangohud.conf", ".wine-10480/", "dbus-1zWfOP1IaR.log", "dbus-notasocket",
|
||||
"plasma-csd-generator.CQGZSw/kept"]
|
||||
|
||||
|
||||
def sweep_function(tmp):
|
||||
match = re.search(r"^clear_stale_tmp\(\) \{\n.*?^\}\n", SESSION.read_text(), re.M | re.S)
|
||||
return match.group(0).replace("find /tmp ", "find %s " % tmp)
|
||||
|
||||
|
||||
class SessionTmpTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.root = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.root, True)
|
||||
self.tmp = self.root / "tmp"
|
||||
self.tmp.mkdir()
|
||||
for name in STALE + KEPT:
|
||||
path = self.tmp / name
|
||||
if name.endswith("/"):
|
||||
path.mkdir(parents=True)
|
||||
elif name.endswith("="):
|
||||
listener = socket.socket(socket.AF_UNIX)
|
||||
listener.bind(str(self.tmp / name[:-1]))
|
||||
listener.close()
|
||||
else:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("x")
|
||||
self.bin = self.root / "bin"
|
||||
self.bin.mkdir()
|
||||
|
||||
def sweep(self, running=""):
|
||||
pgrep = self.bin / "pgrep"
|
||||
pgrep.write_text("#!/bin/sh\nprintf '%s' '" + running + "'\n")
|
||||
pgrep.chmod(0o755)
|
||||
env = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]))
|
||||
return subprocess.run(["bash", "-c", sweep_function(self.tmp) + "clear_stale_tmp"], env=env,
|
||||
capture_output=True, text=True, timeout=30, check=True).stdout
|
||||
|
||||
def exists(self, name):
|
||||
return os.path.lexists(self.tmp / name.rstrip("=").split("/")[0])
|
||||
|
||||
def test_what_killed_sessions_left_goes_and_nothing_else(self):
|
||||
self.assertEqual("== /tmp: cleared 8 entries earlier sessions left\n", self.sweep())
|
||||
for name in STALE:
|
||||
self.assertFalse(self.exists(name), name)
|
||||
for name in KEPT:
|
||||
self.assertTrue((self.tmp / name).exists(), name)
|
||||
|
||||
def kept_while(self, running, owned):
|
||||
self.sweep(running)
|
||||
for name in STALE:
|
||||
self.assertEqual(name in owned, self.exists(name), name)
|
||||
|
||||
def test_a_running_client_keeps_its_own(self):
|
||||
self.kept_while("1234 /root/.local/share/Steam/steamrtarm64/steam -gamepadui\n", STEAM)
|
||||
|
||||
def test_a_running_chromium_keeps_its_singleton(self):
|
||||
self.kept_while("88 /opt/Heroic/heroic --type=renderer --enable-features=x\n", CHROMIUM)
|
||||
|
||||
def test_a_running_appimage_keeps_its_stamp(self):
|
||||
self.kept_while("77 /bin/bash /usr/local/bin/droiddeck-appimage-run /root/Apps/X.AppImage\n", APPIMAGE)
|
||||
|
||||
def test_a_running_session_bus_keeps_its_socket(self):
|
||||
self.kept_while("66 dbus-daemon --config-file=/usr/share/dbus-1/session.conf --nofork --session\n", BUS)
|
||||
|
||||
def test_the_system_bus_is_not_a_session_bus(self):
|
||||
self.kept_while("55 dbus-daemon --config-file=/usr/local/share/droiddeck/system-bus.conf --nofork\n", [])
|
||||
|
||||
def test_a_running_desktop_keeps_its_decorations(self):
|
||||
self.kept_while("44 kwin_wayland --xwayland\n", KDE)
|
||||
|
||||
def test_a_clean_tmp_says_nothing(self):
|
||||
self.sweep()
|
||||
self.assertEqual("", self.sweep())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -208,6 +208,33 @@ class ReconcileTest(unittest.TestCase):
|
||||
self.assertEqual((state["pending"], state.get("applied", 0)), (TOOL_11, 0))
|
||||
self.assertTrue(self.helper.request_waiting())
|
||||
|
||||
def test_per_game_customize_and_inherit_apply_live(self):
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL_11}, [TOOL, TOOL_11])
|
||||
(self.state / "games.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"games": {
|
||||
"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"},
|
||||
"11": None,
|
||||
},
|
||||
}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("10", TOOL_11), ("11", TOOL)])
|
||||
self.assertEqual(state["auto"], {"11": TOOL})
|
||||
|
||||
def test_missing_per_game_proton_stays_deferred_live(self):
|
||||
page = FakePage({"0": TOOL, "10": "GE-Proton9-1", "11": TOOL_11}, [TOOL, TOOL_11])
|
||||
(self.state / "games.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"games": {
|
||||
"10": {"valve": False, "dir": "GE-Proton9-1"},
|
||||
"11": None,
|
||||
},
|
||||
}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("11", TOOL)])
|
||||
self.assertEqual(page.mapping["10"], "GE-Proton9-1")
|
||||
self.assertEqual(state["auto"], {"11": TOOL})
|
||||
|
||||
def test_file_mode_defers_to_the_live_helper(self):
|
||||
(self.state / "live.pid").write_text("%d\n" % os.getpid())
|
||||
self.assertTrue(COMPAT["live_helper_running"]())
|
||||
|
||||
@@ -14,6 +14,8 @@ DISPLAY = MODULE['DISPLAY']
|
||||
seed_native_resolution = MODULE['seed_native_resolution']
|
||||
initialize_native_resolution = MODULE['initialize_native_resolution']
|
||||
NATIVE_RESOLUTION = MODULE['NATIVE_RESOLUTION']
|
||||
seed_no_screensaver_in_game = MODULE['seed_no_screensaver_in_game']
|
||||
initialize_screensaver = MODULE['initialize_screensaver']
|
||||
|
||||
|
||||
class SteamUiScaleTest(unittest.TestCase):
|
||||
@@ -151,3 +153,60 @@ class SteamNativeResolutionTest(unittest.TestCase):
|
||||
initialize_native_resolution(self.root)
|
||||
self.assertEqual(text, self.config.read_text())
|
||||
self.assertFalse(self.marker.exists())
|
||||
|
||||
|
||||
class SteamScreensaverTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.config = self.root / 'config/config.vdf'
|
||||
self.config.parent.mkdir()
|
||||
self.marker = self.config.with_name('droiddeck-screensaver-initialized')
|
||||
|
||||
def in_game(self, text):
|
||||
return parse(text).get('InstallConfigStore').get('Customization').get('Screensaver').get('WhileInGame')
|
||||
|
||||
def test_fresh_client_shows_no_screensaver_over_a_game(self):
|
||||
self.assertTrue(initialize_screensaver(self.root))
|
||||
self.assertEqual('0', self.in_game(self.config.read_text()))
|
||||
self.assertTrue(self.marker.exists())
|
||||
|
||||
def test_it_goes_beside_the_screensaver_the_user_picked(self):
|
||||
text = ('"InstallConfigStore"\n{\n\t"Customization"\n\t{\n\t\t"Screensaver"\n\t\t{\n'
|
||||
'\t\t\t"CurrentScreensaver"\t\t"steam-bouncinglogo"\n\t\t}\n\t}\n}\n')
|
||||
updated, changed = seed_no_screensaver_in_game(text)
|
||||
self.assertTrue(changed)
|
||||
screensaver = parse(updated).get('InstallConfigStore').get('Customization').get('Screensaver')
|
||||
self.assertEqual('steam-bouncinglogo', screensaver.get('CurrentScreensaver'))
|
||||
self.assertEqual('0', screensaver.get('WhileInGame'))
|
||||
self.assertIn('\t\t\t"WhileInGame"\t\t"0"\n\t\t}\n', updated)
|
||||
|
||||
def test_users_choice_is_kept(self):
|
||||
text = '"InstallConfigStore" { "Customization" { "Screensaver" { "WhileInGame" "1" } } }'
|
||||
self.assertEqual((text, False), seed_no_screensaver_in_game(text))
|
||||
|
||||
def test_turning_it_back_on_survives_restart(self):
|
||||
initialize_screensaver(self.root)
|
||||
text = '"InstallConfigStore" { "Customization" { } }'
|
||||
self.config.write_text(text)
|
||||
self.assertFalse(initialize_screensaver(self.root))
|
||||
self.assertEqual(text, self.config.read_text())
|
||||
|
||||
def test_every_seeded_setting_lands_in_one_valid_config(self):
|
||||
initialize(self.root, 2340, 1080)
|
||||
initialize_native_resolution(self.root)
|
||||
initialize_screensaver(self.root)
|
||||
store = parse(self.config.read_text()).get('InstallConfigStore')
|
||||
self.assertIsNotNone(store.get('UI').get('display').get(DISPLAY))
|
||||
self.assertEqual('1', store.get('Gamescope').get(NATIVE_RESOLUTION))
|
||||
self.assertEqual('0', store.get('Customization').get('Screensaver').get('WhileInGame'))
|
||||
|
||||
def test_invalid_config_is_never_rewritten_or_marked_initialized(self):
|
||||
for text in ('"InstallConfigStore" {', '"InstallConfigStore" { "Customization" "bad" }',
|
||||
'"InstallConfigStore" { "Customization" { "Screensaver" "bad" } }'):
|
||||
self.config.write_text(text)
|
||||
with self.assertRaises(ValueError):
|
||||
initialize_screensaver(self.root)
|
||||
self.assertEqual(text, self.config.read_text())
|
||||
self.assertFalse(self.marker.exists())
|
||||
Reference in new issue
Block a user