mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 22:36:00 +00:00
fix: resolve zram focus conflicts
This commit is contained in:
commit
36135327f5
327 files changed
+20986
-2696
No files matched your search
@@ -110,7 +110,8 @@
|
||||
],
|
||||
"outputs": [
|
||||
"app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so"
|
||||
]
|
||||
],
|
||||
"ndk": true
|
||||
},
|
||||
"audio": {
|
||||
"script": "tools/components/recipes/audio.sh",
|
||||
|
||||
+11
-1
@@ -10,7 +10,7 @@
|
||||
# 5. on a foldable cycles the device state (half-opened, and with --closed also closed) through
|
||||
# `cmd device_state`, then puts the original state back;
|
||||
# 6. reads the newest session folder of a debug build: first frame, last frame rate, the
|
||||
# memory page size and the last process exits.
|
||||
# memory page size, the proot that session ran, and the last process exits.
|
||||
#
|
||||
# Usage: tools/device-smoke.sh [--serial SERIAL] [--apk FILE] [--pkg PACKAGE]
|
||||
# [--no-density] [--no-size] [--no-fold] [--closed]
|
||||
@@ -279,6 +279,16 @@ else
|
||||
ev=$(sh_ run-as "$pkg" cat "files/logs/$dir/events.jsonl" 2>/dev/null)
|
||||
echo "$ev" | grep -q '"frame.first"' && ok "first frame was drawn" || note "no frame.first in $dir"
|
||||
echo "$ev" | grep -q '"session.failed"' && bad "session.failed: $(echo "$ev" | grep '"session.failed"' | tail -1 | cut -c1-160)"
|
||||
report=$(sh_ run-as "$pkg" cat "files/logs/$dir/device.txt" 2>/dev/null)
|
||||
proot_line=$(echo "$report" | grep 'proot binary' | head -1)
|
||||
case $proot_line in
|
||||
*"rootfs fallback"*|*"missing"*) bad "session proot is not the patched binary ($proot_line)" ;;
|
||||
*"apk"*|*"add-on pack"*) ok "patched proot ($proot_line)" ;;
|
||||
*) note "device report has no proot binary line (build from before the check)" ;;
|
||||
esac
|
||||
app_log=$(sh_ run-as "$pkg" cat "files/logs/$dir/app.log" 2>/dev/null)
|
||||
echo "$app_log" | grep -Fq 'proot: fast path on (' && ok "proot fast path was on" \
|
||||
|| note "proot fast path activation was not recorded ($(echo "$report" | grep 'proot fast path' | tr '\n' '; '))"
|
||||
fps=$(sh_ run-as "$pkg" cat "files/logs/$dir/app.log" 2>/dev/null | grep 'last 10 s:' | tail -1 | sed 's/.*last 10 s: //' | cut -c1-70)
|
||||
[ -n "$fps" ] && echo " last stats $fps"
|
||||
sh_ run-as "$pkg" cat "files/logs/$dir/device.txt" 2>/dev/null | grep -E 'Memory page size|^Kernel' | sed 's/^/ report /'
|
||||
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
repo_root=$1
|
||||
source_dir=$2
|
||||
: "${NDK:=${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT:-}}}}"
|
||||
: "${NDK:?set NDK to the Android NDK root}"
|
||||
case "$(uname -s)" in
|
||||
Darwin) host=darwin-x86_64 ;;
|
||||
Linux) host=linux-x86_64 ;;
|
||||
*) echo 'Unsupported NDK host' >&2; exit 1 ;;
|
||||
esac
|
||||
toolchain="$NDK/toolchains/llvm/prebuilt/$host/bin"
|
||||
patch -d "$source_dir" -p1 < "$repo_root/tools/directaudio/microphone-toggle.patch"
|
||||
"$toolchain/aarch64-linux-android28-clang" -O2 -Wl,-z,max-page-size=16384 \
|
||||
"$source_dir/directaudio-relay.c" -o "$repo_root/app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so" \
|
||||
-laaudio -llog -pthread
|
||||
"$toolchain/llvm-strip" --strip-unneeded "$repo_root/app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so"
|
||||
@@ -3,7 +3,7 @@ set -euo pipefail
|
||||
repo_root=$1
|
||||
sink_out=$2
|
||||
. "${repo_root}/tools/directaudio/release.env"
|
||||
for v in DIRECTAUDIO_REPO DIRECTAUDIO_TAG DIRECTAUDIO_WINE11_SHA256 DIRECTAUDIO_SYSTHREAD_SHA256 DIRECTAUDIO_RELAY_SHA256 DIRECTAUDIO_SINK_SHA256; do
|
||||
for v in DIRECTAUDIO_REPO DIRECTAUDIO_TAG DIRECTAUDIO_WINE11_SHA256 DIRECTAUDIO_SYSTHREAD_SHA256 DIRECTAUDIO_SINK_SHA256 DIRECTAUDIO_SOURCE_COMMIT DIRECTAUDIO_SOURCE_SHA256; do
|
||||
[[ -n "${!v:-}" && "${!v}" != TBD ]] || { echo "tools/directaudio/release.env: ${v} is not set" >&2; exit 1; }
|
||||
done
|
||||
work=$(mktemp -d)
|
||||
@@ -24,7 +24,15 @@ fetch() {
|
||||
}
|
||||
fetch directaudio-linux-wine11.zip "${DIRECTAUDIO_WINE11_SHA256}"
|
||||
fetch directaudio-linux-wine11-systhread.zip "${DIRECTAUDIO_SYSTHREAD_SHA256}"
|
||||
fetch directaudio-linux-relay.zip "${DIRECTAUDIO_RELAY_SHA256}"
|
||||
source_archive="${cache}/${DIRECTAUDIO_SOURCE_SHA256}-directaudio-source.tar.gz"
|
||||
if ! echo "${DIRECTAUDIO_SOURCE_SHA256} ${source_archive}" | sha256sum -c - >/dev/null 2>&1; then
|
||||
curl -fsSL --retry 3 -o "${work}/source.tar.gz" \
|
||||
"https://github.com/${DIRECTAUDIO_REPO}/archive/${DIRECTAUDIO_SOURCE_COMMIT}.tar.gz"
|
||||
echo "${DIRECTAUDIO_SOURCE_SHA256} ${work}/source.tar.gz" | sha256sum -c - >/dev/null
|
||||
mv "${work}/source.tar.gz" "${source_archive}"
|
||||
fi
|
||||
mkdir "${work}/source"
|
||||
tar -xzf "${source_archive}" --strip-components=1 -C "${work}/source"
|
||||
fetch directaudio-linux-sink.zip "${DIRECTAUDIO_SINK_SHA256}"
|
||||
|
||||
assets="${repo_root}/app/src/main/assets/directaudio"
|
||||
@@ -40,9 +48,8 @@ done
|
||||
grep -q '^abi wine11$' "${assets}/linux-wine11/version.txt"
|
||||
grep -q '^abi systhread$' "${assets}/linux-wine11-systhread/version.txt"
|
||||
|
||||
mkdir -p "${work}/relay" "${work}/sink" "${sink_out}" "${repo_root}/app/src/main/jniLibs/arm64-v8a"
|
||||
unzip -q "${work}/directaudio-linux-relay.zip" -d "${work}/relay"
|
||||
install -m755 "${work}/relay/libdirectaudiorelay.so" "${repo_root}/app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so"
|
||||
mkdir -p "${work}/sink" "${sink_out}" "${repo_root}/app/src/main/jniLibs/arm64-v8a"
|
||||
"${repo_root}/tools/directaudio/build-relay.sh" "${repo_root}" "${work}/source"
|
||||
unzip -q "${work}/directaudio-linux-sink.zip" -d "${work}/sink"
|
||||
install -m755 "${work}/sink/module-directaudio-native-sink.so" "${sink_out}/"
|
||||
echo "DirectAudio ${DIRECTAUDIO_TAG}: two driver sets, the relay helper and the client sink in place"
|
||||
@@ -0,0 +1,123 @@
|
||||
--- a/directaudio-relay.c
|
||||
+++ b/directaudio-relay.c
|
||||
@@ -70,6 +70,9 @@
|
||||
* session log captures it too. Event-level lines are always on: they fire a
|
||||
* handful of times per session and are what makes a field report actionable. */
|
||||
static int g_verbose;
|
||||
+static const char *g_mic_control;
|
||||
+static int g_mic_enabled = 1;
|
||||
+static pthread_mutex_t g_mic_operations = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static void rlog(const char *fmt, ...)
|
||||
{
|
||||
@@ -735,6 +738,9 @@
|
||||
(void)user;
|
||||
if (aq != __atomic_load_n(&g_mic.cq, __ATOMIC_SEQ_CST) && __atomic_load_n(&g_mic.cq, __ATOMIC_SEQ_CST))
|
||||
return AAUDIO_CALLBACK_RESULT_CONTINUE;
|
||||
+ if (!__atomic_load_n(&g_mic_enabled, __ATOMIC_ACQUIRE))
|
||||
+ memset(audioData, 0, numFrames * g_mic.in_channels *
|
||||
+ (g_mic.in_format == AAUDIO_FORMAT_PCM_I16 ? sizeof(int16_t) : sizeof(float)));
|
||||
__atomic_add_fetch(&g_mic.cb_count, 1, __ATOMIC_RELAXED);
|
||||
|
||||
pthread_mutex_lock(&g_clients_lock);
|
||||
@@ -832,13 +838,14 @@
|
||||
AAudioStream *aq = NULL;
|
||||
int start = 0, stop = 0;
|
||||
|
||||
+ pthread_mutex_lock(&g_mic_operations);
|
||||
pthread_mutex_lock(&g_mic.lock);
|
||||
g_mic.want += delta;
|
||||
if (g_mic.want < 0) g_mic.want = 0;
|
||||
if (g_mic.cq)
|
||||
{
|
||||
- if (g_mic.want > 0 && !g_mic.started) { g_mic.started = 1; start = 1; aq = g_mic.cq; }
|
||||
- if (g_mic.want == 0 && g_mic.started) { g_mic.started = 0; stop = 1; aq = g_mic.cq; }
|
||||
+ if (g_mic.want > 0 && __atomic_load_n(&g_mic_enabled, __ATOMIC_ACQUIRE) && !g_mic.started) { g_mic.started = 1; start = 1; aq = g_mic.cq; }
|
||||
+ if ((g_mic.want == 0 || !__atomic_load_n(&g_mic_enabled, __ATOMIC_ACQUIRE)) && g_mic.started) { g_mic.started = 0; stop = 1; aq = g_mic.cq; }
|
||||
}
|
||||
pthread_mutex_unlock(&g_mic.lock);
|
||||
|
||||
@@ -856,8 +863,23 @@
|
||||
else if (stop)
|
||||
{
|
||||
AAudioStream_requestStop(aq);
|
||||
- REVENT("mic stop (%s was the last consumer)", who);
|
||||
- }
|
||||
+ REVENT("mic stop (%s)", who);
|
||||
+ }
|
||||
+ pthread_mutex_unlock(&g_mic_operations);
|
||||
+}
|
||||
+
|
||||
+static void mic_control_update(void)
|
||||
+{
|
||||
+ FILE *f;
|
||||
+ int enabled;
|
||||
+ if (!g_mic_control) return;
|
||||
+ f = fopen(g_mic_control, "r");
|
||||
+ enabled = f && fgetc(f) == '1';
|
||||
+ if (f) fclose(f);
|
||||
+ if (enabled == __atomic_load_n(&g_mic_enabled, __ATOMIC_ACQUIRE)) return;
|
||||
+ __atomic_store_n(&g_mic_enabled, enabled, __ATOMIC_RELEASE);
|
||||
+ mic_want(0, "session toggle");
|
||||
+ REVENT("mic enabled=%d", enabled);
|
||||
}
|
||||
|
||||
static void *mic_reopen_thread(void *unused)
|
||||
@@ -870,8 +892,9 @@
|
||||
|
||||
__atomic_store_n(&g_mic.reopen_redo, 0, __ATOMIC_SEQ_CST);
|
||||
|
||||
+ pthread_mutex_lock(&g_mic_operations);
|
||||
pthread_mutex_lock(&g_mic.lock);
|
||||
- want_start = g_mic.want > 0;
|
||||
+ want_start = g_mic.want > 0 && __atomic_load_n(&g_mic_enabled, __ATOMIC_ACQUIRE);
|
||||
pthread_mutex_unlock(&g_mic.lock);
|
||||
|
||||
if (open_input(&neu) == AAUDIO_OK)
|
||||
@@ -902,6 +925,7 @@
|
||||
AAudioStream_close(old);
|
||||
}
|
||||
|
||||
+ pthread_mutex_unlock(&g_mic_operations);
|
||||
if (__atomic_load_n(&g_mic.reopen_redo, __ATOMIC_SEQ_CST)) { usleep(20000); continue; }
|
||||
__atomic_store_n(&g_mic.reopen_running, 0, __ATOMIC_SEQ_CST);
|
||||
if (!__atomic_load_n(&g_mic.reopen_redo, __ATOMIC_SEQ_CST)) break;
|
||||
@@ -1348,7 +1372,8 @@
|
||||
/* ---- housekeeping: watchdog tick + mailbox watch, once a second ------------- */
|
||||
static void *housekeeping_thread(void *unused)
|
||||
{
|
||||
- struct timespec iv = { 1, 0 };
|
||||
+ struct timespec iv = { 0, 100000000 };
|
||||
+ unsigned tick = 0;
|
||||
|
||||
(void)unused;
|
||||
for (;;)
|
||||
@@ -1357,6 +1382,8 @@
|
||||
int reload = 0;
|
||||
|
||||
nanosleep(&iv, NULL);
|
||||
+ mic_control_update();
|
||||
+ if (++tick % 10) continue;
|
||||
|
||||
if (g_rt_path[0])
|
||||
{
|
||||
@@ -1402,8 +1429,9 @@
|
||||
{
|
||||
if (!strcmp(argv[i], "--socket") && i + 1 < argc) path = argv[++i];
|
||||
else if (!strcmp(argv[i], "--mic-fifo") && i + 1 < argc) fifo_path = argv[++i];
|
||||
+ else if (!strcmp(argv[i], "--mic-control") && i + 1 < argc) g_mic_control = argv[++i];
|
||||
else if (!strcmp(argv[i], "--log")) g_verbose = 1;
|
||||
- else { fprintf(stderr, "usage: directaudio-relay --socket <path> [--mic-fifo <path>] [--log]\n"); return 2; }
|
||||
+ else { fprintf(stderr, "usage: directaudio-relay --socket <path> [--mic-fifo <path>] [--mic-control <path>] [--log]\n"); return 2; }
|
||||
}
|
||||
if (!path)
|
||||
{
|
||||
@@ -1429,6 +1457,8 @@
|
||||
chmod(path, 0666);
|
||||
if (listen(srv, 8) != 0) { REVENT("listen: %d", errno); return 1; }
|
||||
|
||||
+ mic_control_update();
|
||||
+ REVENT("mic enabled=%d", __atomic_load_n(&g_mic_enabled, __ATOMIC_ACQUIRE));
|
||||
if (pthread_create(&th, NULL, housekeeping_thread, NULL) == 0) pthread_detach(th);
|
||||
if (fifo_path && fifo_setup(fifo_path) != 0)
|
||||
REVENT("mic-fifo: disabled");
|
||||
@@ -2,5 +2,6 @@ DIRECTAUDIO_REPO=The412Banner/directaudio
|
||||
DIRECTAUDIO_TAG=directaudio-linux-v1.1.0
|
||||
DIRECTAUDIO_WINE11_SHA256=835e6cab072f5148893c43379e60506483aeb3f1444e777b430c295cbeb472c9
|
||||
DIRECTAUDIO_SYSTHREAD_SHA256=2ddc47f446142d5940540ad40a423ca8d47fd536e3225b888df1077c6be7329e
|
||||
DIRECTAUDIO_RELAY_SHA256=b68eb6d7a892fd92a1cd73fac36dc05cabb77cc73792e2c582d3eeccad355942
|
||||
DIRECTAUDIO_SINK_SHA256=1d5d3ed709e5389ef7603f019c62b07e4e8428bb42882193d4a144a5c15425b6
|
||||
DIRECTAUDIO_SOURCE_COMMIT=52aedbf8ddd42874a5bbd21df20e1046367f442e
|
||||
DIRECTAUDIO_SOURCE_SHA256=a20c9a0684ae3b1e60a6b9c17b7f1d5ec2501627ae9683aa9f391576a6c1974d
|
||||
@@ -17,7 +17,7 @@ if __name__ == '__main__':
|
||||
sys.exit('Docker is unavailable: ' + engine.stderr.strip())
|
||||
image = run('image', 'inspect', sys.argv[1])
|
||||
if image.returncode:
|
||||
if 'No such image' not in image.stderr:
|
||||
if 'No such image' not in image.stderr and 'image not known' not in image.stderr: # Docker, Podman
|
||||
sys.exit('Cannot inspect the build image: ' + image.stderr.strip())
|
||||
repo = Path(__file__).resolve().parents[1]
|
||||
subprocess.run(['docker', 'build', '--platform', 'linux/amd64', '-t', sys.argv[1],
|
||||
|
||||
+32
-1
@@ -21,6 +21,7 @@ from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from adb_device import DeviceResolutionError, resolve_serial
|
||||
from proot_profile import report as proot_profile_report
|
||||
|
||||
|
||||
# tools/release/variants.txt: the same app also ships as other packages (e.g. com.antutu.benchmark.full).
|
||||
@@ -37,6 +38,13 @@ class ControlError(RuntimeError):
|
||||
self.code = code
|
||||
|
||||
|
||||
def profile_slow_us(value: str) -> int:
|
||||
number = int(value)
|
||||
if not 1 <= number <= 1_000_000_000:
|
||||
raise argparse.ArgumentTypeError("--slow-us must be between 1 and 1000000000")
|
||||
return number
|
||||
|
||||
|
||||
def adb_path(configured: str | None) -> str:
|
||||
if configured:
|
||||
return configured
|
||||
@@ -628,6 +636,10 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
|
||||
request["text"] = args.text
|
||||
return add_serial(checked(provider_call(adb, serial, "ui", request=request), "UI_FAILED"), serial)
|
||||
|
||||
if command == "proot-profile":
|
||||
lines = ["PROOT_PROFILE=1", f"PROOT_PROFILE_SLOW_US={args.slow_us}"] if args.profile_op == "enable" else ["PROOT_PROFILE=0"]
|
||||
return add_serial(checked(provider_call(adb, serial, "env", request={"op": "set", "lines": lines, "persistent": False}), "ENV_FAILED"), serial)
|
||||
|
||||
if command == "env":
|
||||
if args.env_op == "set":
|
||||
request = {"op": "set", "lines": args.lines, "persistent": args.persistent}
|
||||
@@ -828,6 +840,16 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
if name == "set-text":
|
||||
op.add_argument("--text", required=True)
|
||||
|
||||
profile = commands.add_parser("proot-profile", help="profile PRoot syscall handlers in the next session, or rank a saved log")
|
||||
profile_ops = profile.add_subparsers(dest="profile_op", required=True)
|
||||
profile_enable = profile_ops.add_parser("enable", help="enable counters and bounded slow samples for the next session")
|
||||
profile_enable.add_argument("--slow-us", type=profile_slow_us, default=1000, metavar="US")
|
||||
profile_ops.add_parser("disable", help="disable profiling for the next session")
|
||||
profile_report = profile_ops.add_parser("report", help="read a local session.log without a device")
|
||||
profile_report.add_argument("path", type=Path)
|
||||
profile_report.add_argument("--sort", choices=["wall", "cpu", "calls"], default="wall")
|
||||
profile_report.add_argument("--limit", type=int, default=20)
|
||||
|
||||
env = commands.add_parser("env", help="session environment lines (debugging tools)")
|
||||
env_ops = env.add_subparsers(dest="env_op", required=True)
|
||||
env_ops.add_parser("list")
|
||||
@@ -837,7 +859,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
env_clear = env_ops.add_parser("clear")
|
||||
env_clear.add_argument("scope", nargs="?", choices=["next", "persistent", "all"], default="next")
|
||||
|
||||
override = commands.add_parser("override", help="put a binary first on the next session's PATH (debugging tools)")
|
||||
override = commands.add_parser("override", help="override a program or libblfastpath.so for the next session (debugging tools)")
|
||||
override.add_argument("name", help="the program name, e.g. gamescope")
|
||||
override.add_argument("path", help="the local file to push")
|
||||
|
||||
@@ -941,6 +963,15 @@ def main(argv: list[str] | None = None) -> int:
|
||||
try:
|
||||
if not PACKAGE_NAME.fullmatch(PACKAGE): # it reaches the device shell through `am start` and `content call`
|
||||
raise ControlError(f"DROIDDECK_PACKAGE is not an Android package name: {PACKAGE!r}", "INVALID_REQUEST")
|
||||
if args.command == "proot-profile" and args.profile_op == "report":
|
||||
if args.limit < 1:
|
||||
raise ControlError("--limit must be positive", "INVALID_ARGUMENTS")
|
||||
try:
|
||||
result = proot_profile_report(args.path.expanduser(), args.sort, args.limit)
|
||||
except OSError as exc:
|
||||
raise ControlError(str(exc), "FILE_IO") from exc
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
adb = adb_path(args.adb)
|
||||
serial = resolve_serial(adb, args.serial, log=True)
|
||||
result = execute(args, adb, serial)
|
||||
|
||||
@@ -85,3 +85,17 @@ the patched component retained 1/20, then 0 after destruction. The unassigned
|
||||
control retained 20/20 and then 0. In Backpack Battles, two batches of ten touch
|
||||
drags leaked 188 and 197 SHM descriptors before the fix; the same batches added
|
||||
zero after the fix (112 total descriptors before and after each batch).
|
||||
|
||||
## 0117 WSI: cache the present-time Xwayland bypass check
|
||||
|
||||
`QueuePresentKHR` in the WSI layer calls `canBypassXWayland` for every swapchain on
|
||||
every present. Each call makes several synchronous X requests (window geometry,
|
||||
`_WINE_ALLOW_FLIP`, parent window, a child-window scan, the toplevel window). At
|
||||
high frame rates that is thousands of round trips a second: on an AYANEO Pocket FIT
|
||||
running AIO Graphics Test uncapped, Xwayland used 24-32% of a core and the game's
|
||||
present thread sat about half idle.
|
||||
|
||||
The patch can keep the result for `DROIDDECK_WSI_BYPASS_CHECK_MS` milliseconds. Unset
|
||||
or 0 keeps the per-present check; the app sets 100 only in Performance mode and 0
|
||||
otherwise. With 100, a window resize or a flip/obscure change is seen up to 100 ms
|
||||
later than before; surface creation and capability queries still check every time.
|
||||
@@ -49,7 +49,11 @@ tar --use-compress-program=unzstd -xf "$PKG" -C out --strip-components=2 usr/bin
|
||||
mv out/gamescope out/usr/local/bin/gamescope
|
||||
chmod 755 out/usr/local/bin/gamescope
|
||||
strip --strip-unneeded out/usr/local/bin/gamescope || true
|
||||
NEEDED=$(readelf -d out/usr/local/bin/gamescope | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p')
|
||||
# The WSI layer carries patches too (0117); the runtime's stock copy is replaced.
|
||||
mkdir -p out/usr/lib
|
||||
tar --use-compress-program=unzstd -xf "$PKG" -C out usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so
|
||||
strip --strip-unneeded out/usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so || true
|
||||
NEEDED=$(for f in out/usr/local/bin/gamescope out/usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so; do readelf -d "$f" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p'; done | sort -u)
|
||||
echo "NEEDED: $NEEDED"
|
||||
MISSING=""
|
||||
for lib in $NEEDED; do grep -qx "$lib" tools/gamescope/runtime-sonames.txt || MISSING="$MISSING $lib"; done
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
--- a/layer/VkLayer_FROG_gamescope_wsi.cpp 2026-10-25 07:56:48.179978889 +0000
|
||||
+++ b/layer/VkLayer_FROG_gamescope_wsi.cpp 2026-10-25 07:56:48.207978889 +0000
|
||||
@@ -23,6 +23,8 @@
|
||||
#include <optional>
|
||||
|
||||
#include <poll.h>
|
||||
+#include <time.h>
|
||||
+#include <cstdlib>
|
||||
#include <sys/stat.h>
|
||||
// For limiter file.
|
||||
#include <time.h>
|
||||
@@ -476,6 +478,34 @@
|
||||
// Cached for comparison.
|
||||
std::optional<VkRect2D> cachedWindowRect;
|
||||
|
||||
+ // canBypassXWayland costs several X round trips; at present time it is refreshed at most
|
||||
+ // every DROIDDECK_WSI_BYPASS_CHECK_MS (default 0 = every present; DroidDeck's Performance mode sets 100).
|
||||
+ std::optional<bool> presentBypass;
|
||||
+ bool presentBypassHdr = false;
|
||||
+ uint64_t presentBypassNs = 0;
|
||||
+
|
||||
+ static uint64_t presentBypassIntervalNs() {
|
||||
+ static const uint64_t interval = [] {
|
||||
+ const char *v = getenv("DROIDDECK_WSI_BYPASS_CHECK_MS");
|
||||
+ return uint64_t(v && *v ? strtoull(v, nullptr, 10) : 0) * 1000000ull;
|
||||
+ }();
|
||||
+ return interval;
|
||||
+ }
|
||||
+
|
||||
+ bool canBypassXWaylandAtPresent(bool hdrColorspace) {
|
||||
+ if (isWayland())
|
||||
+ return true;
|
||||
+ timespec ts;
|
||||
+ clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
+ const uint64_t now = uint64_t(ts.tv_sec) * 1000000000ull + uint64_t(ts.tv_nsec);
|
||||
+ if (!presentBypass || presentBypassHdr != hdrColorspace || now - presentBypassNs >= presentBypassIntervalNs()) {
|
||||
+ presentBypass = canBypassXWayland(hdrColorspace);
|
||||
+ presentBypassHdr = hdrColorspace;
|
||||
+ presentBypassNs = now;
|
||||
+ }
|
||||
+ return *presentBypass;
|
||||
+ }
|
||||
+
|
||||
bool isWayland() const {
|
||||
// Is native Wayland?
|
||||
return connection == nullptr;
|
||||
@@ -1597,7 +1627,7 @@
|
||||
continue;
|
||||
}
|
||||
|
||||
- const bool canBypass = gamescopeSurface->canBypassXWayland(gamescopeSwapchain->isHdrColorspace);
|
||||
+ const bool canBypass = gamescopeSurface->canBypassXWaylandAtPresent(gamescopeSwapchain->isHdrColorspace);
|
||||
if (canBypass != gamescopeSwapchain->isBypassingXWayland) {
|
||||
if (canBypass) {
|
||||
if (!(gamescopeSurface->flags & GamescopeLayerClient::Flag::NoSuboptimal))
|
||||
@@ -1,3 +1,3 @@
|
||||
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p12
|
||||
GAMESCOPE_SHA256=07b69944a1ebf2741d4a867afa6327dcc63ec458f432a8f7483089dce2197010
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p13
|
||||
GAMESCOPE_SHA256=93c789dc9e08828496f1caa2849d56acdf205838de723a24b296547a29c0b6af
|
||||
@@ -12,6 +12,9 @@ export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
|
||||
for conf in client client-rt; do
|
||||
mkdir -p "/etc/pipewire/$conf.conf.d" && printf 'context.properties = {\n module.rt = false\n}\n' >"/etc/pipewire/$conf.conf.d/droiddeck-rt.conf"
|
||||
done 2>/dev/null
|
||||
export DROIDDECK_NESTED_SCALE=1
|
||||
export DROIDDECK_GLTHREAD=${mesa_glthread:-}
|
||||
unset MESA_LOADER_DRIVER_OVERRIDE LIBGL_KOPPER_DRI2 mesa_glthread
|
||||
|
||||
@@ -6,21 +6,42 @@ if [ -n "${BL_DEBUG_DIR:-}" ]; then
|
||||
fi
|
||||
width=${BL_WIDTH:-1280}
|
||||
height=${BL_HEIGHT:-720}
|
||||
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
|
||||
window=0
|
||||
if [ "${BL_DESKTOP_GPU_WINDOW:-1}" != 0 ] && [ -n "${WAYLAND_DISPLAY:-}" ] && [ "$WAYLAND_DISPLAY" != wayland-0 ]; then
|
||||
window=1
|
||||
parent=$WAYLAND_DISPLAY
|
||||
args=(--backend sdl --expose-wayland -W "$width" -H "$height" -w "$width" -h "$height")
|
||||
else
|
||||
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height")
|
||||
fi
|
||||
if [ "${BL_FPS:-0}" -gt 0 ]; then
|
||||
args+=(-r "$BL_FPS")
|
||||
elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
|
||||
args+=(-r "$BL_REFRESH")
|
||||
fi
|
||||
[ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled)
|
||||
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on wayland-0)"
|
||||
export WAYLAND_DISPLAY=wayland-0
|
||||
if [ "$window" = 1 ]; then
|
||||
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} in a window on $parent)"
|
||||
else
|
||||
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} on wayland-0)"
|
||||
export WAYLAND_DISPLAY=wayland-0
|
||||
fi
|
||||
export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11
|
||||
unset LIBGL_ALWAYS_SOFTWARE QT_QUICK_BACKEND KWIN_COMPOSE
|
||||
wsi=",${MESA_VK_WSI_DEBUG:-},"
|
||||
while [[ $wsi == *,sw,* ]]; do wsi=${wsi//,sw,/,}; done
|
||||
wsi=${wsi#,}; wsi=${wsi%,}
|
||||
if [ -n "$wsi" ]; then export MESA_VK_WSI_DEBUG=$wsi; else unset MESA_VK_WSI_DEBUG; fi
|
||||
export BL_DESKTOP_GPU_CHILD=1
|
||||
export MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true
|
||||
[ -n "${DROIDDECK_GLTHREAD:-}" ] && export mesa_glthread=$DROIDDECK_GLTHREAD
|
||||
export APPIMAGE_EXTRACT_AND_RUN=1
|
||||
gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
|
||||
if [ "$window" = 1 ]; then
|
||||
export BL_GPU_CHILD_WSI=${MESA_VK_WSI_DEBUG:-}
|
||||
SDL_VIDEODRIVER=wayland MESA_VK_WSI_DEBUG=sw gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
|
||||
else
|
||||
gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@"
|
||||
fi
|
||||
rc=$?
|
||||
echo "== droiddeck-gpu $(date -u +%H:%M:%S): exited $rc"
|
||||
exit $rc
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Runs DroidDeck's bundled innoextract with its own boost libraries. The guest's
|
||||
# env -i startup has no LD_LIBRARY_PATH, and the rootfs must not grow a second
|
||||
# copy of boost for the installer fallback.
|
||||
LD_LIBRARY_PATH=/usr/local/lib/droiddeck-inno
|
||||
export LD_LIBRARY_PATH
|
||||
exec /usr/local/lib/droiddeck-inno/innoextract "$@"
|
||||
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
BIN
Binary file not shown.
+23
@@ -0,0 +1,23 @@
|
||||
Boost Software License - Version 1.0 - August 17th, 2003
|
||||
|
||||
Permission is hereby granted, free of charge, to any person or organization
|
||||
obtaining a copy of the software and accompanying documentation covered by
|
||||
this license (the "Software") to use, reproduce, display, distribute,
|
||||
execute, and transmit the Software, and to prepare derivative works of the
|
||||
Software, and to permit third-parties to whom the Software is furnished to
|
||||
do so, all subject to the following:
|
||||
|
||||
The copyright notices in the Software and this entire statement, including
|
||||
the above license grant, this restriction and the following disclaimer,
|
||||
must be included in all copies of the Software, in whole or in part, and
|
||||
all derivative works of the Software, unless such copies or derivative
|
||||
works are solely in the form of machine-executable object code generated by
|
||||
a source language processor.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
|
||||
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
|
||||
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
|
||||
Copyright (C) 2011-2020 Daniel Scharrer <daniel@constexpr.org>
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the author(s) be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
+1318
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@ set -u
|
||||
export LANG=C.UTF-8
|
||||
step() { echo "== STEP $*"; }
|
||||
fail() { echo "== FAIL $*"; exit 1; }
|
||||
[ "$(id -u)" = 0 ] || fail "needs root: install Flatpak from the launcher's Store, which runs this as root"
|
||||
|
||||
PACKAGES="flatpak ostree appstream libxmlb libmalcontent libfyaml accountsservice composefs xdg-dbus-proxy"
|
||||
while read -r pkg probe; do
|
||||
@@ -48,10 +49,13 @@ if [ ! -f /etc/pacman.d/gnupg/pubring.gpg ] && [ ! -f /etc/pacman.d/gnupg/pubrin
|
||||
fi
|
||||
|
||||
step "Reading the package lists"
|
||||
pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy >/dev/null 2>&1 \
|
||||
|| pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1 | tail -3 \
|
||||
|| fail "could not reach the Arch Linux ARM mirrors"
|
||||
[ -f "$WORK/db/sync/extra.db" ] || fail "could not reach the Arch Linux ARM mirrors"
|
||||
sync_log=$(pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1) \
|
||||
|| sync_log=$(pacman --config "$CONF" --dbpath "$WORK/db" --noconfirm -Sy 2>&1)
|
||||
if [ ! -f "$WORK/db/sync/extra.db" ]; then
|
||||
printf '%s\n' "$sync_log" | tail -3
|
||||
reason=$(printf '%s\n' "$sync_log" | grep -m1 -i '^error' | cut -c1-160)
|
||||
fail "could not reach the Arch Linux ARM mirrors${reason:+ ($reason)}"
|
||||
fi
|
||||
|
||||
step "Downloading Flatpak"
|
||||
out=$(pacman --config "$CONF" --dbpath "$WORK/db" --cachedir "$WORK/pkg" --noconfirm -Sw -dd $PACKAGES 2>&1)
|
||||
|
||||
@@ -122,12 +122,26 @@ def arkham_city_x87(game):
|
||||
|
||||
|
||||
|
||||
@fix
|
||||
def protonfixes_off(game):
|
||||
if game.stem in ("blackops3", "darksoulsremastered"):
|
||||
return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)"
|
||||
|
||||
|
||||
@fix
|
||||
def caravan_sandwitch_feature_level(game):
|
||||
if "caravansandwitch.exe" in game.files or game.stem == "caravansandwitch-win64-shipping":
|
||||
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "Caravan SandWitch: D3D12 feature level 12_1 (12_2 hands it mesh shader pipelines vkd3d-proton cannot build)"
|
||||
|
||||
|
||||
@fix
|
||||
def robocop_rogue_city_feature_level(game):
|
||||
"""vkd3d-proton turns mesh shaders off on Adreno, but 12_2 still advertises them, and UE5 then builds mesh
|
||||
pipelines with no pipeline layout that crash Turnip on launch."""
|
||||
if "robocop.exe" in game.files or game.stem == "robocop-win64-shipping":
|
||||
return {"VKD3D_FEATURE_LEVEL": "12_1"}, [], "RoboCop: Rogue City: D3D12 feature level 12_1"
|
||||
|
||||
|
||||
@fix
|
||||
def cyberpunk_feature_level(game):
|
||||
if game.stem == "cyberpunk2077" or (
|
||||
@@ -273,6 +287,58 @@ def game_gpu(env):
|
||||
return result
|
||||
|
||||
|
||||
def vram_cap(env):
|
||||
"""Puts the session's VRAM cap ahead of the game's own DXVK settings, so a game profile can still raise it."""
|
||||
value = env.get("BL_VRAM_MB", "")
|
||||
if not re.fullmatch(r"[1-9][0-9]{0,6}", value):
|
||||
return env
|
||||
result = env.copy()
|
||||
cap = "dxgi.maxDeviceMemory = %d" % int(value)
|
||||
own = result.get("DXVK_CONFIG", "").strip().strip(";").strip()
|
||||
result["DXVK_CONFIG"] = cap + "; " + own if own else cap
|
||||
return result
|
||||
|
||||
|
||||
def parse_cores(text):
|
||||
"""CPU numbers from a list such as "0-3,6"; None when the text is not one."""
|
||||
cores = set()
|
||||
for part in text.replace(" ", "").split(","):
|
||||
match = re.fullmatch(r"(\d{1,3})(?:-(\d{1,3}))?", part)
|
||||
if not match:
|
||||
return None
|
||||
first, last = int(match.group(1)), int(match.group(2) or match.group(1))
|
||||
if last < first:
|
||||
return None
|
||||
cores.update(range(first, last + 1))
|
||||
return cores or None
|
||||
|
||||
|
||||
def online_cores():
|
||||
try:
|
||||
with open("/sys/devices/system/cpu/online") as f:
|
||||
cores = parse_cores(f.read().strip())
|
||||
except OSError:
|
||||
cores = None
|
||||
return cores or os.sched_getaffinity(0) | set(range(os.cpu_count() or 0))
|
||||
|
||||
|
||||
def game_cores(env):
|
||||
"""Pins the game to the cores its profile names, in place of the session's game cores."""
|
||||
text = env.get("DROIDDECK_GAME_CORES", "").strip()
|
||||
if not text:
|
||||
return
|
||||
cores = parse_cores(text)
|
||||
chosen = cores & online_cores() if cores else None
|
||||
if not chosen:
|
||||
print("droiddeck-game-env: ignoring game cores %r" % text, file=sys.stderr)
|
||||
return
|
||||
try:
|
||||
os.sched_setaffinity(0, chosen)
|
||||
print("droiddeck-game-env: game cores %s" % ",".join(map(str, sorted(chosen))), file=sys.stderr)
|
||||
except OSError as error:
|
||||
print("droiddeck-game-env: could not use game cores %r (%s)" % (text, error), file=sys.stderr)
|
||||
|
||||
|
||||
def apply_config(env, config, app_id, fixes=None):
|
||||
if config.get("version") != 1:
|
||||
raise ValueError("unsupported environment configuration")
|
||||
@@ -546,7 +612,9 @@ def main():
|
||||
command = offline_without_anticheat(command, env)
|
||||
if mic_enabled == "0":
|
||||
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
|
||||
env = vram_cap(env)
|
||||
env = force_ssbs(command, env)
|
||||
game_cores(env)
|
||||
try:
|
||||
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
|
||||
except Exception as error:
|
||||
|
||||
@@ -45,6 +45,13 @@ def advertise_compositing():
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) < 2:
|
||||
raise SystemExit('usage: droiddeck-gpu-window <program> [args...]')
|
||||
if 'BL_GPU_CHILD_WSI' in os.environ:
|
||||
wsi = os.environ.pop('BL_GPU_CHILD_WSI')
|
||||
if wsi:
|
||||
os.environ['MESA_VK_WSI_DEBUG'] = wsi
|
||||
else:
|
||||
os.environ.pop('MESA_VK_WSI_DEBUG', None)
|
||||
os.environ['SDL_VIDEODRIVER'] = 'x11'
|
||||
os.environ.setdefault('GTK_CSD', '1')
|
||||
try:
|
||||
connection = advertise_compositing()
|
||||
|
||||
@@ -9,9 +9,9 @@ Add an app does) when that holds native programs or libraries. A Steam library's
|
||||
droiddeck-open --exec FILE [ARGS...] an exec the kernel refused (libblsession)
|
||||
droiddeck-open --install the Run entries and default handlers
|
||||
|
||||
The desktop composites in software, so a program started from it goes full screen on the GPU
|
||||
(droiddeck-gpu), as the menu's games do: --window keeps it in a desktop window instead, --terminal
|
||||
runs it in Konsole. A plain script stays on the desktop, and an exec whose output is read (a terminal,
|
||||
The desktop composites in software, so a program started from it runs on the GPU in a window of its
|
||||
own (droiddeck-gpu), as the menu's games do: --window keeps it on the desktop's software drawing
|
||||
instead, --terminal runs it in Konsole. A plain script stays on the desktop, and an exec whose output is read (a terminal,
|
||||
a pipe, a file) stays where it was started.
|
||||
"""
|
||||
import fcntl
|
||||
@@ -337,7 +337,7 @@ def unattended(env):
|
||||
|
||||
|
||||
def placed(cmd, what, mode, env):
|
||||
"""[cmd] where it shows: full screen on the GPU from the desktop, else where it was started."""
|
||||
"""[cmd] where it shows: on the GPU from the desktop, else where it was started."""
|
||||
if mode == "terminal" and what not in ("windows", "steam") and shutil.which("konsole"):
|
||||
return ["konsole", "--hold", "-e"] + cmd
|
||||
if mode == "window" or what in ("script", "steam") or not on_desktop(env):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/python3
|
||||
"""Runs a Windows program with the Proton the Steam client has chosen for it.
|
||||
|
||||
droiddeck-proton-run [--window] PROGRAM [ARGS...]
|
||||
droiddeck-proton-run [--window] [--prefix ID] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]
|
||||
droiddeck-proton-run --app ID [--dir FOLDER] [--options TEXT] [PROGRAM [ARGS...]]
|
||||
|
||||
The program belongs to an installed Steam game when it sits in one's folder, to a prefix when it
|
||||
@@ -10,10 +10,15 @@ its own, under the id the client gives a new shortcut. That title's CompatToolMa
|
||||
config.vdf picks the tool, else the client's default for all other titles ("0"). The tool is
|
||||
started as the client starts it - its toolmanifest's command line, the waitforexitandrun verb and
|
||||
the STEAM_COMPAT_* environment - so its wrapper applies the game's settings, components and audio.
|
||||
--window keeps the program in the desktop's own window, drawn with WineD3D.
|
||||
--window keeps the program in the desktop's own window, drawn with WineD3D on the desktop's software
|
||||
GL (llvmpipe): KWin there composites in software, and the session's zink finds no device.
|
||||
--prefix ID puts the program in compatdata/ID whatever it is. --verb run starts it beside what already
|
||||
runs in the prefix, which waitforexitandrun would wait for; the wrapper's launch-time steps are skipped.
|
||||
--game-id ID keeps the id of the launch it runs for: gamescope shows the windows that carry the id Steam launched.
|
||||
--app starts one game without the Steam client (its Start without Steam): a Steam game's default
|
||||
Windows launch option from appinfo.vdf when no program is given, else the program in that
|
||||
shortcut's own prefix, started in --dir with the shortcut's launch options (--options).
|
||||
shortcut's own prefix, started in --dir with the shortcut's launch options (--options). Without
|
||||
--options it takes the launch options set in the client's Properties for that game or shortcut.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
@@ -30,7 +35,10 @@ BIN_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
STATE = os.path.join(HOME, ".local", "share", "droiddeck-compat", "state.json")
|
||||
EXTRA_LIBRARIES = ("/mnt/droiddeck", "/mnt/droiddeck-sd")
|
||||
SYSTEM_TOOLS = ("/usr/share/steam/compatibilitytools.d", "/usr/local/share/steam/compatibilitytools.d")
|
||||
DESKTOP_GL = {"LIBGL_ALWAYS_SOFTWARE": "1", "GALLIUM_DRIVER": "llvmpipe"}
|
||||
NOT_DESKTOP_GL = ("MESA_LOADER_DRIVER_OVERRIDE", "LIBGL_KOPPER_DRI2")
|
||||
VERB = "waitforexitandrun"
|
||||
VERBS = (VERB, "run")
|
||||
SHORTCUT_BIT = 0x80000000
|
||||
STEAM_APP_LIMIT = 2 ** 31
|
||||
|
||||
@@ -185,9 +193,9 @@ def steam_game(program, libs):
|
||||
def prefix_of(program):
|
||||
for folder, below in ancestors(program):
|
||||
parent = os.path.dirname(folder)
|
||||
if below == "pfx" and os.path.basename(parent) == "compatdata" and os.path.basename(folder).isdigit():
|
||||
if below == "pfx" and os.path.basename(parent) == "compatdata" and re.fullmatch(r"-?[0-9]+", os.path.basename(folder)):
|
||||
library = os.path.dirname(os.path.dirname(parent))
|
||||
return Target(os.path.basename(folder), folder, os.path.dirname(program), library, "prefix")
|
||||
return Target(str(int(os.path.basename(folder)) % 2 ** 32), folder, os.path.dirname(program), library, "prefix")
|
||||
return None
|
||||
|
||||
|
||||
@@ -230,10 +238,68 @@ def shortcut_entries(root):
|
||||
return entries
|
||||
|
||||
|
||||
def prefix_folder(root, appid):
|
||||
"""The prefix folder the client made for [appid], under either spelling of the id."""
|
||||
folder = os.path.join(root, "steamapps", "compatdata")
|
||||
try:
|
||||
names = sorted(os.listdir(folder))
|
||||
except OSError:
|
||||
names = []
|
||||
candidates = []
|
||||
for name in names:
|
||||
if not re.fullmatch(r"-?[0-9]+", name):
|
||||
continue
|
||||
try:
|
||||
matches = int(name) % 2 ** 32 == appid % 2 ** 32
|
||||
except ValueError:
|
||||
continue
|
||||
match = os.path.join(folder, name)
|
||||
if matches and os.path.isdir(match):
|
||||
candidates.append((os.path.isdir(os.path.join(match, "pfx")),
|
||||
name == str(appid % 2 ** 32), name, match))
|
||||
if candidates:
|
||||
return min(candidates, key=lambda item: (not item[0], not item[1], item[2]))[3]
|
||||
return os.path.join(folder, str(appid % 2 ** 32))
|
||||
|
||||
|
||||
def vdf_string(token):
|
||||
return re.sub(r'\\(.)', r'\1', token[1:-1]) if token.startswith('"') else ""
|
||||
|
||||
|
||||
def steam_options(app, root):
|
||||
"""The launch options the client keeps for a game (localconfig.vdf) or a shortcut (shortcuts.vdf)."""
|
||||
try:
|
||||
tool = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-steam-shortcuts"))
|
||||
account = tool["account_dir"](root)
|
||||
if not account:
|
||||
return ""
|
||||
if int(app) >= STEAM_APP_LIMIT:
|
||||
with open(os.path.join(account, "config", "shortcuts.vdf"), "rb") as f:
|
||||
shortcuts = tool["parse"](f.read()).get("shortcuts", {})
|
||||
for value in shortcuts.values():
|
||||
if isinstance(value, dict) and (value.get("appid", value.get("AppId")) or 0) & 0xFFFFFFFF == int(app):
|
||||
options = value.get("LaunchOptions", value.get("launchoptions", ""))
|
||||
return options if isinstance(options, str) else ""
|
||||
return ""
|
||||
tokens = compat()["tokenize"](read_text(os.path.join(account, "config", "localconfig.vdf")) or "")
|
||||
start = compat()["find_block"](tokens, ["UserLocalConfigStore", "Software", "Valve", "Steam", "apps", app])
|
||||
if start is None:
|
||||
return ""
|
||||
end, depth = compat()["block_end"](tokens, start), 0
|
||||
for i in range(start + 1, end):
|
||||
if tokens[i] in ("{", "}"):
|
||||
depth += 1 if tokens[i] == "{" else -1
|
||||
elif depth == 0 and tokens[i].lower() == '"launchoptions"' and i + 1 < end:
|
||||
return vdf_string(tokens[i + 1])
|
||||
except (OSError, ValueError, IndexError, KeyError, TypeError, AttributeError, struct.error):
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def shortcut(program, root):
|
||||
for appid, exe, start in shortcut_entries(root):
|
||||
if same_file(program, exe):
|
||||
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)),
|
||||
return Target(appid, prefix_folder(root, appid),
|
||||
os.path.dirname(program), root, "shortcut", start if os.path.isdir(start) else None)
|
||||
return None
|
||||
|
||||
@@ -250,10 +316,19 @@ def locate(program, root):
|
||||
if found:
|
||||
return found
|
||||
appid = own_id(program)
|
||||
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)),
|
||||
return Target(appid, prefix_folder(root, appid),
|
||||
os.path.dirname(program), root, "own")
|
||||
|
||||
|
||||
def fixed(program, root, appid):
|
||||
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)),
|
||||
os.path.dirname(program), root, "fixed")
|
||||
|
||||
|
||||
def prefix_id(value):
|
||||
return value if value.isdigit() and not value.startswith("0") and int(value) <= 0xFFFFFFFF else None
|
||||
|
||||
|
||||
def split_words(text):
|
||||
try:
|
||||
return shlex.split(text or "")
|
||||
@@ -325,7 +400,8 @@ def steam_launch(appid, root):
|
||||
|
||||
|
||||
def shortcut_target(appid, program, start, root):
|
||||
return Target(appid, os.path.join(root, "steamapps", "compatdata", str(appid)), os.path.dirname(program), root,
|
||||
appid = int(appid) % 2 ** 32
|
||||
return Target(str(appid), prefix_folder(root, appid), os.path.dirname(program), root,
|
||||
"shortcut", start if start and os.path.isdir(start) else None)
|
||||
|
||||
|
||||
@@ -337,7 +413,7 @@ def steam_launches(target, program, root):
|
||||
return os.path.relpath(program, target.install).replace(os.sep, "/").lower() in entry.get("launch", ())
|
||||
|
||||
|
||||
def environment(env, target, tool_folder, root, window=False):
|
||||
def environment(env, target, tool_folder, root, window=False, game_id=None):
|
||||
env = dict(env)
|
||||
steamapps = [os.path.join(lib, "steamapps") for lib in libraries(root)]
|
||||
env.update({
|
||||
@@ -355,28 +431,52 @@ def environment(env, target, tool_folder, root, window=False):
|
||||
else:
|
||||
game = str(number << 32 | 0x02000000)
|
||||
env.update(SteamAppId="0", STEAM_COMPAT_APP_ID="0", SteamGameId=game, SteamOverlayGameId=game)
|
||||
if game_id:
|
||||
env.update(SteamGameId=game_id, SteamOverlayGameId=game_id)
|
||||
if window:
|
||||
env.setdefault("PROTON_USE_WINED3D", "1")
|
||||
env.update(DESKTOP_GL)
|
||||
for name in NOT_DESKTOP_GL:
|
||||
env.pop(name, None)
|
||||
return env
|
||||
|
||||
|
||||
def windows_path(path):
|
||||
def windows_path(path, compatdata=None):
|
||||
if compatdata:
|
||||
drive = os.path.join(compatdata, "pfx", "drive_c")
|
||||
inside = os.path.relpath(path, drive)
|
||||
if inside != "." and not inside.startswith(".."):
|
||||
return "C:\\" + inside.replace("/", "\\")
|
||||
return "Z:" + path.replace("/", "\\")
|
||||
|
||||
|
||||
def arguments(program, args):
|
||||
def arguments(program, args, desktop=None, compatdata=None):
|
||||
if program.lower().endswith(".msi"):
|
||||
return ["msiexec", "/i", windows_path(program)] + args
|
||||
if desktop:
|
||||
return ["explorer.exe", "/desktop=droiddeck,%s" % desktop, windows_path(program, compatdata)] + args
|
||||
return [program] + args
|
||||
|
||||
|
||||
def main(argv):
|
||||
window = False
|
||||
app, start, options = None, None, ""
|
||||
prefix = None
|
||||
verb = VERB
|
||||
game_id = None
|
||||
desktop = None
|
||||
app, start, options = None, None, None
|
||||
while argv and argv[0].startswith("--"):
|
||||
option = argv.pop(0)
|
||||
if option == "--window":
|
||||
window = True
|
||||
elif option == "--prefix" and argv and prefix_id(argv[0]):
|
||||
prefix = argv.pop(0)
|
||||
elif option == "--verb" and argv and argv[0] in VERBS:
|
||||
verb = argv.pop(0)
|
||||
elif option == "--game-id" and argv and argv[0].isdigit() and argv[0] != "0":
|
||||
game_id = argv.pop(0)
|
||||
elif option == "--desktop" and argv and re.fullmatch(r"[1-9][0-9]{2,4}x[1-9][0-9]{2,4}", argv[0]):
|
||||
desktop = argv.pop(0)
|
||||
elif option in ("--app", "--dir", "--options") and argv:
|
||||
value = argv.pop(0)
|
||||
if option == "--app":
|
||||
@@ -394,9 +494,11 @@ def main(argv):
|
||||
say("%s is not an app id" % app)
|
||||
return 2
|
||||
if not argv and app is None:
|
||||
say("usage: droiddeck-proton-run [--window] PROGRAM [ARGS...]")
|
||||
say("usage: droiddeck-proton-run [--window] [--prefix ID] [--verb run] [--game-id ID] [--desktop WxH] PROGRAM [ARGS...]")
|
||||
return 2
|
||||
root = os.environ.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or STEAM_ROOT
|
||||
if options is None:
|
||||
options = steam_options(app, root) if app is not None else ""
|
||||
extra, args = split_options(options)
|
||||
if not argv:
|
||||
if int(app) >= STEAM_APP_LIMIT:
|
||||
@@ -416,6 +518,8 @@ def main(argv):
|
||||
args = args + argv[1:]
|
||||
if app is not None and int(app) >= STEAM_APP_LIMIT:
|
||||
target = shortcut_target(app, program, start, root)
|
||||
elif prefix:
|
||||
target = fixed(program, root, prefix)
|
||||
else:
|
||||
target = locate(program, root)
|
||||
available = tools(root)
|
||||
@@ -425,7 +529,7 @@ def main(argv):
|
||||
return 69
|
||||
folder, command = available[name]
|
||||
os.makedirs(target.compatdata, exist_ok=True)
|
||||
env = environment(os.environ, target, folder, root, window)
|
||||
env = environment(os.environ, target, folder, root, window, game_id)
|
||||
env.update(extra)
|
||||
say("%s with %s (%s), %s prefix %s%s" % (program, name, why, target.kind, target.compatdata,
|
||||
", without the Steam client" if app is not None else ""))
|
||||
@@ -434,7 +538,7 @@ def main(argv):
|
||||
except OSError:
|
||||
os.chdir(os.path.dirname(program))
|
||||
entry = os.path.join(folder, command)
|
||||
os.execve(entry, [entry, VERB] + arguments(program, args), env)
|
||||
os.execve(entry, [entry, verb] + arguments(program, args, desktop, target.compatdata), env)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -16,7 +16,7 @@ if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
|
||||
fi
|
||||
exec > >({ dd of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1
|
||||
echo "== droiddeck-session $(date) mode=$mode $*"
|
||||
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} fps=${BL_FPS:-0} icd=${VK_ICD_FILENAMES:-none}"
|
||||
echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}"
|
||||
echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)"
|
||||
echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)"
|
||||
fi
|
||||
@@ -211,13 +211,19 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
width=${BL_WIDTH:-1280}
|
||||
height=${BL_HEIGHT:-720}
|
||||
nested=$width
|
||||
nested_h=$height
|
||||
if [ "${BL_FOLLOW_OUTPUT:-0}" = 1 ]; then
|
||||
echo "== gamescope: the output follows the screen (${width}x${height} to start)"
|
||||
elif [ "$mode" = steam ] && [ "${BL_GAMESCOPE_STRETCH_16X9:-0}" = 1 ]; then
|
||||
wide=$(( (height * 16 + 4) / 9 / 2 * 2 ))
|
||||
tall=$(( (width * 9 + 8) / 16 / 2 * 2 ))
|
||||
if [ "$wide" -gt "$width" ]; then
|
||||
nested=$wide
|
||||
echo "== gamescope: games at ${nested}x${height} stretched to the ${width}x${height} output"
|
||||
elif [ "$tall" -gt "$height" ]; then
|
||||
nested_h=$tall
|
||||
fi
|
||||
if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then
|
||||
echo "== gamescope: games at ${nested}x${nested_h} stretched to the ${width}x${height} output"
|
||||
fi
|
||||
fi
|
||||
# Off unless Performance asks for it. Compositing the cursor here adds a second
|
||||
@@ -225,11 +231,12 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
if [ "$mode" = steam ] && [ "${BL_CURSOR_COMPOSITE:-0}" = 1 ]; then
|
||||
export gamescope_cursor_composite=2
|
||||
fi
|
||||
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$height")
|
||||
[ "$nested" != "$width" ] && args+=(-S stretch) && export BL_STRETCHED=1
|
||||
if [ "${BL_FPS:-0}" -gt 0 ]; then
|
||||
args+=(-r "$BL_FPS")
|
||||
elif [ "${BL_REFRESH:-0}" -gt 0 ]; then
|
||||
args=(--backend wayland --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h")
|
||||
if [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; then
|
||||
args+=(-S stretch)
|
||||
export BL_STRETCHED=1
|
||||
fi
|
||||
if [ "${BL_REFRESH:-0}" -gt 0 ]; then
|
||||
args+=(-r "$BL_REFRESH")
|
||||
fi
|
||||
[ "$mode" = steam ] && [ "${BL_STEAM_UI:-}" != desktop ] && args+=(-e)
|
||||
@@ -249,6 +256,10 @@ if [ -z "${BL_INSIDE:-}" ]; then
|
||||
echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)"
|
||||
fi
|
||||
export BL_INSIDE=1
|
||||
# A fixed path: left to itself gamescope creates a new limiter state file on every start.
|
||||
rm -f "${XDG_RUNTIME_DIR:-/tmp}"/gamescope-limiter-*
|
||||
export GAMESCOPE_LIMITER_FILE="${XDG_RUNTIME_DIR:-/tmp}/droiddeck-gamescope-limiter"
|
||||
rm -f "$GAMESCOPE_LIMITER_FILE"
|
||||
if [ "$mode" = steam ]; then
|
||||
if /usr/local/bin/droiddeck-pipewire start; then
|
||||
eval "$(/usr/local/bin/droiddeck-pipewire env)"
|
||||
@@ -446,11 +457,19 @@ case $mode in
|
||||
fi
|
||||
if [ "${BL_ZRAM:-0}" = 1 ]; then
|
||||
step "zRAM compression: on"
|
||||
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam is not compressed while games run (turned off in Performance)"
|
||||
_bl_ram_cap=0
|
||||
case ${BL_RAM_CAP_MB:-} in
|
||||
''|0) ;;
|
||||
*[!0-9]*|0*|???????*) step "RAM cap: ignored invalid value '$BL_RAM_CAP_MB'" ;;
|
||||
*) _bl_ram_cap=$((BL_RAM_CAP_MB * 1024)); step "RAM cap: ${BL_RAM_CAP_MB} MB" ;;
|
||||
esac
|
||||
(
|
||||
bl_zram_scan() {
|
||||
_bl_game=0 _bl_pids=() _bl_apps=
|
||||
_bl_game=0 _bl_pids=() _bl_others=() _bl_apps=
|
||||
local _d _c _args _name _a _id
|
||||
for _d in /proc/[0-9]*; do
|
||||
[ "${_d##*/}" != "$BASHPID" ] || continue
|
||||
_args=()
|
||||
# Under FEX the program is FEX's first argument. AppId= is its own argument.
|
||||
while IFS= read -r -d '' _c; do _args+=("$_c"); done 2>/dev/null < "$_d/cmdline" || true
|
||||
@@ -472,30 +491,67 @@ case $mode in
|
||||
done
|
||||
;;
|
||||
steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;;
|
||||
*) _bl_others+=("${_d##*/}") ;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
bl_zram_usage() {
|
||||
local _p _k _v _u _rss=0 _swap=0
|
||||
for _p in "${_bl_pids[@]}"; do
|
||||
for _p in "$@"; do
|
||||
while read -r _k _v _u; do
|
||||
case $_k in VmRSS:) _rss=$((_rss + _v)) ;; VmSwap:) _swap=$((_swap + _v)) ;; esac
|
||||
done 2>/dev/null < "/proc/$_p/status"
|
||||
done
|
||||
echo "${#_bl_pids[@]} processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
|
||||
_bl_rss=$_rss
|
||||
echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB"
|
||||
}
|
||||
# Only processes that loaded libblsession are the session's own and answer SIGURG.
|
||||
bl_session_others() {
|
||||
local _p
|
||||
_bl_session=()
|
||||
for _p in "${_bl_others[@]}"; do
|
||||
grep -q -m1 '/libblsession\.so$' "/proc/$_p/maps" 2>/dev/null && _bl_session+=("$_p")
|
||||
done
|
||||
}
|
||||
bl_zram_pick() {
|
||||
if [ "$1" = session ]; then
|
||||
bl_session_others
|
||||
_pids=("${_bl_session[@]}")
|
||||
else
|
||||
_pids=("${_bl_pids[@]}")
|
||||
fi
|
||||
}
|
||||
# Same protocol as SessionSuspendController: an empty ack when the page-out starts, a byte when it is done.
|
||||
# A process whose SIGURG handler was replaced never acks, so it is not waited for after the first 2 s.
|
||||
bl_zram_wait() {
|
||||
local _p _left _start=$SECONDS
|
||||
while [ $((SECONDS - _start)) -lt 12 ]; do
|
||||
_left=0
|
||||
for _p in "$@"; do
|
||||
[ -s "/tmp/.bl-zram.ack.$_p" ] && continue
|
||||
[ -d "/proc/$_p" ] || continue
|
||||
[ $((SECONDS - _start)) -ge 2 ] && [ ! -e "/tmp/.bl-zram.ack.$_p" ] && continue
|
||||
_left=1
|
||||
done
|
||||
[ "$_left" = 1 ] || break
|
||||
nap 0.2
|
||||
done
|
||||
for _p in "$@"; do rm -f "/tmp/.bl-zram.ack.$_p"; done
|
||||
}
|
||||
bl_zram_send() {
|
||||
step "zRAM: $2 ($(bl_zram_usage))"
|
||||
printf '%s' "$1" > /tmp/.bl-zram
|
||||
[ "${#_bl_pids[@]}" = 0 ] || kill -URG "${_bl_pids[@]}" 2>/dev/null
|
||||
nap 5
|
||||
local _mode=$1 _what=$2 _which=$3 _pids _p
|
||||
bl_zram_pick "$_which"
|
||||
step "zRAM: $_what ($(bl_zram_usage "${_pids[@]}"))"
|
||||
for _p in "${_pids[@]}"; do rm -f "/tmp/.bl-zram.ack.$_p"; done
|
||||
printf '%s' "$_mode" > /tmp/.bl-zram
|
||||
[ "${#_pids[@]}" = 0 ] || kill -URG "${_pids[@]}" 2>/dev/null
|
||||
if [ "$_mode" = 1 ]; then bl_zram_wait "${_pids[@]}"; else nap 5; fi
|
||||
bl_zram_scan
|
||||
step "zRAM: done ($(bl_zram_usage))"
|
||||
bl_zram_pick "$_which"
|
||||
step "zRAM: done ($(bl_zram_usage "${_pids[@]}"))"
|
||||
}
|
||||
# Proton's reaper exists before the game window does, and compressing then stalls the
|
||||
# launch. focusedApp uses the same 32-bit id as that reaper's AppId= (769 is Steam; a
|
||||
# shortcut's CGameID keeps this id in its high half). The clock starts on a match, then
|
||||
# waits 20 s more. Desktop Steam never writes focus.json, so the game process is enough.
|
||||
# Proton starts its reaper before the game window; compressing during launch stalls it.
|
||||
# Desktop Steam has no focus.json, so it still uses the game process as its trigger.
|
||||
bl_game_focused() {
|
||||
if [ "${BL_DESKTOP:-}" = 1 ] || [ -z "${BL_LAUNCH_DIR:-}" ]; then
|
||||
return 0
|
||||
@@ -509,18 +565,58 @@ case $mode in
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
_bl_since=-1 _bl_packed=-1
|
||||
bl_over_cap() {
|
||||
[ "$_bl_ram_cap" -gt 0 ] || return 1
|
||||
_bl_measured=$SECONDS
|
||||
bl_session_others
|
||||
bl_zram_usage "${_bl_pids[@]}" "${_bl_session[@]}" > /dev/null
|
||||
[ "$_bl_rss" -gt "$_bl_ram_cap" ]
|
||||
}
|
||||
bl_cap_due() {
|
||||
[ "$_bl_ram_cap" -gt 0 ] && { [ "$_bl_measured" -lt 0 ] || [ $((SECONDS - _bl_measured)) -ge 30 ]; }
|
||||
}
|
||||
_bl_since=-1 _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30
|
||||
while kill -0 $$ 2>/dev/null; do
|
||||
bl_zram_scan
|
||||
if bl_cap_due; then
|
||||
if bl_over_cap; then
|
||||
# A cap below the game's working set cannot be met; paging out again every 30 s only churns.
|
||||
if [ "$_bl_capped" -lt 0 ] || [ $((SECONDS - _bl_capped)) -ge "$_bl_backoff" ]; then
|
||||
bl_zram_usage "${_bl_pids[@]}" > /dev/null
|
||||
if [ "$_bl_rss" -ge $((512 * 1024)) ]; then
|
||||
bl_zram_send 1 "over the ${BL_RAM_CAP_MB} MB RAM cap, compressing the client" client
|
||||
[ "$_bl_game" = 1 ] && _bl_packed=$SECONDS
|
||||
else
|
||||
step "RAM cap: over, client already small ($((_bl_rss / 1024)) MB resident), skipping it"
|
||||
fi
|
||||
bl_over_cap && bl_zram_send 1 "still over the RAM cap, compressing the rest of the session" session
|
||||
if bl_over_cap; then
|
||||
_bl_backoff=$((_bl_backoff * 2 > 600 ? 600 : _bl_backoff * 2))
|
||||
step "RAM cap: still over after paging out, next try in ${_bl_backoff} s"
|
||||
else
|
||||
_bl_backoff=30
|
||||
fi
|
||||
_bl_capped=$SECONDS
|
||||
fi
|
||||
else
|
||||
_bl_backoff=30
|
||||
if [ "$_bl_unpack" = 1 ] && [ "$_bl_game" = 0 ]; then
|
||||
bl_zram_send 0 "back under the RAM cap, reading the client back" client
|
||||
_bl_unpack=0
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
if [ "$_bl_game" = 1 ] && bl_game_focused; then
|
||||
[ "$_bl_since" -ge 0 ] || _bl_since=$SECONDS
|
||||
if [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] &&
|
||||
if [ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] &&
|
||||
{ [ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 300 ]; }; then
|
||||
bl_zram_send 1 "compressing the client"
|
||||
bl_zram_send 1 "compressing the client" client
|
||||
_bl_packed=$SECONDS
|
||||
fi
|
||||
elif [ "$_bl_game" != 1 ]; then
|
||||
[ "$_bl_packed" -lt 0 ] || bl_zram_send 0 "game closed, reading the client back"
|
||||
if [ "$_bl_packed" -ge 0 ]; then
|
||||
if bl_over_cap; then _bl_unpack=1; else bl_zram_send 0 "game closed, reading the client back" client; _bl_unpack=0; fi
|
||||
fi
|
||||
_bl_since=-1 _bl_packed=-1
|
||||
else
|
||||
_bl_since=-1
|
||||
@@ -843,7 +939,11 @@ BUSCONF
|
||||
echo "== steam: devtools port $BL_CDP_PORT, guest processes only"
|
||||
fi
|
||||
[ -n "${BL_LAUNCH_DIR:-}" ] && mkdir -p "$BL_LAUNCH_DIR/agent" && echo "$BL_CDP_PORT" > "$BL_LAUNCH_DIR/agent/cdp-port"
|
||||
[ "$steam_x64" = 1 ] || { "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 & }
|
||||
if [ "$steam_x64" = 1 ]; then
|
||||
{ droiddeck-steam-compat --files-only "$steam_root" 2>&1 & }
|
||||
else
|
||||
{ "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 & }
|
||||
fi
|
||||
_bl_ui=(-gamepadui)
|
||||
[ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=()
|
||||
_bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle=vulkan)
|
||||
|
||||
@@ -620,10 +620,11 @@ class Watcher:
|
||||
|
||||
|
||||
class Helper:
|
||||
def __init__(self, steam_root, port, steamos=False):
|
||||
def __init__(self, steam_root, port, steamos=False, files_only=False):
|
||||
self.steam_root = steam_root
|
||||
self.port = port
|
||||
self.steamos = steamos
|
||||
self.files_only = files_only
|
||||
self.page = None
|
||||
self.known = set()
|
||||
self.installed = None
|
||||
@@ -647,9 +648,14 @@ class Helper:
|
||||
self.finish_chooser(ident, None)
|
||||
return
|
||||
command = [sys.executable, os.path.realpath(__file__), "--choose-file"]
|
||||
reaper = os.path.join(self.steam_root, "steamrtarm64", "reaper")
|
||||
if os.access(reaper, os.X_OK):
|
||||
command = [reaper, "SteamLaunch", "AppId=769", "--"] + command
|
||||
# Gamescope shows the dialog over the client by the AppId on a reaper above it; the x86-64 client has no
|
||||
# native reaper, so the arm64 client's is borrowed when it is installed.
|
||||
data = os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share")
|
||||
for root in (self.steam_root, os.path.join(data, "Steam")):
|
||||
reaper = os.path.join(root, "steamrtarm64", "reaper")
|
||||
if os.access(reaper, os.X_OK):
|
||||
command = [reaper, "SteamLaunch", "AppId=769", "--"] + command
|
||||
break
|
||||
try:
|
||||
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL, start_new_session=True)
|
||||
@@ -699,6 +705,11 @@ class Helper:
|
||||
try:
|
||||
if page.evaluate("typeof SteamClient === 'object' && typeof SteamClient.WebUITransport === 'object'") is not True:
|
||||
raise LookupError("SteamClient is not ready")
|
||||
if self.files_only:
|
||||
page.call("Runtime.addBinding", {"name": FILE_BINDING})
|
||||
page.evaluate(FILE_JS)
|
||||
self.page = page
|
||||
return True
|
||||
page.call("Runtime.addBinding", {"name": BINDING})
|
||||
page.call("Runtime.addBinding", {"name": VR_BINDING})
|
||||
page.evaluate(VR_JS)
|
||||
@@ -847,7 +858,22 @@ class Helper:
|
||||
self.open_chooser(e["params"]["payload"])
|
||||
return events
|
||||
|
||||
def serve_files(self):
|
||||
say("attached to the client on port %d for its file dialogs" % self.port)
|
||||
while True:
|
||||
sources = [self.page.ws] + ([self.chooser[1].stdout] if self.chooser is not None else [])
|
||||
queued = self.page.ws.pending() or bool(self.page.events)
|
||||
ready = [self.page.ws] if queued else select.select(sources, [], [], 30)[0]
|
||||
if self.chooser is not None and self.chooser[1].stdout in ready:
|
||||
self.chooser_done()
|
||||
if self.page.ws in ready or self.page.events:
|
||||
for e in self.page.drain():
|
||||
if called(e, FILE_BINDING) and isinstance(e.get("params", {}).get("payload"), str):
|
||||
self.open_chooser(e["params"]["payload"])
|
||||
|
||||
def serve(self, watcher):
|
||||
if self.files_only:
|
||||
return self.serve_files()
|
||||
with open(COMPAT["state_path"]("live.pid"), "w") as f:
|
||||
f.write("%d\n" % os.getpid())
|
||||
say("attached to the client on port %d" % self.port)
|
||||
@@ -903,12 +929,29 @@ def chooser_main():
|
||||
|
||||
|
||||
def main():
|
||||
steam_root = sys.argv[1]
|
||||
files_only = sys.argv[1:2] == ["--files-only"]
|
||||
steam_root = sys.argv[2 if files_only else 1]
|
||||
try:
|
||||
port = int(os.environ.get("BL_CDP_PORT", ""))
|
||||
except ValueError:
|
||||
say("no devtools port for this session; the client's mapping is kept through config.vdf")
|
||||
return 0
|
||||
if files_only:
|
||||
helper = Helper(steam_root, port, files_only=True)
|
||||
failures = 0
|
||||
while True:
|
||||
try:
|
||||
helper.attach()
|
||||
failures = 0
|
||||
helper.serve(None)
|
||||
except Exception as e:
|
||||
helper.close_chooser()
|
||||
if helper.page is not None:
|
||||
say("lost the client (%s); reattaching" % e)
|
||||
helper.page.ws.close()
|
||||
helper.page = None
|
||||
failures += 1
|
||||
time.sleep(min(2 * max(failures, 1), 10))
|
||||
os.makedirs(COMPAT["COMPAT_DIR"], exist_ok=True)
|
||||
watcher = Watcher([COMPAT["state_path"]("request.json"), COMPAT["state_path"]("games.json")] +
|
||||
[os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")])
|
||||
@@ -943,4 +986,5 @@ if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
finally:
|
||||
detach()
|
||||
if sys.argv[1:2] != ["--files-only"]:
|
||||
detach()
|
||||
@@ -25,6 +25,8 @@ Android: an EOS sign-in step that falls back to a browser (a consent Epic asks f
|
||||
is finished there. An EOS overlay pointer (HKCU\Software\Epic Games\EOS "OverlayPath") an earlier
|
||||
build wrote is removed - with it the game exited while loading.
|
||||
|
||||
Battle.net.exe in Battle.net's prefix is handed to droiddeck-battlenet, which runs the whole launch.
|
||||
|
||||
droiddeck-store-launch <the arguments Steam gave the compat tool>
|
||||
"""
|
||||
|
||||
@@ -291,6 +293,27 @@ def create_prefix(compat_data, proton, timeout=120):
|
||||
CLOUD_TIMEOUT = 15.0
|
||||
CLOUD_STORES = ("gog", "epic")
|
||||
STORE_GAME = 10
|
||||
RAN = 11
|
||||
RAN_FAILED = 12
|
||||
BATTLENET = "/usr/local/bin/droiddeck-battlenet"
|
||||
BATTLENET_EXE = re.compile(r"(?i)/compatdata/2596113170/pfx/drive_c/Program Files \(x86\)/Battle\.net/Battle\.net\.exe$")
|
||||
BATTLENET_LAUNCH = re.compile(r'(?i)^--exec=\s*"?launch\s+([A-Za-z0-9_]{1,16})"?$')
|
||||
|
||||
|
||||
def battlenet(argv, env=os.environ):
|
||||
if env.get("BL_BATTLENET"):
|
||||
return None
|
||||
exe, code = False, None
|
||||
for raw in argv:
|
||||
arg = raw.strip().strip('"').strip("'")
|
||||
if BATTLENET_EXE.search(arg.replace("\\", "/")):
|
||||
exe = True
|
||||
found = BATTLENET_LAUNCH.match(arg)
|
||||
if found:
|
||||
code = found.group(1)
|
||||
if not exe:
|
||||
return None
|
||||
return [BATTLENET, "launch", code] if code else [BATTLENET, "open"]
|
||||
|
||||
|
||||
def cloud_on(sidecar):
|
||||
@@ -511,6 +534,10 @@ def main(argv):
|
||||
pass
|
||||
rest = rest[2:]
|
||||
return exited(rest, code)
|
||||
command = battlenet(argv)
|
||||
if command is not None:
|
||||
log("battlenet " + " ".join(command[1:]))
|
||||
return RAN if subprocess.call(command) == 0 else RAN_FAILED
|
||||
found = find_store_game(argv)
|
||||
if found is None:
|
||||
return 0
|
||||
|
||||
@@ -69,7 +69,10 @@ bl_store_launch() {
|
||||
fi
|
||||
[ -x /usr/local/bin/droiddeck-store-launch ] || return 0
|
||||
/usr/local/bin/droiddeck-store-launch "$@"
|
||||
[ $? -eq 10 ] && BL_STORE_EXIT=1
|
||||
rc=$?
|
||||
[ $rc -eq 10 ] && BL_STORE_EXIT=1
|
||||
[ $rc -eq 11 ] && exit 0
|
||||
[ $rc -eq 12 ] && exit 1
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -87,6 +90,34 @@ bl_run() {
|
||||
}
|
||||
"""
|
||||
|
||||
BL_DESKTOP_GPU_SETUP = """
|
||||
bl_desktop_gpu() {
|
||||
local name saved gpu=/usr/local/bin/droiddeck-gpu
|
||||
local names=(LD_PRELOAD LD_LIBRARY_PATH ENABLE_VK_LAYER_VALVE_steam_overlay_1 ENABLE_VK_LAYER_VALVE_steam_fossilize_1)
|
||||
if [ -n "${BL_DESKTOP_GPU_CHILD:-}" ]; then
|
||||
for name in "${names[@]}"; do
|
||||
saved=BL_GPU_SAVED_$name
|
||||
[ -n "${!saved+x}" ] || continue
|
||||
export "$name=${!saved}"
|
||||
unset "$saved"
|
||||
done
|
||||
return 0
|
||||
fi
|
||||
[ "${BL_DESKTOP:-}" = 1 ] && [ "${verb:-}" = waitforexitandrun ] && [ -x "$gpu" ] || return 0
|
||||
local choice=${BL_DESKTOP_GPU:-on}
|
||||
case "${choice,,}" in off | 0 | no | false) return 0 ;; esac
|
||||
case " $* " in *iscriptevaluator*) return 0 ;; esac
|
||||
local clear=()
|
||||
for name in "${names[@]}"; do
|
||||
[ -n "${!name+x}" ] || continue
|
||||
export "BL_GPU_SAVED_$name=${!name}"
|
||||
clear+=(-u "$name")
|
||||
done
|
||||
echo "droiddeck-gpu: the desktop starts this game on the GPU" >&2
|
||||
exec env "${clear[@]}" "$gpu" "$0" "$verb" "$@"
|
||||
}
|
||||
bl_desktop_gpu "$@"
|
||||
"""
|
||||
BL_COMPONENTS_SETUP = """
|
||||
bl_components() {
|
||||
base=$1
|
||||
@@ -377,7 +408,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
|
||||
|
||||
def launcher_sh(sources=SOURCES):
|
||||
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
|
||||
"verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
"verb=$1; shift", "verb=$1; shift\n" + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
|
||||
|
||||
|
||||
@@ -466,7 +497,7 @@ verb=$1; shift
|
||||
case $verb in
|
||||
getcompatpath | getnativepath) printf '%s\\n' "$1"; exit 0 ;;
|
||||
esac
|
||||
""" + BL_GAME_CPUS_SETUP + """
|
||||
""" + BL_DESKTOP_GPU_SETUP + BL_GAME_CPUS_SETUP + """
|
||||
bl_game_cpus
|
||||
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "$verb"; then
|
||||
exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@"
|
||||
@@ -649,7 +680,7 @@ def adopt_extras(tools):
|
||||
try:
|
||||
body = (EXTRA_WRAPPER_SH % entry_point).replace(
|
||||
'here=$(dirname "$0")',
|
||||
'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
'here=$(dirname "$0")\n' + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP
|
||||
+ BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1)
|
||||
write_changed(wrapper, body, 0o755)
|
||||
write_changed(manifest, EXTRA_MANIFEST_VDF)
|
||||
@@ -1219,6 +1250,32 @@ def requested_games(requests, catalog, runnable=None):
|
||||
return resolved
|
||||
|
||||
|
||||
OWN_PROTON = "DroidDeck-Proton"
|
||||
ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64")
|
||||
|
||||
|
||||
def own_builds(tools):
|
||||
return [t for t in tools if isinstance(t, dict) and not t.get("valve") and
|
||||
isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")]
|
||||
|
||||
|
||||
def build_key(name):
|
||||
return [int(n) for n in re.findall(r"\d+", ARCH_WORDS.sub(" ", name))]
|
||||
|
||||
|
||||
def own_proton_moves(state, catalog):
|
||||
names = {t["name"] for t in catalog}
|
||||
before = state.get("tools") if isinstance(state.get("tools"), list) else ()
|
||||
seen = state.get("own_builds") if isinstance(state.get("own_builds"), list) else []
|
||||
known = {n for n in seen if isinstance(n, str)} | {t["name"] for t in own_builds(before)} | {t["name"] for t in own_builds(catalog)}
|
||||
state["own_builds"] = sorted(known)
|
||||
builds = own_builds(catalog)
|
||||
if not builds:
|
||||
return None, set()
|
||||
newest = max(builds, key=lambda t: (build_key(t["dir"]), t["dir"]))["name"]
|
||||
return newest, known - names
|
||||
|
||||
|
||||
def now_ms():
|
||||
import time
|
||||
return int(time.time() * 1000)
|
||||
@@ -1379,11 +1436,26 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
|
||||
catalog = tool_catalog(os.path.dirname(os.path.dirname(os.path.abspath(config_path))),
|
||||
dict(protect) if isinstance(protect, dict) else {name: name for name in protect})
|
||||
names = [t["name"] for t in catalog]
|
||||
newest, gone = own_proton_moves(state, catalog)
|
||||
previous, applied, chosen = state.get("default"), state.get("applied"), state.get("seq")
|
||||
if default is None:
|
||||
if settle:
|
||||
default, state = choose_default(current.get("0", ""), state, read_json(state_path("request.json", directory)), catalog)
|
||||
else:
|
||||
default = state.get("default") if state.get("default") in names else TOOL
|
||||
if settle and newest and default == TOOL and state.get("applied") == applied and state.get("seq") == chosen and (
|
||||
previous in gone or not state.get("own_proton")):
|
||||
default = newest
|
||||
state.update(default=newest, seq=now_ms(), source="update")
|
||||
if settle and newest:
|
||||
state["own_proton"] = True
|
||||
if newest:
|
||||
for app, name in list(current.items()):
|
||||
if app != "0" and name in gone:
|
||||
set_mapping(tokens, mapping, app, newest)
|
||||
current[app] = newest
|
||||
if isinstance(state.get("auto"), dict):
|
||||
state["auto"] = {app: newest if name in gone else name for app, name in state["auto"].items()}
|
||||
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
|
||||
requests = settled_game_requests(state, current, catalog, not steam_running(), directory)
|
||||
overrides = requested_games(requests or {}, catalog)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# Published proot pack for a build that did not compile libproot.so into the APK.
|
||||
# CI builds embed the binary and publish their own pack; this pin is what a source
|
||||
# build downloads. Tag on DroidDeck-Components: pack-proot-<first 16 hex of the digest>.
|
||||
# Update both lines when source builds should pick up a newer proot.
|
||||
PROOT_PACK_SHA256=5a2b7284e6357f88a14a790abd54e61effbe5f202c63b6aaba9b974c559649c3
|
||||
PROOT_PACK_SIZE=96643
|
||||
@@ -124,3 +124,11 @@ Old kernel fixes:
|
||||
by the kernel instead. The original clone flags are preserved. When the kernel supplies a valid
|
||||
ID in the notification, normal setup is unchanged. No timers or background polling are added.
|
||||
Completely missing notifications and ambiguous matches for separate processes are not recovered.
|
||||
|
||||
Development diagnostics:
|
||||
|
||||
- `0018-syscall-handler-profile.patch` - `PROOT_PROFILE=1` enables per-syscall entry/exit handler
|
||||
counts, wall/CPU time, periodic cumulative JSON totals, and bounded slow-handler samples on
|
||||
stderr. `profile.h` is copied into the source tree by `build.sh`. It adds no ptrace stops;
|
||||
handler timing excludes tracee kernel time and scheduling before handler entry. See
|
||||
`docs/development/proot-performance.md` for the capture and library-override workflow.
|
||||
@@ -31,6 +31,7 @@ fetch() {
|
||||
fetch proot.tar.gz "https://github.com/termux/proot/archive/${PROOT_COMMIT}.tar.gz" "$PROOT_SHA256"
|
||||
fetch talloc.tar.gz "https://www.samba.org/ftp/talloc/talloc-${TALLOC_VERSION}.tar.gz" "$TALLOC_SHA256"
|
||||
cp "$HERE/statx_mnt_id.h" "$WORK/proot/src/tracee/statx_mnt_id.h"
|
||||
cp "$HERE/profile.h" "$WORK/proot/src/syscall/profile.h"
|
||||
for patch in "$HERE"/patches/*.patch; do
|
||||
patch -d "$WORK/proot" -p1 --forward --quiet < "$patch"
|
||||
done
|
||||
|
||||
@@ -875,19 +875,84 @@ int __fxstat(int ver, int fd, struct stat *st) {
|
||||
}
|
||||
int __fxstat64(int ver, int fd, struct stat64 *st) { return __fxstat(ver, fd, (struct stat *)st); }
|
||||
|
||||
#ifndef STATX__RESERVED
|
||||
#define STATX__RESERVED 0x80000000U
|
||||
#endif
|
||||
|
||||
static int statx_missing;
|
||||
|
||||
static unsigned int dev_major(unsigned long long dev) {
|
||||
return ((dev >> 8) & 0xfff) | ((unsigned int)(dev >> 32) & ~0xfffU);
|
||||
}
|
||||
static unsigned int dev_minor(unsigned long long dev) {
|
||||
return (dev & 0xff) | ((unsigned int)(dev >> 12) & ~0xffU);
|
||||
}
|
||||
|
||||
static void fill_statx(struct statx *out, const struct stat *st) {
|
||||
memset(out, 0, sizeof *out);
|
||||
out->stx_mask = STATX_BASIC_STATS;
|
||||
out->stx_blksize = st->st_blksize;
|
||||
out->stx_nlink = st->st_nlink;
|
||||
out->stx_uid = st->st_uid;
|
||||
out->stx_gid = st->st_gid;
|
||||
out->stx_mode = st->st_mode;
|
||||
out->stx_ino = st->st_ino;
|
||||
out->stx_size = st->st_size;
|
||||
out->stx_blocks = st->st_blocks;
|
||||
out->stx_atime.tv_sec = st->st_atim.tv_sec;
|
||||
out->stx_atime.tv_nsec = st->st_atim.tv_nsec;
|
||||
out->stx_ctime.tv_sec = st->st_ctim.tv_sec;
|
||||
out->stx_ctime.tv_nsec = st->st_ctim.tv_nsec;
|
||||
out->stx_mtime.tv_sec = st->st_mtim.tv_sec;
|
||||
out->stx_mtime.tv_nsec = st->st_mtim.tv_nsec;
|
||||
out->stx_rdev_major = dev_major(st->st_rdev);
|
||||
out->stx_rdev_minor = dev_minor(st->st_rdev);
|
||||
out->stx_dev_major = dev_major(st->st_dev);
|
||||
out->stx_dev_minor = dev_minor(st->st_dev);
|
||||
}
|
||||
|
||||
/* Emulate statx on older kernels < 4.11 */
|
||||
static long statx_call(int dirfd, const char *path, int flags, unsigned mask, struct statx *out) {
|
||||
struct stat st;
|
||||
long rs;
|
||||
if ((flags & ~(AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT | AT_STATX_SYNC_TYPE)) ||
|
||||
(flags & AT_STATX_SYNC_TYPE) == AT_STATX_SYNC_TYPE)
|
||||
return -EINVAL;
|
||||
if (!statx_missing) {
|
||||
rs = sc(SYS_statx, dirfd, (long)path, flags, mask, (long)out);
|
||||
if (rs != -ENOSYS) return rs;
|
||||
statx_missing = 1;
|
||||
}
|
||||
if (flags & AT_STATX_SYNC_TYPE) return -ENOSYS;
|
||||
rs = sc(SYS_newfstatat, dirfd, (long)path, (long)&st,
|
||||
flags & (AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT), 0);
|
||||
if (rs < 0) return rs;
|
||||
fill_statx(out, &st);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *out) {
|
||||
REAL(statx, int (*)(int, const char *, int, unsigned, struct statx *));
|
||||
struct res r;
|
||||
long rs;
|
||||
if (mask & STATX__RESERVED) { errno = EINVAL; return -1; }
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wnonnull-compare"
|
||||
if (!out) { errno = EFAULT; return -1; }
|
||||
if (!path) {
|
||||
if (!(flags & AT_EMPTY_PATH)) { errno = EFAULT; return -1; }
|
||||
return real_statx ? real_statx(dirfd, path, flags, mask, out) : ret(sc(SYS_statx, dirfd, (long)path, flags, mask, (long)out));
|
||||
}
|
||||
#pragma GCC diagnostic pop
|
||||
if ((flags & AT_EMPTY_PATH) && !path[0] && fp_ready()) {
|
||||
hits++;
|
||||
return ret(sc(SYS_statx, dirfd, (long)"", flags, mask, (long)out));
|
||||
return ret(statx_call(dirfd, "", flags, mask, out));
|
||||
}
|
||||
rs = (flags & ~(AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT | AT_STATX_SYNC_TYPE)) ? FP_SLOW
|
||||
: resolve(dirfd, path, (flags & AT_SYMLINK_NOFOLLOW ? 0 : 1) | MAY_BE_UNSEEN, &r);
|
||||
if (rs == 1) rs = -ENOENT;
|
||||
if (rs == 0 || rs == UNSEEN)
|
||||
rs = sc(SYS_statx, AT_FDCWD, (long)r.host, flags | (rs == 0 && !r.magic ? AT_SYMLINK_NOFOLLOW : 0), mask, (long)out);
|
||||
rs = statx_call(AT_FDCWD, r.host, flags | (rs == 0 && !r.magic ? AT_SYMLINK_NOFOLLOW : 0), mask, out);
|
||||
ANSWER(rs, dirfd, path, real_statx(dirfd, path, flags, mask, out));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
--- a/src/syscall/syscall.c
|
||||
+++ b/src/syscall/syscall.c
|
||||
@@ -32,6 +32,7 @@
|
||||
#include "tracee/reg.h"
|
||||
#include "tracee/mem.h"
|
||||
#include "cli/note.h"
|
||||
+#include "syscall/profile.h"
|
||||
|
||||
/**
|
||||
* Copy in @path a C string (PATH_MAX bytes max.) from the @tracee's
|
||||
@@ -100,7 +101,7 @@
|
||||
return set_sysarg_data(tracee, path, strlen(path) + 1, reg);
|
||||
}
|
||||
|
||||
-void translate_syscall(Tracee *tracee)
|
||||
+static void translate_syscall_impl(Tracee *tracee)
|
||||
{
|
||||
const bool is_enter_stage = IS_IN_SYSENTER(tracee);
|
||||
int status;
|
||||
@@ -283,3 +284,18 @@
|
||||
else
|
||||
print_current_regs(tracee, 4, "sysexit end");
|
||||
}
|
||||
+
|
||||
+void translate_syscall(Tracee *tracee)
|
||||
+{
|
||||
+ if (!dd_profile_enabled()) {
|
||||
+ translate_syscall_impl(tracee);
|
||||
+ return;
|
||||
+ }
|
||||
+ int saved = errno;
|
||||
+ const bool entering = IS_IN_SYSENTER(tracee);
|
||||
+ uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC);
|
||||
+ uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID);
|
||||
+ errno = saved;
|
||||
+ translate_syscall_impl(tracee);
|
||||
+ dd_profile_record(get_sysnum(tracee, ORIGINAL), entering, tracee->pid, wall, cpu);
|
||||
+}
|
||||
@@ -0,0 +1,99 @@
|
||||
/* SPDX-License-Identifier: GPL-2.0-or-later */
|
||||
#ifndef DROIDDECK_PROOT_PROFILE_H
|
||||
#define DROIDDECK_PROOT_PROFILE_H
|
||||
|
||||
#include <errno.h>
|
||||
#include <inttypes.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
struct dd_profile_counter {
|
||||
uint64_t calls, wall_ns, cpu_ns, max_ns;
|
||||
};
|
||||
static struct dd_profile_counter dd_profile_counts[PR_NB_SYSNUM][2];
|
||||
static int dd_profile_on = -1;
|
||||
static uint64_t dd_profile_id, dd_profile_next, dd_profile_slow_ns = 1000000;
|
||||
static unsigned dd_profile_samples;
|
||||
|
||||
static uint64_t dd_profile_clock(clockid_t clock)
|
||||
{
|
||||
struct timespec ts;
|
||||
if (clock_gettime(clock, &ts) != 0) return 0;
|
||||
return (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
|
||||
}
|
||||
|
||||
static void dd_profile_flush(void)
|
||||
{
|
||||
int saved = errno;
|
||||
for (unsigned nr = 0; nr < PR_NB_SYSNUM; nr++) {
|
||||
for (unsigned stage = 0; stage < 2; stage++) {
|
||||
const struct dd_profile_counter *c = &dd_profile_counts[nr][stage];
|
||||
if (!c->calls) continue;
|
||||
fprintf(stderr, "proot-profile {\"type\":\"total\",\"tracer\":%d,\"id\":%" PRIu64
|
||||
",\"syscall\":\"%s\",\"stage\":\"%s\",\"calls\":%" PRIu64
|
||||
",\"wall_ns\":%" PRIu64 ",\"cpu_ns\":%" PRIu64 ",\"max_ns\":%" PRIu64 "}\n",
|
||||
getpid(), dd_profile_id, stringify_sysnum(nr), stage ? "exit" : "enter",
|
||||
c->calls, c->wall_ns, c->cpu_ns, c->max_ns);
|
||||
}
|
||||
}
|
||||
errno = saved;
|
||||
}
|
||||
|
||||
static int dd_profile_enabled(void)
|
||||
{
|
||||
if (dd_profile_on >= 0) return dd_profile_on;
|
||||
int saved = errno;
|
||||
const char *value = getenv("PROOT_PROFILE");
|
||||
dd_profile_on = value && strcmp(value, "1") == 0;
|
||||
if (dd_profile_on) {
|
||||
value = getenv("PROOT_PROFILE_SLOW_US");
|
||||
if (value && *value) {
|
||||
char *end;
|
||||
unsigned long long us = strtoull(value, &end, 10);
|
||||
if (!*end && us > 0 && us <= 1000000000ULL) dd_profile_slow_ns = us * 1000;
|
||||
}
|
||||
dd_profile_id = dd_profile_clock(CLOCK_MONOTONIC);
|
||||
dd_profile_next = dd_profile_id + 5000000000ULL;
|
||||
atexit(dd_profile_flush);
|
||||
fprintf(stderr, "proot-profile {\"type\":\"start\",\"tracer\":%d,\"id\":%" PRIu64
|
||||
",\"slow_ns\":%" PRIu64 ",\"sample_limit\":32,\"sample_window_ms\":5000,\"scope\":\"syscall-handler\"}\n",
|
||||
getpid(), dd_profile_id, dd_profile_slow_ns);
|
||||
}
|
||||
errno = saved;
|
||||
return dd_profile_on;
|
||||
}
|
||||
|
||||
static void dd_profile_record(unsigned nr, int entering, pid_t pid,
|
||||
uint64_t start_wall, uint64_t start_cpu)
|
||||
{
|
||||
int saved = errno;
|
||||
uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID);
|
||||
uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC);
|
||||
if (nr >= PR_NB_SYSNUM) nr = PR_void;
|
||||
if (!start_wall || !start_cpu || wall < start_wall || cpu < start_cpu) goto done;
|
||||
uint64_t elapsed = wall - start_wall, used = cpu - start_cpu;
|
||||
struct dd_profile_counter *c = &dd_profile_counts[nr][!entering];
|
||||
c->calls++;
|
||||
c->wall_ns += elapsed;
|
||||
c->cpu_ns += used;
|
||||
if (elapsed > c->max_ns) c->max_ns = elapsed;
|
||||
if (wall >= dd_profile_next) {
|
||||
dd_profile_flush();
|
||||
dd_profile_next = wall + 5000000000ULL;
|
||||
dd_profile_samples = 0;
|
||||
}
|
||||
if (elapsed >= dd_profile_slow_ns && dd_profile_samples < 32) {
|
||||
dd_profile_samples++;
|
||||
fprintf(stderr, "proot-profile {\"type\":\"slow\",\"tracer\":%d,\"id\":%" PRIu64
|
||||
",\"pid\":%d,\"syscall\":\"%s\",\"stage\":\"%s\",\"wall_ns\":%" PRIu64
|
||||
",\"cpu_ns\":%" PRIu64 "}\n", getpid(), dd_profile_id, pid,
|
||||
stringify_sysnum(nr), entering ? "enter" : "exit", elapsed, used);
|
||||
}
|
||||
done:
|
||||
errno = saved;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Read cumulative PRoot handler counters from a session log without double counting snapshots."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections import deque
|
||||
from pathlib import Path
|
||||
|
||||
PREFIX = "proot-profile "
|
||||
|
||||
|
||||
def report(path: Path, sort: str = "wall", limit: int = 20) -> dict:
|
||||
latest = {}
|
||||
starts = set()
|
||||
samples = deque(maxlen=128)
|
||||
malformed = 0
|
||||
with path.open(errors="replace") as stream:
|
||||
for line in stream:
|
||||
if PREFIX not in line:
|
||||
continue
|
||||
try:
|
||||
row = json.loads(line.split(PREFIX, 1)[1])
|
||||
identity = (int(row["tracer"]), int(row["id"]))
|
||||
if row["type"] == "start":
|
||||
starts.add(identity)
|
||||
elif row["type"] in {"total", "slow"}:
|
||||
if row["stage"] not in {"enter", "exit"} or not isinstance(row["syscall"], str):
|
||||
raise ValueError("invalid syscall/stage")
|
||||
fields = ("calls", "wall_ns", "cpu_ns", "max_ns") if row["type"] == "total" else ("wall_ns", "cpu_ns", "pid")
|
||||
if any(type(row[key]) is not int or row[key] < 0 for key in fields):
|
||||
raise ValueError("invalid counter")
|
||||
if row["type"] == "total":
|
||||
latest[identity + (row["syscall"], row["stage"])] = row
|
||||
else:
|
||||
samples.append(row)
|
||||
except (ValueError, TypeError, KeyError):
|
||||
malformed += 1
|
||||
groups = {}
|
||||
for (_, _, syscall, stage), row in latest.items():
|
||||
total = groups.setdefault((syscall, stage), dict(syscall=syscall, stage=stage, calls=0, wall_ns=0, cpu_ns=0, max_ns=0))
|
||||
for key in ("calls", "wall_ns", "cpu_ns"):
|
||||
total[key] += row[key]
|
||||
total["max_ns"] = max(total["max_ns"], row["max_ns"])
|
||||
for row in groups.values():
|
||||
row["wallMs"] = round(row["wall_ns"] / 1_000_000, 3)
|
||||
row["cpuMs"] = round(row["cpu_ns"] / 1_000_000, 3)
|
||||
row["meanUs"] = round(row["wall_ns"] / max(row["calls"], 1) / 1000, 3)
|
||||
row["maxUs"] = round(row["max_ns"] / 1000, 3)
|
||||
rows = sorted(groups.values(), key=lambda row: row[{"wall": "wall_ns", "cpu": "cpu_ns", "calls": "calls"}[sort]], reverse=True)
|
||||
return dict(ok=True, command="proot-profile", scope="syscall-handler",
|
||||
note="Handler wall time includes tracer descheduling and filesystem waits; it excludes tracee kernel time and wake-up/queue delay before the handler. Counts are handler visits, including chained calls, not unique syscalls.",
|
||||
path=str(path), tracers=len(starts | {key[:2] for key in latest}),
|
||||
handlerCalls=sum(row["calls"] for row in rows),
|
||||
handlerWallNs=sum(row["wall_ns"] for row in rows),
|
||||
handlerCpuNs=sum(row["cpu_ns"] for row in rows),
|
||||
malformedRecords=malformed, totals=rows[:limit], slowSamples=list(samples),
|
||||
hasCounters=bool(latest))
|
||||
@@ -0,0 +1,359 @@
|
||||
#include "framegen.hpp"
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int levels = 7;
|
||||
constexpr VkImageUsageFlags flow_usage =
|
||||
VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
||||
enum Pipeline { LUMA, DOWNSAMPLE, FLOW3, FLOW4, EXPAND3, EXPAND4, GLOBAL_MOTION, PREWARP, FLOW_REG, SYNTH };
|
||||
struct Image { VkExtent3D extent; VkFormat format; VkImageUsageFlags usage; };
|
||||
struct Allocation { VkDeviceSize size; std::unique_ptr<uint8_t[]> data; };
|
||||
struct Binding { VkDescriptorType type; VkImageView view; VkBuffer buffer; VkDeviceSize range; };
|
||||
struct Dispatch { unsigned pipeline; uint32_t x, y, z; };
|
||||
std::map<VkImage, Image> images;
|
||||
std::map<VkImageView, VkImage> views;
|
||||
std::map<VkBuffer, VkBufferCreateInfo> buffers;
|
||||
std::map<VkDeviceMemory, Allocation> allocations;
|
||||
std::map<VkBuffer, VkDeviceMemory> buffer_memory;
|
||||
std::map<VkDescriptorSet, std::map<uint32_t, Binding>> descriptors;
|
||||
std::map<VkPipeline, unsigned> pipelines;
|
||||
std::map<VkImage, unsigned> image_ids;
|
||||
std::map<VkBuffer, unsigned> buffer_ids;
|
||||
std::vector<Dispatch> dispatches;
|
||||
uintptr_t serial = 100;
|
||||
unsigned buffer_creates, set_creates;
|
||||
VkPipeline bound_pipeline;
|
||||
VkDescriptorSet bound_set;
|
||||
uint64_t command_hash = 14695981039346656037ull;
|
||||
|
||||
template<class T> T handle() { return reinterpret_cast<T>(++serial); }
|
||||
|
||||
void hash(uint64_t value) {
|
||||
for (unsigned i = 0; i < 8; i++) {
|
||||
command_hash = (command_hash ^ (value & 255)) * 1099511628211ull;
|
||||
value >>= 8;
|
||||
}
|
||||
}
|
||||
|
||||
void hash_image(VkImage image) {
|
||||
assert(images.count(image));
|
||||
if (!image_ids.count(image)) image_ids[image] = static_cast<unsigned>(image_ids.size() + 1);
|
||||
const auto &info = images.at(image);
|
||||
hash(image_ids.at(image));
|
||||
hash(info.extent.width); hash(info.extent.height); hash(info.format); hash(info.usage);
|
||||
}
|
||||
|
||||
template<class Info, class Out>
|
||||
VkResult VKAPI_CALL create(VkDevice, const Info *, const VkAllocationCallbacks *, Out *out) {
|
||||
*out = handle<Out>();
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
template<class T> void VKAPI_CALL destroy(VkDevice, T, const VkAllocationCallbacks *) {}
|
||||
|
||||
VkResult VKAPI_CALL create_image(VkDevice, const VkImageCreateInfo *info,
|
||||
const VkAllocationCallbacks *, VkImage *out) {
|
||||
*out = handle<VkImage>();
|
||||
images[*out] = {info->extent, info->format, info->usage};
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
VkResult VKAPI_CALL create_view(VkDevice, const VkImageViewCreateInfo *info,
|
||||
const VkAllocationCallbacks *, VkImageView *out) {
|
||||
assert(images.count(info->image));
|
||||
*out = handle<VkImageView>();
|
||||
views[*out] = info->image;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
void VKAPI_CALL destroy_image(VkDevice, VkImage image, const VkAllocationCallbacks *) {
|
||||
assert(images.erase(image) == 1);
|
||||
}
|
||||
void VKAPI_CALL destroy_view(VkDevice, VkImageView view, const VkAllocationCallbacks *) {
|
||||
assert(views.erase(view) == 1);
|
||||
}
|
||||
VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo *info,
|
||||
const VkAllocationCallbacks *, VkBuffer *out) {
|
||||
*out = handle<VkBuffer>();
|
||||
buffers[*out] = *info;
|
||||
buffer_creates++;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks *) {
|
||||
assert(buffers.erase(buffer) == 1);
|
||||
buffer_memory.erase(buffer);
|
||||
}
|
||||
void VKAPI_CALL image_requirements(VkDevice, VkImage image, VkMemoryRequirements *out) {
|
||||
const auto &info = images.at(image);
|
||||
const uint64_t bytes = info.format == VK_FORMAT_R32_SFLOAT ? 4 : 8;
|
||||
*out = {uint64_t(info.extent.width) * info.extent.height * bytes, 1, 1};
|
||||
}
|
||||
void VKAPI_CALL buffer_requirements(VkDevice, VkBuffer buffer, VkMemoryRequirements *out) {
|
||||
*out = {buffers.at(buffer).size, 1, 1};
|
||||
}
|
||||
VkResult VKAPI_CALL allocate(VkDevice, const VkMemoryAllocateInfo *info,
|
||||
const VkAllocationCallbacks *, VkDeviceMemory *out) {
|
||||
*out = handle<VkDeviceMemory>();
|
||||
allocations[*out].size = info->allocationSize;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks *) {
|
||||
assert(allocations.erase(memory) == 1);
|
||||
}
|
||||
VkResult VKAPI_CALL bind_image(VkDevice, VkImage image, VkDeviceMemory memory, VkDeviceSize) {
|
||||
assert(images.count(image) && allocations.count(memory));
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
VkResult VKAPI_CALL bind_buffer(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) {
|
||||
assert(buffers.count(buffer) && allocations.count(memory));
|
||||
buffer_memory[buffer] = memory;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
VkResult VKAPI_CALL map_memory(VkDevice, VkDeviceMemory memory, VkDeviceSize offset,
|
||||
VkDeviceSize size, VkMemoryMapFlags, void **out) {
|
||||
auto &allocation = allocations.at(memory);
|
||||
assert(offset == 0 && size <= allocation.size);
|
||||
allocation.data = std::make_unique<uint8_t[]>(allocation.size);
|
||||
*out = allocation.data.get();
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
void VKAPI_CALL unmap(VkDevice, VkDeviceMemory memory) { assert(allocations.count(memory)); }
|
||||
VkResult VKAPI_CALL idle(VkDevice) { return VK_SUCCESS; }
|
||||
void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProperties *out) {
|
||||
*out = {};
|
||||
out->memoryTypeCount = 1;
|
||||
out->memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
|
||||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
|
||||
}
|
||||
VkResult VKAPI_CALL allocate_sets(VkDevice, const VkDescriptorSetAllocateInfo *info, VkDescriptorSet *out) {
|
||||
for (uint32_t i = 0; i < info->descriptorSetCount; i++) {
|
||||
out[i] = handle<VkDescriptorSet>();
|
||||
descriptors[out[i]] = {};
|
||||
set_creates++;
|
||||
}
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
VkResult VKAPI_CALL reset_pool(VkDevice, VkDescriptorPool, VkDescriptorPoolResetFlags) {
|
||||
descriptors.clear();
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
void VKAPI_CALL update_sets(VkDevice, uint32_t count, const VkWriteDescriptorSet *writes,
|
||||
uint32_t, const VkCopyDescriptorSet *) {
|
||||
for (uint32_t i = 0; i < count; i++) {
|
||||
const auto &write = writes[i];
|
||||
assert(descriptors.count(write.dstSet) && write.descriptorCount == 1);
|
||||
Binding binding{write.descriptorType, VK_NULL_HANDLE, VK_NULL_HANDLE, 0};
|
||||
if (write.pImageInfo) {
|
||||
binding.view = write.pImageInfo->imageView;
|
||||
assert(views.count(binding.view));
|
||||
} else {
|
||||
binding.buffer = write.pBufferInfo->buffer;
|
||||
binding.range = write.pBufferInfo->range;
|
||||
assert(buffers.count(binding.buffer));
|
||||
}
|
||||
descriptors.at(write.dstSet)[write.dstBinding] = binding;
|
||||
}
|
||||
}
|
||||
VkResult VKAPI_CALL create_pipelines(VkDevice, VkPipelineCache, uint32_t count,
|
||||
const VkComputePipelineCreateInfo *, const VkAllocationCallbacks *,
|
||||
VkPipeline *out) {
|
||||
for (uint32_t i = 0; i < count; i++) {
|
||||
const auto index = static_cast<unsigned>(pipelines.size());
|
||||
out[i] = handle<VkPipeline>();
|
||||
pipelines[out[i]] = index;
|
||||
}
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
void VKAPI_CALL bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline pipeline) {
|
||||
assert(pipelines.count(pipeline));
|
||||
bound_pipeline = pipeline;
|
||||
}
|
||||
void VKAPI_CALL bind_sets(VkCommandBuffer, VkPipelineBindPoint, VkPipelineLayout,
|
||||
uint32_t, uint32_t count, const VkDescriptorSet *sets,
|
||||
uint32_t, const uint32_t *) {
|
||||
assert(count == 1 && descriptors.count(sets[0]));
|
||||
bound_set = sets[0];
|
||||
}
|
||||
void VKAPI_CALL dispatch(VkCommandBuffer, uint32_t x, uint32_t y, uint32_t z) {
|
||||
const unsigned pipeline = pipelines.at(bound_pipeline);
|
||||
dispatches.push_back({pipeline, x, y, z});
|
||||
hash(1); hash(pipeline); hash(x); hash(y); hash(z);
|
||||
for (const auto &[slot, binding] : descriptors.at(bound_set)) {
|
||||
hash(slot); hash(binding.type);
|
||||
if (binding.view) {
|
||||
hash_image(views.at(binding.view));
|
||||
} else {
|
||||
if (!buffer_ids.count(binding.buffer))
|
||||
buffer_ids[binding.buffer] = static_cast<unsigned>(buffer_ids.size() + 1);
|
||||
const auto &allocation = allocations.at(buffer_memory.at(binding.buffer));
|
||||
const auto size = binding.range == VK_WHOLE_SIZE ? allocation.size : binding.range;
|
||||
assert(allocation.data && size <= allocation.size);
|
||||
hash(buffer_ids.at(binding.buffer)); hash(size);
|
||||
for (VkDeviceSize i = 0; i < size; i++) hash(allocation.data[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags src, VkPipelineStageFlags dst,
|
||||
VkDependencyFlags flags, uint32_t nm, const VkMemoryBarrier *memory,
|
||||
uint32_t nb, const VkBufferMemoryBarrier *, uint32_t ni,
|
||||
const VkImageMemoryBarrier *image) {
|
||||
assert(nb == 0);
|
||||
hash(2); hash(src); hash(dst); hash(flags); hash(nm); hash(ni);
|
||||
for (uint32_t i = 0; i < nm; i++) {
|
||||
hash(memory[i].srcAccessMask); hash(memory[i].dstAccessMask);
|
||||
}
|
||||
for (uint32_t i = 0; i < ni; i++) {
|
||||
hash_image(image[i].image);
|
||||
hash(image[i].oldLayout); hash(image[i].newLayout);
|
||||
hash(image[i].srcAccessMask); hash(image[i].dstAccessMask);
|
||||
hash(image[i].srcQueueFamilyIndex); hash(image[i].dstQueueFamilyIndex);
|
||||
}
|
||||
}
|
||||
void VKAPI_CALL clear_image(VkCommandBuffer, VkImage image, VkImageLayout layout,
|
||||
const VkClearColorValue *color, uint32_t count, const VkImageSubresourceRange *) {
|
||||
assert(count == 1);
|
||||
hash(3); hash_image(image); hash(layout);
|
||||
for (unsigned i = 0; i < 4; i++) hash(color->uint32[i]);
|
||||
}
|
||||
void VKAPI_CALL copy_image(VkCommandBuffer, VkImage src, VkImageLayout sl, VkImage dst,
|
||||
VkImageLayout dl, uint32_t count, const VkImageCopy *region) {
|
||||
assert(count == 1);
|
||||
hash(4); hash_image(src); hash(sl); hash_image(dst); hash(dl);
|
||||
hash(region->extent.width); hash(region->extent.height); hash(region->extent.depth);
|
||||
}
|
||||
|
||||
uint32_t dimension(uint32_t full, int level) { return std::max(full >> level, 1u); }
|
||||
|
||||
void check_images(uint32_t width, uint32_t height, int finest) {
|
||||
assert(images.size() == static_cast<size_t>(32 - 2 * finest));
|
||||
for (int level = finest; level < levels; level++) {
|
||||
const auto w = dimension(width, level), h = dimension(height, level);
|
||||
assert(std::any_of(images.begin(), images.end(), [=](const auto &entry) {
|
||||
const auto &image = entry.second;
|
||||
return image.format == VK_FORMAT_R16G16B16A16_SFLOAT && image.usage == flow_usage &&
|
||||
image.extent.width == w && image.extent.height == h;
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
VkImageView external_image(uint32_t width, uint32_t height) {
|
||||
VkImage image = handle<VkImage>();
|
||||
VkImageView view = handle<VkImageView>();
|
||||
images[image] = {{width, height, 1}, VK_FORMAT_R8G8B8A8_UNORM,
|
||||
VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT};
|
||||
views[view] = image;
|
||||
return view;
|
||||
}
|
||||
|
||||
void record(ddfg::FrameGen &fg, int model, uint32_t width, uint32_t height, unsigned generations) {
|
||||
const auto previous = external_image(width, height), current = external_image(width, height);
|
||||
const auto first = dispatches.size();
|
||||
for (unsigned i = 0; i < generations; i++)
|
||||
fg.record(reinterpret_cast<VkCommandBuffer>(1), previous, current, external_image(width, height),
|
||||
float(i + 1) / float(generations + 1), 0, i, i != 0);
|
||||
std::vector<Dispatch> expected;
|
||||
auto add = [&](unsigned pipeline, int level) {
|
||||
expected.push_back({pipeline, (dimension(width, level) + 15) / 16,
|
||||
(dimension(height, level) + 15) / 16, 1});
|
||||
};
|
||||
add(LUMA, 0); add(LUMA, 0);
|
||||
for (int level = 1; level < levels; level++) { add(DOWNSAMPLE, level); add(DOWNSAMPLE, level); }
|
||||
expected.push_back({GLOBAL_MOTION, 8, 1, 1});
|
||||
for (int level = fg.flowFinest(); level < levels; level++) add(PREWARP, level);
|
||||
for (int level = levels - 1; level >= fg.flowFinest(); level--) add(model == 4 ? FLOW4 : FLOW3, level);
|
||||
for (int i = 0; i < 4; i++) add(FLOW_REG, fg.flowFinest());
|
||||
add(model == 4 ? EXPAND4 : EXPAND3, 0);
|
||||
for (unsigned i = 0; i < generations; i++) add(SYNTH, 0);
|
||||
assert(dispatches.size() - first == expected.size());
|
||||
for (size_t i = 0; i < expected.size(); i++) {
|
||||
const auto &actual = dispatches[first + i], &want = expected[i];
|
||||
assert(actual.pipeline == want.pipeline && actual.x == want.x && actual.y == want.y && actual.z == want.z);
|
||||
}
|
||||
for (auto it = views.begin(); it != views.end();) {
|
||||
if (images.at(it->second).format == VK_FORMAT_R8G8B8A8_UNORM) {
|
||||
images.erase(it->second);
|
||||
it = views.erase(it);
|
||||
} else ++it;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 8);
|
||||
const std::string mode = argv[1];
|
||||
const int model = std::atoi(argv[2]), preset = std::atoi(argv[3]);
|
||||
uint32_t width = static_cast<uint32_t>(std::atoi(argv[4]));
|
||||
uint32_t height = static_cast<uint32_t>(std::atoi(argv[5]));
|
||||
const unsigned generations = static_cast<unsigned>(std::atoi(argv[6]));
|
||||
const unsigned repeats = static_cast<unsigned>(std::atoi(argv[7]));
|
||||
assert((model == 3 || model == 4) && preset >= 0 && preset <= 2);
|
||||
assert(width && height && generations >= 1 && generations <= 3 && repeats > 0);
|
||||
ddfg::DeviceDispatch dd;
|
||||
ddfg::InstanceDispatch id;
|
||||
id.GetPhysicalDeviceMemoryProperties = memory_properties;
|
||||
dd.CreateImage = create_image; dd.DestroyImage = destroy_image;
|
||||
dd.CreateImageView = create_view; dd.DestroyImageView = destroy_view;
|
||||
dd.CreateBuffer = create_buffer; dd.DestroyBuffer = destroy_buffer;
|
||||
dd.GetImageMemoryRequirements = image_requirements; dd.GetBufferMemoryRequirements = buffer_requirements;
|
||||
dd.AllocateMemory = allocate; dd.FreeMemory = free_memory;
|
||||
dd.BindImageMemory = bind_image; dd.BindBufferMemory = bind_buffer;
|
||||
dd.MapMemory = map_memory; dd.UnmapMemory = unmap; dd.DeviceWaitIdle = idle;
|
||||
dd.CreateSampler = create<VkSamplerCreateInfo, VkSampler>; dd.DestroySampler = destroy<VkSampler>;
|
||||
dd.CreateShaderModule = create<VkShaderModuleCreateInfo, VkShaderModule>;
|
||||
dd.DestroyShaderModule = destroy<VkShaderModule>;
|
||||
dd.CreateDescriptorSetLayout = create<VkDescriptorSetLayoutCreateInfo, VkDescriptorSetLayout>;
|
||||
dd.DestroyDescriptorSetLayout = destroy<VkDescriptorSetLayout>;
|
||||
dd.CreatePipelineLayout = create<VkPipelineLayoutCreateInfo, VkPipelineLayout>;
|
||||
dd.DestroyPipelineLayout = destroy<VkPipelineLayout>;
|
||||
dd.CreateDescriptorPool = create<VkDescriptorPoolCreateInfo, VkDescriptorPool>;
|
||||
dd.DestroyDescriptorPool = destroy<VkDescriptorPool>; dd.ResetDescriptorPool = reset_pool;
|
||||
dd.AllocateDescriptorSets = allocate_sets; dd.UpdateDescriptorSets = update_sets;
|
||||
dd.CreateComputePipelines = create_pipelines; dd.DestroyPipeline = destroy<VkPipeline>;
|
||||
dd.CmdBindPipeline = bind_pipeline; dd.CmdBindDescriptorSets = bind_sets; dd.CmdDispatch = dispatch;
|
||||
dd.CmdPipelineBarrier = barrier; dd.CmdClearColorImage = clear_image; dd.CmdCopyImage = copy_image;
|
||||
ddfg::FrameGen fg;
|
||||
assert(fg.init(&dd, &id, reinterpret_cast<VkPhysicalDevice>(1), reinterpret_cast<VkDevice>(2),
|
||||
0, reinterpret_cast<VkQueue>(3)));
|
||||
ddfg::Config cfg;
|
||||
cfg.enabled = true; cfg.model = model; cfg.perfPreset = preset; cfg.flowScale = 0.6f;
|
||||
fg.configure(cfg);
|
||||
assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM));
|
||||
assert(mode == "resources" || mode == "record" || mode == "resize" || mode == "preset");
|
||||
for (unsigned repeat = 0; repeat < repeats; repeat++) {
|
||||
const auto old_buffers = buffer_creates, old_sets = set_creates;
|
||||
if (mode != "record") check_images(width, height, fg.flowFinest());
|
||||
record(fg, model, width, height, generations);
|
||||
if (mode != "record") {
|
||||
assert(buffer_creates - old_buffers == static_cast<unsigned>(15 - fg.flowFinest()));
|
||||
assert(set_creates - old_sets == static_cast<unsigned>(54 - 4 * fg.flowFinest()));
|
||||
}
|
||||
if (repeat + 1 == repeats) break;
|
||||
if (mode == "resize") {
|
||||
width += 17; height += 9;
|
||||
assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM));
|
||||
} else if (mode == "preset") {
|
||||
cfg.perfPreset = (cfg.perfPreset + 1) % 3;
|
||||
fg.configure(cfg);
|
||||
} else {
|
||||
assert(mode == "record");
|
||||
}
|
||||
}
|
||||
uint64_t bytes = 0;
|
||||
for (const auto &[image, info] : images) {
|
||||
(void)image;
|
||||
bytes += uint64_t(info.extent.width) * info.extent.height *
|
||||
(info.format == VK_FORMAT_R32_SFLOAT ? 4 : 8);
|
||||
}
|
||||
std::printf("PASS images=%zu bytes=%llu buffers=%u sets=%u dispatches=%zu trace=%016llx\n",
|
||||
images.size(), static_cast<unsigned long long>(bytes), buffer_creates, set_creates,
|
||||
dispatches.size(), static_cast<unsigned long long>(command_hash));
|
||||
fg.destroy();
|
||||
assert(images.empty() && views.empty());
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -28,6 +28,7 @@ class ClientZramFocusTest(unittest.TestCase):
|
||||
_bl_since=-1 _bl_packed=-1
|
||||
_bl_pids=(123)
|
||||
bl_game_focused() { [ "$focused" = 1 ]; }
|
||||
bl_over_cap() { return 1; }
|
||||
bl_zram_send() { echo "send:$1"; }
|
||||
tick() {
|
||||
SECONDS=$1 _bl_game=$2 focused=$3
|
||||
@@ -44,8 +45,50 @@ tick 60 0 0
|
||||
'''
|
||||
result = run_bash(harness)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('', result.stderr)
|
||||
self.assertEqual(['refocus:-1', 'send:1', 'send:0'], result.stdout.splitlines())
|
||||
|
||||
def monitor_harness(self):
|
||||
source = SCRIPT.read_text()
|
||||
start = source.index(' bl_zram_scan\n if bl_cap_due; then')
|
||||
stop = source.index(' nap 5', start)
|
||||
return '''
|
||||
_bl_since=-1 _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30
|
||||
_bl_pids=(123)
|
||||
bl_zram_scan() { :; }
|
||||
bl_game_focused() { [ "$focused" = 1 ]; }
|
||||
bl_cap_due() { [ "$cap_due" = 1 ]; }
|
||||
bl_over_cap() { [ "$over_cap" = 1 ]; }
|
||||
bl_zram_send() { echo "send:$1:$3"; }
|
||||
tick() {
|
||||
SECONDS=$1 _bl_game=$2 focused=$3 over_cap=$4 cap_due=$5
|
||||
''' + source[start:stop] + '\n}\n'
|
||||
|
||||
def test_client_toggle_still_disables_automatic_compression(self):
|
||||
result = run_bash(self.monitor_harness() + '''
|
||||
BL_ZRAM_CLIENT=0
|
||||
tick 0 1 1 0 0
|
||||
tick 25 1 1 0 0
|
||||
tick 30 0 0 0 0
|
||||
''')
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('', result.stderr)
|
||||
self.assertEqual('', result.stdout)
|
||||
|
||||
def test_game_exit_defers_restore_until_the_session_is_under_the_ram_cap(self):
|
||||
result = run_bash(self.monitor_harness() + '''
|
||||
tick 0 1 1 0 0
|
||||
tick 20 1 1 0 0
|
||||
tick 25 1 0 0 0
|
||||
tick 30 0 0 1 0
|
||||
echo "deferred:$_bl_unpack:$_bl_packed"
|
||||
tick 35 0 0 0 1
|
||||
echo "restored:$_bl_unpack"
|
||||
''')
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('', result.stderr)
|
||||
self.assertEqual(['send:1:client', 'deferred:1:-1', 'send:0:client', 'restored:0'], result.stdout.splitlines())
|
||||
|
||||
def test_scan_keeps_the_running_game_and_ignores_steams_own_reaper(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
@@ -53,10 +96,12 @@ tick 60 0 0
|
||||
self.write_cmd(root, 10, ['/usr/lib/steam/reaper', 'SteamLaunch', 'AppId=769', '--'])
|
||||
self.write_cmd(root, 20, ['/usr/bin/FEX', '/usr/lib/steam/reaper', 'SteamLaunch', 'AppId=1245620', '--'])
|
||||
self.write_cmd(root, 30, ['/home/deck/.local/share/Steam/steamrtarm64/steam'])
|
||||
self.write_cmd(root, 40, ['/usr/bin/wine', 'game.exe'])
|
||||
self.write_cmd(root, 50, ['/usr/bin/FEXInterpreter', '/usr/bin/steamwebhelper'])
|
||||
scan = function_source('bl_zram_scan').replace('for _d in /proc/[0-9]*', 'for _d in "$FAKE"/[0-9]*')
|
||||
result = run_bash('FAKE=%s\n%s\nbl_zram_scan\necho "game=$_bl_game"\necho "apps=${_bl_apps# }"\necho "pids=${_bl_pids[*]}"' % (root, scan))
|
||||
result = run_bash('FAKE=%s\n%s\nbl_zram_scan\necho "game=$_bl_game"\necho "apps=${_bl_apps# }"\necho "pids=${_bl_pids[*]}"\necho "others=${_bl_others[*]}"' % (root, scan))
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual(['game=1', 'apps=1245620', 'pids=30'], result.stdout.splitlines())
|
||||
self.assertEqual(['game=1', 'apps=1245620', 'pids=30 50', 'others=40'], result.stdout.splitlines())
|
||||
|
||||
def test_focus_must_be_the_running_game(self):
|
||||
focus = function_source('bl_game_focused')
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
CHAIN = ROOT / "app/src/main/cpp/framegen/ddfg"
|
||||
|
||||
|
||||
class DdfgFlowLevelsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = shutil.which(os.environ.get("CXX", "c++"))
|
||||
if compiler is None:
|
||||
raise unittest.SkipTest("A host C++ compiler is required")
|
||||
candidates = [Path("/usr/include/vulkan"), Path("/opt/homebrew/include/vulkan")]
|
||||
for key in ("ANDROID_NDK_HOME", "ANDROID_NDK_ROOT", "NDK_HOME"):
|
||||
if os.environ.get(key):
|
||||
candidates.extend(Path(os.environ[key]).glob("toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan"))
|
||||
for sdk in {Path(os.environ.get("ANDROID_HOME", "/nonexistent")),
|
||||
Path(os.environ.get("ANDROID_SDK_ROOT", "/nonexistent")),
|
||||
Path.home() / "Library/Android/sdk", Path.home() / "Android/Sdk"}:
|
||||
candidates.extend(sdk.glob("ndk/*/toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan"))
|
||||
headers = next((p for p in candidates if (p / "vulkan.h").is_file()), None)
|
||||
if headers is None:
|
||||
raise unittest.SkipTest("Vulkan headers from the Android NDK or system SDK are required")
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix="droiddeck-ddfg-levels-")
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
work = Path(cls.temp.name)
|
||||
shutil.copytree(headers, work / "include/vulkan", ignore=shutil.ignore_patterns("*.hpp"))
|
||||
if (headers.parent / "vk_video").is_dir():
|
||||
shutil.copytree(headers.parent / "vk_video", work / "include/vk_video")
|
||||
cls.binary = work / "ddfg-flow-levels"
|
||||
build = subprocess.run([
|
||||
compiler, "-std=c++17", "-O2", "-Wall", "-Wextra",
|
||||
"-Wno-missing-field-initializers", "-Wno-misleading-indentation",
|
||||
"-I" + str(work / "include"), "-I" + str(CHAIN),
|
||||
str(ROOT / "tools/tests/ddfg_flow_levels_harness.cpp"), str(CHAIN / "framegen.cpp"),
|
||||
"-o", str(cls.binary),
|
||||
], capture_output=True, text=True, timeout=120)
|
||||
if build.returncode:
|
||||
raise RuntimeError(build.stdout + build.stderr)
|
||||
|
||||
def run_case(self, mode="resources", model=4, preset=2, width=1280, height=720, generations=1, repeats=1):
|
||||
result = subprocess.run([
|
||||
str(self.binary), mode, str(model), str(preset), str(width), str(height),
|
||||
str(generations), str(repeats),
|
||||
], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertTrue(result.stdout.startswith("PASS "), result.stdout)
|
||||
return dict(re.findall(r"(\w+)=(\w+)", result.stdout))
|
||||
|
||||
def test_each_model_and_preset_allocates_only_solved_flow_levels(self):
|
||||
for model in (3, 4):
|
||||
for preset, finest in enumerate((1, 2, 3)):
|
||||
with self.subTest(model=model, preset=preset):
|
||||
values = self.run_case(model=model, preset=preset)
|
||||
self.assertEqual(int(values["images"]), 32 - 2 * finest)
|
||||
self.assertEqual(int(values["buffers"]), 18 - finest)
|
||||
self.assertEqual(int(values["sets"]), 54 - 4 * finest)
|
||||
|
||||
def test_default_preset_saves_the_exact_high_resolution_flow_payload(self):
|
||||
for width, height in ((1280, 720), (1920, 1080), (2560, 1440)):
|
||||
with self.subTest(width=width, height=height):
|
||||
values = self.run_case(width=width, height=height)
|
||||
pixels = lambda level: max(width >> level, 1) * max(height >> level, 1)
|
||||
luma_bytes = 4 * (2 * sum(pixels(l) for l in range(7)) +
|
||||
sum(pixels(l) for l in range(3, 7)))
|
||||
flow_bytes = 8 * (sum(pixels(l) for l in range(3, 7)) +
|
||||
2 * width * height + 2 * pixels(3))
|
||||
self.assertEqual(int(values["bytes"]), luma_bytes + flow_bytes)
|
||||
|
||||
def test_small_and_odd_extents_keep_valid_bindings_and_dispatch_sizes(self):
|
||||
for width, height in ((1, 1), (17, 9), (135, 73)):
|
||||
for preset in range(3):
|
||||
with self.subTest(width=width, height=height, preset=preset):
|
||||
self.run_case(width=width, height=height, preset=preset)
|
||||
|
||||
def test_two_three_and_four_times_generation_keep_the_same_dispatch_schedule(self):
|
||||
for model in (3, 4):
|
||||
for preset in range(3):
|
||||
for generations in (1, 2, 3):
|
||||
with self.subTest(model=model, preset=preset, generations=generations):
|
||||
self.run_case("record", model=model, preset=preset, generations=generations, repeats=3)
|
||||
|
||||
def test_resize_rebuilds_every_solved_level(self):
|
||||
for preset in range(3):
|
||||
with self.subTest(preset=preset):
|
||||
self.run_case("resize", preset=preset, generations=3, repeats=3)
|
||||
|
||||
def test_live_preset_changes_rebuild_the_level_range(self):
|
||||
for model in (3, 4):
|
||||
with self.subTest(model=model):
|
||||
self.run_case("preset", model=model, generations=3, repeats=4)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,74 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
GPU = TOOLS / "linuxfs/desktop/droiddeck-gpu"
|
||||
WINDOW = TOOLS / "linuxfs/overlay/usr/local/bin/droiddeck-gpu-window"
|
||||
KEYS = ("MESA_VK_WSI_DEBUG", "SDL_VIDEODRIVER", "WAYLAND_DISPLAY", "BL_GPU_CHILD_WSI", "BL_DESKTOP_GPU_CHILD")
|
||||
|
||||
|
||||
class DesktopGpuWindowTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.tmp, True)
|
||||
self.out = self.tmp / "gamescope.json"
|
||||
fake = self.tmp / "gamescope"
|
||||
fake.write_text("#!%s\nimport json, os, sys\njson.dump({'args': sys.argv[1:], 'env': {k: os.environ.get(k) for k in %r}}, open(%r, 'w'))\n"
|
||||
% (sys.executable, KEYS, str(self.out)))
|
||||
fake.chmod(0o755)
|
||||
|
||||
def run_gpu(self, **env):
|
||||
base = {k: v for k, v in os.environ.items() if k not in KEYS + ("BL_DEBUG_DIR", "BL_DESKTOP_GPU_WINDOW")}
|
||||
base.update(PATH="%s:%s" % (self.tmp, os.environ["PATH"]), BL_WIDTH="1280", BL_HEIGHT="720", **env)
|
||||
subprocess.run(["bash", str(GPU), "game.exe"], env=base, check=True, capture_output=True)
|
||||
return json.loads(self.out.read_text())
|
||||
|
||||
def test_on_the_desktop_the_game_gets_a_window_of_its_own(self):
|
||||
run = self.run_gpu(WAYLAND_DISPLAY="wayland-1", MESA_VK_WSI_DEBUG="sw,linear")
|
||||
self.assertEqual(run["args"][:2], ["--backend", "sdl"])
|
||||
self.assertNotIn("-f", run["args"])
|
||||
self.assertEqual(run["args"][-2:], ["/usr/local/bin/droiddeck-gpu-window", "game.exe"])
|
||||
self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-1")
|
||||
self.assertEqual(run["env"]["SDL_VIDEODRIVER"], "wayland")
|
||||
self.assertEqual(run["env"]["MESA_VK_WSI_DEBUG"], "sw")
|
||||
self.assertEqual(run["env"]["BL_GPU_CHILD_WSI"], "linear")
|
||||
self.assertEqual(run["env"]["BL_DESKTOP_GPU_CHILD"], "1")
|
||||
|
||||
def test_full_screen_stays_available(self):
|
||||
for env in ({"WAYLAND_DISPLAY": "wayland-1", "BL_DESKTOP_GPU_WINDOW": "0"}, {"WAYLAND_DISPLAY": "wayland-0"}, {}):
|
||||
run = self.run_gpu(**env)
|
||||
self.assertEqual(run["args"][:2], ["--backend", "wayland"])
|
||||
self.assertIn("-f", run["args"])
|
||||
self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-0")
|
||||
self.assertIsNone(run["env"]["MESA_VK_WSI_DEBUG"])
|
||||
self.assertIsNone(run["env"]["BL_GPU_CHILD_WSI"])
|
||||
|
||||
def test_the_game_inside_the_window_gets_its_own_settings_back(self):
|
||||
script = "import json, os; print(json.dumps({k: os.environ.get(k) for k in %r}))" % (KEYS,)
|
||||
for saved, expected in (("linear", "linear"), ("", None)):
|
||||
env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DISPLAY",)}
|
||||
env.update(BL_GPU_CHILD_WSI=saved, MESA_VK_WSI_DEBUG="sw", SDL_VIDEODRIVER="wayland")
|
||||
out = subprocess.run([sys.executable, str(WINDOW), sys.executable, "-c", script], env=env,
|
||||
check=True, capture_output=True, text=True).stdout
|
||||
child = json.loads(out)
|
||||
self.assertEqual(child["MESA_VK_WSI_DEBUG"], expected)
|
||||
self.assertEqual(child["SDL_VIDEODRIVER"], "x11")
|
||||
self.assertIsNone(child["BL_GPU_CHILD_WSI"])
|
||||
|
||||
def test_outside_a_window_the_game_keeps_its_settings(self):
|
||||
script = "import os; print(os.environ.get('MESA_VK_WSI_DEBUG'), os.environ.get('SDL_VIDEODRIVER'))"
|
||||
env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DISPLAY",)}
|
||||
env.update(MESA_VK_WSI_DEBUG="linear", SDL_VIDEODRIVER="x11")
|
||||
out = subprocess.run([sys.executable, str(WINDOW), sys.executable, "-c", script], env=env,
|
||||
check=True, capture_output=True, text=True).stdout.split()
|
||||
self.assertEqual(out, ["linear", "x11"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -456,6 +456,15 @@ class ProtonRunTest(Temp):
|
||||
("0", "0", str(appid << 32 | 0x02000000), "1"))
|
||||
self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(self.root / ("steamapps/compatdata/%d" % appid)))
|
||||
|
||||
def test_a_window_draws_with_the_desktops_software_gl(self):
|
||||
target = RUN["Target"]("2596113170", "/c", "/i", str(self.root), "fixed")
|
||||
session = {"MESA_LOADER_DRIVER_OVERRIDE": "zink", "GALLIUM_DRIVER": "zink", "LIBGL_KOPPER_DRI2": "true"}
|
||||
env = RUN["environment"](session, target, "/tool", str(self.root), window=True)
|
||||
self.assertEqual((env["LIBGL_ALWAYS_SOFTWARE"], env["GALLIUM_DRIVER"]), ("1", "llvmpipe"))
|
||||
self.assertNotIn("MESA_LOADER_DRIVER_OVERRIDE", env)
|
||||
self.assertNotIn("LIBGL_KOPPER_DRI2", env)
|
||||
self.assertEqual(RUN["environment"](session, target, "/tool", str(self.root))["GALLIUM_DRIVER"], "zink")
|
||||
|
||||
def test_a_steam_game_keeps_its_own_id(self):
|
||||
target = RUN["Target"]("413150", "/c", "/i", str(self.root), "steam")
|
||||
env = RUN["environment"]({"PROTON_USE_WINED3D": "0"}, target, "/tool", str(self.root), window=True)
|
||||
@@ -465,6 +474,13 @@ class ProtonRunTest(Temp):
|
||||
self.assertEqual(RUN["arguments"]("/root/x/setup.msi", ["/qn"]), ["msiexec", "/i", "Z:\\root\\x\\setup.msi", "/qn"])
|
||||
self.assertEqual(RUN["arguments"]("/root/x/a.exe", ["-w"]), ["/root/x/a.exe", "-w"])
|
||||
|
||||
def test_a_virtual_desktop_runs_the_program_by_its_windows_path(self):
|
||||
pfx = "/root/Steam/steamapps/compatdata/2596113170"
|
||||
self.assertEqual(RUN["arguments"](pfx + "/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe", [], "1280x720", pfx),
|
||||
["explorer.exe", "/desktop=droiddeck,1280x720", "C:\\Program Files (x86)\\Battle.net\\Battle.net Launcher.exe"])
|
||||
self.assertEqual(RUN["arguments"]("/root/.cache/setup.exe", ["--lang=enUS"], "1920x1080", pfx),
|
||||
["explorer.exe", "/desktop=droiddeck,1920x1080", "Z:\\root\\.cache\\setup.exe", "--lang=enUS"])
|
||||
|
||||
def test_a_games_own_program_is_left_to_steam(self):
|
||||
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: STARDEW}))
|
||||
self.assertEqual(RUN["compat"]()["launch_programs"](STARDEW["config"]),
|
||||
@@ -554,6 +570,50 @@ class ProtonRunTest(Temp):
|
||||
self.game("70", "Linux Game", "run.sh")
|
||||
self.assertEqual(self.run_main(["--app", "70"])[0], 2)
|
||||
|
||||
def test_without_steam_a_shortcut_reuses_a_signed_prefix_folder(self):
|
||||
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
|
||||
start = self.tmp / "Games/Epic/Game/Binaries"
|
||||
start.mkdir()
|
||||
signed = self.root / "steamapps/compatdata/-1561598272"
|
||||
signed.mkdir(parents=True)
|
||||
code, calls, dirs = self.run_main(["--app", "2733369024", "--dir", str(start), "--", str(bat)])
|
||||
self.assertIsNone(code)
|
||||
env = calls[0][2]
|
||||
self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(signed))
|
||||
self.assertFalse((self.root / "steamapps/compatdata/2733369024").exists())
|
||||
|
||||
def test_prefix_folder_prefers_initialized_unsigned_over_empty_signed(self):
|
||||
signed = self.root / "steamapps/compatdata/-1561598272"
|
||||
signed.mkdir(parents=True)
|
||||
initialized = self.root / "steamapps/compatdata/2733369024/pfx"
|
||||
initialized.mkdir(parents=True)
|
||||
|
||||
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(initialized.parent))
|
||||
|
||||
def test_prefix_folder_prefers_initialized_signed_over_empty_unsigned(self):
|
||||
unsigned = self.root / "steamapps/compatdata/2733369024"
|
||||
unsigned.mkdir(parents=True)
|
||||
initialized = self.root / "steamapps/compatdata/-1561598272/pfx"
|
||||
initialized.mkdir(parents=True)
|
||||
|
||||
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(initialized.parent))
|
||||
|
||||
def test_prefix_folder_prefers_unsigned_when_initialization_ties(self):
|
||||
unsigned = self.root / "steamapps/compatdata/2733369024/pfx"
|
||||
unsigned.mkdir(parents=True)
|
||||
signed = self.root / "steamapps/compatdata/-1561598272/pfx"
|
||||
signed.mkdir(parents=True)
|
||||
|
||||
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(unsigned.parent))
|
||||
|
||||
def test_prefix_folder_skips_numeric_names_too_long_to_convert(self):
|
||||
from unittest.mock import patch
|
||||
folder = self.root / "steamapps/compatdata"
|
||||
folder.mkdir(parents=True)
|
||||
with patch.object(RUN["os"], "listdir", return_value=["9" * 5000]):
|
||||
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024),
|
||||
str(folder / "2733369024"))
|
||||
|
||||
def test_without_steam_a_shortcut_keeps_its_prefix_folder_and_launch_options(self):
|
||||
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
|
||||
start = self.tmp / "Games/Epic/Game/Binaries"
|
||||
@@ -568,6 +628,43 @@ class ProtonRunTest(Temp):
|
||||
self.assertTrue((self.root / "steamapps/compatdata/2733369024").is_dir())
|
||||
self.assertEqual(dirs, [str(start)])
|
||||
|
||||
def write_account(self):
|
||||
self.write("Steam/config/loginusers.vdf",
|
||||
'"users"\n{\n\t"76561198352563669"\n\t{\n\t\t"MostRecent"\t\t"1"\n\t}\n}\n')
|
||||
return "Steam/userdata/392297941/config/"
|
||||
|
||||
def test_without_steam_and_options_a_game_takes_its_steam_launch_options(self):
|
||||
config = self.write_account()
|
||||
self.write(config + "localconfig.vdf", '"UserLocalConfigStore"\n{\n\t"Software"\n\t{\n\t\t"Valve"\n\t\t{\n'
|
||||
'\t\t\t"Steam"\n\t\t\t{\n\t\t\t\t"apps"\n\t\t\t\t{\n\t\t\t\t\t"413150"\n\t\t\t\t\t{\n'
|
||||
'\t\t\t\t\t\t"cloud"\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t"LaunchOptions"\t\t"-wrong"\n\t\t\t\t\t\t}\n'
|
||||
'\t\t\t\t\t\t"LaunchOptions"\t\t"DXVK_HUD=1 %command% -d3d9 \\"-name=Two Words\\""\n'
|
||||
'\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n')
|
||||
shortcuts = runpy.run_path(str(BIN / "droiddeck-steam-shortcuts"))
|
||||
self.write(config + "shortcuts.vdf", shortcuts["write"]({"shortcuts": {
|
||||
"0": {"appid": -1561598272, "AppName": "Batman", "LaunchOptions": "-d3d9"},
|
||||
"1": {"appid": -1, "AppName": "Other", "LaunchOptions": "-x"},
|
||||
}}))
|
||||
root = str(self.root)
|
||||
self.assertEqual(RUN["steam_options"]("413150", root), 'DXVK_HUD=1 %command% -d3d9 "-name=Two Words"')
|
||||
self.assertEqual(RUN["steam_options"]("2733369024", root), "-d3d9")
|
||||
self.assertEqual(RUN["steam_options"]("70", root), "")
|
||||
self.assertEqual(RUN["steam_options"]("2733369025", root), "")
|
||||
info = {"common": {"type": "Game"}, "config": {"launch": {
|
||||
"0": {"executable": "Game.exe", "type": "default", "config": {"oslist": "windows"}}}}}
|
||||
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: info}))
|
||||
program = self.game("413150", "Some Game", "Game.exe")
|
||||
code, calls, _ = self.run_main(["--app", "413150"])
|
||||
self.assertIsNone(code)
|
||||
_, argv, env = calls[0]
|
||||
self.assertEqual(argv[1:], ["waitforexitandrun", str(program), "-d3d9", "-name=Two Words"])
|
||||
self.assertEqual(env["DXVK_HUD"], "1")
|
||||
bat = self.write("Games/GOG/Batman/Batman.exe", b"MZ")
|
||||
code, calls, _ = self.run_main(["--app", "2733369024", "--", str(bat)])
|
||||
self.assertEqual(calls[0][1][1:], ["waitforexitandrun", str(bat), "-d3d9"])
|
||||
code, calls, _ = self.run_main(["--app", "2733369024", "--options", "", "--", str(bat)])
|
||||
self.assertEqual(calls[0][1][1:], ["waitforexitandrun", str(bat)])
|
||||
|
||||
def test_launch_options_split_like_steam_does(self):
|
||||
split = RUN["split_options"]
|
||||
self.assertEqual(split(""), ({}, []))
|
||||
|
||||
@@ -47,6 +47,8 @@ elif a[:1] == ["shell"]:
|
||||
s.setdefault("log_commands", []).append(a)
|
||||
p.write_text(json.dumps(s))
|
||||
if "ls" in a: print(s["session"])
|
||||
elif a[-1].endswith("/device.txt"): print(s.get("report", ""))
|
||||
elif a[-1].endswith("/app.log"): print(s.get("app_log", ""))
|
||||
else: print("package not debuggable")
|
||||
'''
|
||||
|
||||
@@ -112,6 +114,16 @@ class DeviceSmokeTest(unittest.TestCase):
|
||||
self.assertEqual(1, result.returncode, result.stdout)
|
||||
self.assertIn("could not launch", result.stdout)
|
||||
|
||||
def test_fast_path_requires_a_session_activation_log(self):
|
||||
for active in (False, True):
|
||||
with self.subTest(active=active):
|
||||
result, _ = self.run_smoke(
|
||||
session="session", report="proot fast path (eligible) true",
|
||||
app_log="proot: fast path on (66 binds)" if active else "proot: fast path off - too many binds",
|
||||
)
|
||||
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertEqual(active, "PASS proot fast path was on" in result.stdout)
|
||||
|
||||
def test_session_name_remains_one_remote_argument(self):
|
||||
session = "x';id;#"
|
||||
result, state = self.run_smoke(session=session)
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import json
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
|
||||
TOOL = COMPAT["TOOL"]
|
||||
OLD = {"name": "DroidDeck-Proton-11-11.2", "display": "DroidDeck-Proton 11-11.2", "dir": "DroidDeck-Proton 11-11.2", "valve": False}
|
||||
NEW = {"name": "DroidDeck-Proton-11-11.4", "display": "DroidDeck-Proton 11-11.4", "dir": "DroidDeck-Proton 11-11.4", "valve": False}
|
||||
VALVE = {"name": TOOL, "display": "Proton Experimental ARM64", "dir": "Proton - Experimental (ARM64)", "valve": True}
|
||||
GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}
|
||||
|
||||
|
||||
def config_text(entries):
|
||||
mapping = "".join('"%s" { "name" "%s" "config" "" "priority" "%s" }' % (app, name, "75" if app == "0" else "250") for app, name in entries)
|
||||
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
|
||||
|
||||
|
||||
class DroidDeckProtonDefaultTest(unittest.TestCase):
|
||||
def run_default(self, state, mapping, catalog, apps=(), request=None, settle=True):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
directory = Path(tmp)
|
||||
(directory / "state.json").write_text(json.dumps(state))
|
||||
if request is not None:
|
||||
(directory / "request.json").write_text(json.dumps(request))
|
||||
config = directory / "config.vdf"
|
||||
config.write_text(config_text(mapping))
|
||||
default = COMPAT["register_default"](str(config), list(apps), catalog=catalog, directory=str(directory), settle=settle)
|
||||
return default, COMPAT["read_config_mapping"](str(config)), json.loads((directory / "state.json").read_text())
|
||||
|
||||
def test_a_replacement_seen_while_steam_runs_still_moves_the_default_later(self):
|
||||
_, mapping, state = self.run_default(
|
||||
{"default": OLD["name"], "own_proton": True, "tools": [VALVE, OLD]}, [("0", OLD["name"])], [VALVE, NEW], settle=False)
|
||||
self.assertEqual(state["tools"], [VALVE, NEW])
|
||||
self.assertIn(OLD["name"], state["own_builds"])
|
||||
default, mapping, state = self.run_default(state, [("0", OLD["name"])], [VALVE, NEW])
|
||||
self.assertEqual(default, NEW["name"])
|
||||
self.assertEqual(mapping, {"0": NEW["name"]})
|
||||
|
||||
def test_a_valve_default_picked_in_steam_after_a_replacement_is_kept(self):
|
||||
default, mapping, _ = self.run_default(
|
||||
{"default": OLD["name"], "own_proton": True, "tools": [VALVE, OLD]}, [("0", TOOL)], [VALVE, NEW])
|
||||
self.assertEqual(default, TOOL)
|
||||
self.assertEqual(mapping, {"0": TOOL})
|
||||
|
||||
def test_the_first_start_with_droiddeck_proton_makes_it_the_default_for_following_titles(self):
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL), ("43", TOOL)], [VALVE, NEW], ["42", "43"])
|
||||
self.assertEqual(default, NEW["name"])
|
||||
self.assertEqual(mapping, {"0": NEW["name"], "42": NEW["name"], "43": TOOL})
|
||||
self.assertEqual(state["default"], NEW["name"])
|
||||
self.assertTrue(state["own_proton"])
|
||||
|
||||
def test_a_default_picked_after_the_switch_is_kept(self):
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": NEW["name"], "own_proton": True, "applied": 1, "tools": [VALVE, NEW]},
|
||||
[("0", NEW["name"])], [VALVE, NEW], request={"seq": 2, "valve": True, "dir": VALVE["dir"]})
|
||||
self.assertEqual(default, TOOL)
|
||||
self.assertEqual(mapping, {"0": TOOL})
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": TOOL, "own_proton": True, "tools": [VALVE, NEW]}, [("0", TOOL)], [VALVE, NEW])
|
||||
self.assertEqual(default, TOOL)
|
||||
self.assertEqual(mapping, {"0": TOOL})
|
||||
|
||||
def test_a_replaced_build_moves_its_default_and_titles_to_the_newest(self):
|
||||
default, mapping, state = self.run_default(
|
||||
{"default": OLD["name"], "own_proton": True, "auto": {"42": OLD["name"]}, "tools": [VALVE, OLD, GE]},
|
||||
[("0", OLD["name"]), ("42", OLD["name"]), ("43", OLD["name"]), ("44", GE["name"]), ("45", TOOL)],
|
||||
[VALVE, NEW, GE], ["42", "43", "44", "45"])
|
||||
self.assertEqual(default, NEW["name"])
|
||||
self.assertEqual(mapping, {"0": NEW["name"], "42": NEW["name"], "43": NEW["name"], "44": GE["name"], "45": TOOL})
|
||||
self.assertEqual(state["auto"], {"42": NEW["name"]})
|
||||
|
||||
def test_a_replaced_build_does_not_override_a_valve_default(self):
|
||||
default, mapping, _ = self.run_default(
|
||||
{"default": TOOL, "own_proton": True, "tools": [VALVE, OLD]}, [("0", TOOL), ("43", OLD["name"])], [VALVE, NEW], ["43"])
|
||||
self.assertEqual(default, TOOL)
|
||||
self.assertEqual(mapping, {"0": TOOL, "43": NEW["name"]})
|
||||
|
||||
def test_nothing_changes_without_droiddeck_proton(self):
|
||||
default, mapping, state = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, GE])
|
||||
self.assertEqual(default, TOOL)
|
||||
self.assertEqual(mapping, {"0": TOOL})
|
||||
self.assertNotIn("own_proton", state)
|
||||
|
||||
def test_the_newest_build_is_found_by_version(self):
|
||||
newest, gone = COMPAT["own_proton_moves"]({"tools": [OLD]}, [dict(NEW, name="a", dir="DroidDeck-Proton 11-9.10"), dict(NEW, name="b", dir="DroidDeck-Proton 11-11.1")])
|
||||
self.assertEqual(newest, "b")
|
||||
self.assertEqual(gone, {OLD["name"]})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -413,6 +413,21 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
self.assertEqual("Awake", out["wakefulness"])
|
||||
self.assertIn(["shell", "input", "keyevent", "KEYCODE_WAKEUP"], [c["args"] for c in self.calls()])
|
||||
|
||||
def test_proot_profile_queues_only_the_next_session(self):
|
||||
self.configure({"env": {"ok": True}})
|
||||
code, out = self.run_ctl("proot-profile", "enable", "--slow-us", "250")
|
||||
self.assertEqual(0, code, out)
|
||||
self.assertEqual({"op": "set", "lines": ["PROOT_PROFILE=1", "PROOT_PROFILE_SLOW_US=250"], "persistent": False},
|
||||
self.calls("env")[0]["request"])
|
||||
|
||||
def test_proot_profile_report_needs_no_adb_or_device(self):
|
||||
path = self.dir / "session.log"
|
||||
path.write_text('ordinary log')
|
||||
with unittest.mock.patch.object(ctl, "adb_path", side_effect=AssertionError("must stay offline")):
|
||||
code, out = self.run_ctl("proot-profile", "report", str(path))
|
||||
self.assertEqual(0, code, out)
|
||||
self.assertFalse(out["hasCounters"])
|
||||
|
||||
def test_override_pushes_to_the_inbox_first(self):
|
||||
self.configure({
|
||||
"access": {"ok": True, "commands": True, "inbox": "/sdcard/Android/data/x/files/agent-inbox"},
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup"
|
||||
|
||||
|
||||
class FlatpakSetupTest(unittest.TestCase):
|
||||
def run_setup(self, uid, pacman):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
bin_dir = root / "bin"
|
||||
bin_dir.mkdir()
|
||||
stubs = {"id": "echo %d" % uid, "curl": "exit 7", "pacman": pacman, "pacman-key": "exit 0"}
|
||||
for name, body in stubs.items():
|
||||
(bin_dir / name).write_text("#!/bin/sh\n%s\n" % body)
|
||||
(bin_dir / name).chmod(0o755)
|
||||
script = root / "setup"
|
||||
script.write_text(SCRIPT.read_text().replace("WORK=/var/cache/droiddeck-flatpak", "WORK=%s/work" % root)
|
||||
.replace("/etc/pacman.d/gnupg/pubring.gpg", str(root / "pubring.gpg"))
|
||||
.replace(" /etc/pacman.conf >", " %s >" % (root / "pacman.conf")))
|
||||
(root / "pacman.conf").write_text("[options]\n[core]\nInclude = /etc/pacman.d/mirrorlist\n")
|
||||
(root / "pubring.gpg").write_text("")
|
||||
env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ["PATH"]))
|
||||
result = subprocess.run(["bash", str(script)], env=env, capture_output=True, text=True, timeout=30)
|
||||
return result.returncode, result.stdout
|
||||
|
||||
def test_a_manual_run_without_root_says_so(self):
|
||||
code, out = self.run_setup(1000, "exit 0")
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("== FAIL needs root", out)
|
||||
self.assertNotIn("Reading the package lists", out)
|
||||
|
||||
def test_an_unreachable_mirror_reports_pacmans_error(self):
|
||||
code, out = self.run_setup(0, "echo \"error: failed retrieving file 'core.db' : Could not resolve host\" >&2; exit 1")
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("== FAIL could not reach the Arch Linux ARM mirrors (error: failed retrieving file 'core.db' : "
|
||||
"Could not resolve host)", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -8,6 +8,7 @@ import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from unittest import mock
|
||||
import unittest
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
@@ -76,6 +77,35 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
self.assertEqual(result.stdout.strip(), expected)
|
||||
|
||||
def test_desktop_games_restart_on_the_gpu_with_steams_preloads_handed_back(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
gpu = home / "gpu"
|
||||
gpu.write_text("#!/bin/bash\necho \"gpu LD_PRELOAD=${LD_PRELOAD-unset}\"\nexport BL_DESKTOP_GPU_CHILD=1\nexec \"$@\"\n")
|
||||
gpu.chmod(0o755)
|
||||
launcher = home / "launcher"
|
||||
setup = COMPAT["BL_DESKTOP_GPU_SETUP"].replace("/usr/local/bin/droiddeck-gpu", str(gpu))
|
||||
launcher.write_text("#!/bin/bash\nverb=$1; shift\n" + setup + "echo \"game $verb $* LD_PRELOAD=${LD_PRELOAD-unset} saved=${BL_GPU_SAVED_LD_PRELOAD-unset}\"\n")
|
||||
launcher.chmod(0o755)
|
||||
base = {key: value for key, value in os.environ.items() if not key.startswith("BL_")}
|
||||
base["LD_PRELOAD"] = "overlay.so"
|
||||
for extra, args, expected in (
|
||||
({"BL_DESKTOP": "1"}, ["waitforexitandrun", "game.exe"],
|
||||
["gpu LD_PRELOAD=unset", "game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]),
|
||||
({"BL_DESKTOP": "1", "BL_DESKTOP_GPU": "Off"}, ["waitforexitandrun", "game.exe"],
|
||||
["game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]),
|
||||
({"BL_DESKTOP": "1"}, ["run", "setup.exe"],
|
||||
["game run setup.exe LD_PRELOAD=overlay.so saved=unset"]),
|
||||
({"BL_DESKTOP": "1"}, ["waitforexitandrun", "iscriptevaluator.exe"],
|
||||
["game waitforexitandrun iscriptevaluator.exe LD_PRELOAD=overlay.so saved=unset"]),
|
||||
({}, ["waitforexitandrun", "game.exe"],
|
||||
["game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]),
|
||||
):
|
||||
with self.subTest(extra=extra, args=args):
|
||||
result = subprocess.run([str(launcher)] + args, env=dict(base, **extra),
|
||||
text=True, capture_output=True, check=True)
|
||||
self.assertEqual(result.stdout.splitlines(), expected)
|
||||
|
||||
def test_the_install_script_evaluator_gets_its_scripts_marked_first(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
@@ -180,6 +210,14 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
|
||||
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
|
||||
|
||||
def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self):
|
||||
cap = MODULE["vram_cap"]
|
||||
self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096")
|
||||
self.assertEqual(cap({"BL_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"],
|
||||
"dxgi.maxDeviceMemory = 2048; dxvk.maxFrameRate = 60")
|
||||
for off in ({}, {"BL_VRAM_MB": "0"}, {"BL_VRAM_MB": "lots"}, {"BL_VRAM_MB": "²"}, {"BL_VRAM_MB": "-1"}):
|
||||
self.assertNotIn("DXVK_CONFIG", cap(off))
|
||||
|
||||
def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self):
|
||||
env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"}
|
||||
config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}}
|
||||
@@ -357,7 +395,33 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
(asylum / name).touch()
|
||||
self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], []))
|
||||
|
||||
def test_caravan_sandwitch_and_cyberpunk_run_at_feature_level_12_1(self):
|
||||
def test_black_ops_iii_and_dark_souls_remastered_skip_protonfixes(self):
|
||||
for exe in ("/game/Call of Duty Black Ops III/BlackOps3.exe", "/game/DARK SOULS REMASTERED/DarkSoulsRemastered.exe"):
|
||||
env, extra, notes = MODULE["engine_fixes"](exe, [])
|
||||
self.assertEqual((env, extra), ({"PROTONFIXES_DISABLE": "1"}, []))
|
||||
self.assertTrue(notes)
|
||||
self.assertEqual(MODULE["engine_fixes"]("/game/Game/DarkSoulsII.exe", []), ({}, [], []))
|
||||
|
||||
def test_game_cores_are_parsed_from_lists_and_ranges(self):
|
||||
parse = MODULE["parse_cores"]
|
||||
self.assertEqual(parse("0-3,6"), {0, 1, 2, 3, 6})
|
||||
self.assertEqual(parse(" 4, 5 "), {4, 5})
|
||||
for bad in ("", "a", "3-1", "1,,2", "-1", "1-"):
|
||||
self.assertIsNone(parse(bad), bad)
|
||||
|
||||
def test_a_profiles_game_cores_pin_the_game_within_the_online_cores(self):
|
||||
calls = []
|
||||
os_mod = MODULE["os"]
|
||||
with mock.patch.dict(MODULE["game_cores"].__globals__, {"online_cores": lambda: {0, 1, 2, 3, 4, 5, 6, 7}}), \
|
||||
mock.patch.object(os_mod, "sched_setaffinity", side_effect=lambda pid, cores: calls.append(set(cores)), create=True):
|
||||
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "0-2,9"})
|
||||
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "junk"})
|
||||
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "12-13"})
|
||||
MODULE["game_cores"]({})
|
||||
self.assertEqual(calls, [{0, 1, 2}])
|
||||
self.assertEqual(MODULE["parse_cores"]("0,2-7"), {0, 2, 3, 4, 5, 6, 7})
|
||||
|
||||
def test_caravan_sandwitch_robocop_and_cyberpunk_run_at_feature_level_12_1(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
caravan = Path(tmp) / "Caravan SandWitch"
|
||||
shipping = caravan / "CaravanSandWitch/Binaries/Win64"
|
||||
@@ -369,8 +433,13 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
(cyberpunk / "bin/x64").mkdir(parents=True)
|
||||
for name in ("REDprelauncher.exe", "bin/x64/Cyberpunk2077.exe"):
|
||||
(cyberpunk / name).touch()
|
||||
robocop = Path(tmp) / "RoboCop Rogue City"
|
||||
(robocop / "RoboCop/Binaries/Win64").mkdir(parents=True)
|
||||
for name in ("RoboCop.exe", "RoboCop/Binaries/Win64/RoboCop-Win64-Shipping.exe"):
|
||||
(robocop / name).touch()
|
||||
games = [caravan / "CaravanSandWitch.exe", caravan / ".droiddeck-launch.bat",
|
||||
shipping / "CaravanSandWitch-Win64-Shipping.exe",
|
||||
robocop / "RoboCop.exe", robocop / "RoboCop/Binaries/Win64/RoboCop-Win64-Shipping.exe",
|
||||
cyberpunk / "REDprelauncher.exe", cyberpunk / "bin/x64/Cyberpunk2077.exe"]
|
||||
for exe in games:
|
||||
env, extra, notes = MODULE["engine_fixes"](str(exe), [])
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
from proot_profile import report
|
||||
|
||||
PROGRAM = r'''
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#define PR_NB_SYSNUM 2
|
||||
#define PR_void 0
|
||||
static const char *stringify_sysnum(unsigned nr) { return nr ? "openat" : "void"; }
|
||||
#include "profile.h"
|
||||
int main(void) {
|
||||
errno = EBUSY;
|
||||
if (!dd_profile_enabled()) return errno != EBUSY;
|
||||
if (errno != EBUSY) return 1;
|
||||
for (int i = 0; i < 40; i++) {
|
||||
uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC);
|
||||
uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID);
|
||||
struct timespec wait = {0, 2000000};
|
||||
nanosleep(&wait, 0);
|
||||
errno = ENOENT;
|
||||
dd_profile_record(1, 1, 123, wall, cpu);
|
||||
if (errno != ENOENT) return 2;
|
||||
if (i == 9) dd_profile_flush();
|
||||
}
|
||||
dd_profile_next = 0;
|
||||
uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC);
|
||||
uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID);
|
||||
struct timespec wait = {0, 2000000};
|
||||
nanosleep(&wait, 0);
|
||||
dd_profile_record(1, 0, 123, wall, cpu);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class ProotProfileTest(unittest.TestCase):
|
||||
def test_snapshots_replace_instead_of_adding_and_tracers_remain_separate(self):
|
||||
with tempfile.TemporaryDirectory() as work:
|
||||
path = Path(work) / 'session.log'
|
||||
records = [dict(type='total', tracer=1, id=2, syscall='statx', stage='enter',
|
||||
calls=n, wall_ns=n * 100, cpu_ns=n * 10, max_ns=100) for n in (3, 8)]
|
||||
records.append(dict(records[-1], tracer=2, calls=2))
|
||||
records += [dict(type='total', tracer=1, id=3, syscall='openat', stage='enter',
|
||||
calls=1, wall_ns=1000, cpu_ns=1000, max_ns=1000)]
|
||||
path.write_text('unrelated log\n' + ''.join('prefix proot-profile ' + json.dumps(r) + '\n' for r in records)
|
||||
+ 'proot-profile {truncated\n' + 'proot-profile []\n')
|
||||
result = report(path)
|
||||
self.assertEqual(11, result['handlerCalls'])
|
||||
self.assertEqual(3, result['tracers'])
|
||||
self.assertEqual(2, result['malformedRecords'])
|
||||
self.assertEqual('statx', result['totals'][0]['syscall'])
|
||||
self.assertEqual('openat', report(path, 'cpu')['totals'][0]['syscall'])
|
||||
|
||||
def test_empty_logs_do_not_claim_profiling_ran(self):
|
||||
with tempfile.TemporaryDirectory() as work:
|
||||
path = Path(work) / 'session.log'
|
||||
path.write_text('ordinary log\n')
|
||||
self.assertFalse(report(path)['hasCounters'])
|
||||
|
||||
@unittest.skipUnless(shutil.which('cc'), 'C compiler required')
|
||||
def test_real_clocks_bounded_samples_errno_and_periodic_counters(self):
|
||||
with tempfile.TemporaryDirectory() as work:
|
||||
source = Path(work) / 'profile.c'
|
||||
binary = Path(work) / 'profile'
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(['cc', '-Wall', '-Wextra', '-Werror', '-std=c99', '-I', str(TOOLS / 'proot'),
|
||||
str(source), '-o', str(binary)], check=True)
|
||||
for setting in ('0', ''):
|
||||
result = subprocess.run([binary], env=dict(os.environ, PROOT_PROFILE=setting), capture_output=True, check=True)
|
||||
self.assertEqual(b'', result.stderr)
|
||||
result = subprocess.run([binary], env=dict(os.environ, PROOT_PROFILE='1', PROOT_PROFILE_SLOW_US='1'),
|
||||
capture_output=True, check=True)
|
||||
rows = [json.loads(line.split(b'proot-profile ', 1)[1]) for line in result.stderr.splitlines()]
|
||||
self.assertEqual(33, sum(row['type'] == 'slow' for row in rows))
|
||||
self.assertEqual(32, sum(row['type'] == 'slow' and row['stage'] == 'enter' for row in rows))
|
||||
self.assertGreater(sum(row['type'] == 'total' for row in rows), 2)
|
||||
log = Path(work) / 'session.log'
|
||||
log.write_bytes(result.stderr)
|
||||
counters = report(log)
|
||||
self.assertEqual(41, counters['handlerCalls'])
|
||||
self.assertGreater(counters['handlerWallNs'], counters['handlerCpuNs'])
|
||||
self.assertEqual(40, counters['totals'][0]['calls'])
|
||||
@@ -22,7 +22,7 @@ PACKAGES = [line.split()[1] for line in VARIANTS.read_text().splitlines()
|
||||
def guest_prefix(package):
|
||||
source = SERVICE.read_text()
|
||||
before_environment = source.split("val guest = ArrayList<String>()", 1)[1].split(
|
||||
"addClientEnvironment(guest, steamHere)", 1)[0]
|
||||
"addClientEnvironment(guest,", 1)[0]
|
||||
environment = source.split("private fun addClientEnvironment(", 1)[1].split(
|
||||
'guest.add("HOME=/root")', 1)[0]
|
||||
prefix = []
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Steam owns game caps; the nested compositor follows the output refresh rate."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
|
||||
|
||||
class SessionPacingTest(unittest.TestCase):
|
||||
def launch(self, refresh, **overrides):
|
||||
source = SESSION.read_text()
|
||||
start = source.index(' width=${BL_WIDTH:-1280}')
|
||||
end = source.index('\nfi\n\nbl_displays()', start)
|
||||
block = source[start:end].replace('/usr/local/bin/droiddeck-pipewire', 'pipewire_stub')
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
env = dict(os.environ, XDG_RUNTIME_DIR=directory, BL_REFRESH=str(refresh),
|
||||
BL_MANGOAPP='0', BL_FPS='0', DROIDDECK_GAME_FRAME_LIMIT='0')
|
||||
env.update(overrides)
|
||||
script = '''
|
||||
set -u
|
||||
mode=steam
|
||||
pipewire_stub() { return 1; }
|
||||
run_gamescope() { printf 'ARG:%s\\n' "$@"; }
|
||||
''' + block
|
||||
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True,
|
||||
text=True, timeout=5)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return [line.removeprefix('ARG:') for line in result.stdout.splitlines()
|
||||
if line.startswith('ARG:')]
|
||||
|
||||
def test_display_refresh_sets_the_nested_compositor_rate(self):
|
||||
for refresh in (60, 90, 120):
|
||||
with self.subTest(refresh=refresh):
|
||||
args = self.launch(refresh)
|
||||
self.assertEqual(str(refresh), args[args.index('-r') + 1])
|
||||
self.assertIn('-e', args)
|
||||
|
||||
def test_retired_cap_variables_do_not_override_the_display_rate(self):
|
||||
for performance in ('0', '1'):
|
||||
with self.subTest(performance=performance):
|
||||
args = self.launch(120, BL_FPS='30', DROIDDECK_GAME_FRAME_LIMIT=performance)
|
||||
self.assertEqual('120', args[args.index('-r') + 1])
|
||||
self.assertNotIn('--framerate-limit', args)
|
||||
|
||||
def test_retired_cap_cannot_set_the_rate_when_the_display_rate_is_unknown(self):
|
||||
args = self.launch(0, BL_FPS='30', DROIDDECK_GAME_FRAME_LIMIT='1')
|
||||
self.assertNotIn('-r', args)
|
||||
self.assertNotIn('--framerate-limit', args)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -69,6 +69,44 @@ class SteamCompatEnvironmentTest(unittest.TestCase):
|
||||
os.kill(helper_pid, 9)
|
||||
self.fail('droiddeck-steam-compat outlived the session')
|
||||
|
||||
def test_the_x86_64_client_gets_only_the_file_dialog_bridge(self):
|
||||
source = (BIN / 'droiddeck-session').read_text()
|
||||
start = source.index(' if [ "$steam_x64" = 1 ]; then\n { droiddeck-steam-compat --files-only')
|
||||
block = source[start:source.index(' fi\n', start) + len(' fi\n')]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
helper = root / 'droiddeck-steam-compat'
|
||||
helper.write_text('#!/bin/sh\necho "$@" >> "$ARGS_FILE"\n')
|
||||
helper.chmod(0o755)
|
||||
for x64, expected in (('1', '--files-only /steam'), ('0', '/steam')):
|
||||
with self.subTest(x64=x64):
|
||||
args = root / ('args-' + x64)
|
||||
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
|
||||
ARGS_FILE=str(args), steam_root='/steam', steam_x64=x64)
|
||||
subprocess.run(['bash', '-c', '_bl_compat_env=(env)\n' + block + 'wait\n'], env=env, timeout=10, check=True)
|
||||
self.assertEqual(args.read_text().split('\n')[0], expected)
|
||||
|
||||
def test_files_only_mode_installs_only_the_file_dialog_hook(self):
|
||||
import runpy
|
||||
compat = runpy.run_path(str(BIN / 'droiddeck-steam-compat'))
|
||||
calls = []
|
||||
|
||||
class Page:
|
||||
def __init__(self, port, path):
|
||||
self.ws = None
|
||||
def evaluate(self, expression):
|
||||
calls.append(('evaluate', expression[:40]))
|
||||
return True
|
||||
def call(self, method, params):
|
||||
calls.append((method, params['name']))
|
||||
|
||||
helper = compat['Helper']('/steam', 1234, files_only=True)
|
||||
helper.attach.__globals__.update(shared_context=lambda port: '/devtools/page/1', Page=Page)
|
||||
self.assertTrue(helper.attach())
|
||||
bindings = [name for method, name in calls if method == 'Runtime.addBinding']
|
||||
self.assertEqual(bindings, [compat['FILE_BINDING']])
|
||||
self.assertIn(('evaluate', compat['FILE_JS'][:40]), calls)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -277,11 +277,40 @@ class CloudHooks(unittest.TestCase):
|
||||
for sh in (compat.LAUNCHER_SH, compat.EXTRA_WRAPPER_SH):
|
||||
self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh)
|
||||
self.assertNotIn('exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh)
|
||||
self.assertIn('[ $? -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP)
|
||||
self.assertIn('[ $rc -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP)
|
||||
self.assertIn('droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}"', compat.BL_STORE_SETUP)
|
||||
self.assertIn('exec "$@"', compat.BL_STORE_SETUP)
|
||||
|
||||
|
||||
BNET_EXE = '/root/.local/share/Steam/steamapps/compatdata/2596113170/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe'
|
||||
|
||||
|
||||
class BattleNet(unittest.TestCase):
|
||||
def test_a_games_shortcut_is_handed_to_droiddeck_battlenet(self):
|
||||
self.assertEqual([store.BATTLENET, 'launch', 'Fen'], store.battlenet(['waitforexitandrun', BNET_EXE, '--exec=launch Fen'], env={}))
|
||||
self.assertEqual([store.BATTLENET, 'launch', 'OSI'], store.battlenet(['"%s"' % BNET_EXE, '--exec="launch OSI"'], env={}))
|
||||
self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE], env={}))
|
||||
|
||||
def test_anything_else_and_its_own_starts_are_left_alone(self):
|
||||
other = BNET_EXE.replace('2596113170', '123')
|
||||
self.assertIsNone(store.battlenet([other, '--exec=launch Fen'], env={}))
|
||||
self.assertIsNone(store.battlenet(['/x/Diablo IV/Diablo IV.exe'], env={}))
|
||||
self.assertIsNone(store.battlenet([BNET_EXE, '--exec=launch Fen'], env={'BL_BATTLENET': '1'}))
|
||||
self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE, '--exec=launch Fen;rm'], env={}))
|
||||
|
||||
def test_the_launch_runs_there_and_the_wrapper_ends_with_it(self):
|
||||
with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=0) as call:
|
||||
os.environ.pop('BL_BATTLENET', None)
|
||||
self.assertEqual(store.RAN, store.main([BNET_EXE, '--exec=launch Pro']))
|
||||
call.assert_called_once_with([store.BATTLENET, 'launch', 'Pro'])
|
||||
with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=1):
|
||||
os.environ.pop('BL_BATTLENET', None)
|
||||
self.assertEqual(store.RAN_FAILED, store.main([BNET_EXE, '--exec=launch Pro']))
|
||||
self.assertIn('[ $rc -eq 11 ] && exit 0', compat.BL_STORE_SETUP)
|
||||
self.assertIn('[ $rc -eq 12 ] && exit 1', compat.BL_STORE_SETUP)
|
||||
self.assertLess(compat.BL_STORE_SETUP.index('droiddeck-store-launch "$@"'), compat.BL_STORE_SETUP.index('[ $rc -eq 11 ] && exit 0'))
|
||||
|
||||
|
||||
class Launchers(unittest.TestCase):
|
||||
def test_both_proton_launchers_ask_before_proton_starts(self):
|
||||
sh = compat.LAUNCHER_SH
|
||||
|
||||
Reference in new issue
Block a user