mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-26 00:06:02 +00:00
Merge org main 5aa245cf into the non-Adreno test branch
Conflicts resolved keeping both sides: main's comment cleanup (#764) taken where only comments differed; the test branch's code kept everywhere else. ensureAuto runs main's Quest auto drivers before the Mali paths; vkp_update_map keeps the Quest layer path and the completion-unknown check (pass_begin goes through it); gamescope backend selection plus main's steam-mode cursor composite; droiddeck-session's watcher is main's shared loop with the Venus GL probe after it; SessionFiles/runtime_inputs/build.yml carry both the Xclipse layer and main's VR assets. Main's GPU detection test follows the non-Adreno support text; the Steam presentation test finds its block by code, not by a removed comment.
This commit is contained in:
commit
75612da44b
1016 files changed
+95104
-48259
No files matched your search
@@ -3,7 +3,6 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Exercise the real cache with Vulkan lifetime callbacks, without an Android surface or GPU. */
|
||||
#define VK_PRESENT_H
|
||||
const char *vkp_gpu_name(void) { return "cache test"; }
|
||||
void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; }
|
||||
@@ -61,7 +60,6 @@ int main(int argc, char **argv) {
|
||||
assert(scene_ensure(source, 1280, 720) == 0);
|
||||
VkImageView original = bound_view;
|
||||
if (!strcmp(argv[1], "recycled")) {
|
||||
/* The owner destroys the image, then Vulkan reuses its handle at the same size. */
|
||||
vkp_effects_forget_image(source);
|
||||
assert(freed_sets == 1 && freed_views == 1);
|
||||
assert(scene_ensure(source, 1280, 720) == 0);
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define WL_POINTER_BUTTON_STATE_RELEASED 0
|
||||
#define WL_POINTER_FRAME_SINCE_VERSION 5
|
||||
struct wl_resource { int version, releases, frames; uint32_t held; };
|
||||
struct seat_pointer { struct wl_resource *ptr, *focus; };
|
||||
static struct seat_pointer g_ptrs[3];
|
||||
static int g_nptrs = 3;
|
||||
static void *g_grab, *g_display;
|
||||
static unsigned motion_calls, flushes;
|
||||
static uint32_t now_ms(void) { return 42; }
|
||||
static uint32_t wl_display_next_serial(void *d) { (void)d; return 1; }
|
||||
static int wl_resource_get_version(struct wl_resource *r) { return r->version; }
|
||||
static void wl_pointer_send_frame(struct wl_resource *r) { r->frames++; }
|
||||
static void wl_display_flush_clients(void *d) { (void)d; flushes++; }
|
||||
static void wl_pointer_send_button(struct wl_resource *r, uint32_t serial,
|
||||
uint32_t t, uint32_t button, uint32_t state) {
|
||||
(void)serial; (void)t;
|
||||
assert(state == WL_POINTER_BUTTON_STATE_RELEASED);
|
||||
r->held &= ~(1u << (button - 0x110));
|
||||
r->releases++;
|
||||
}
|
||||
/* The old dispatcher calls this even for releases, emitting stale coordinates.
|
||||
* Recording this boundary detects that unwanted motion/focus routing path. */
|
||||
static void pointer_input(double x, double y, int relative, uint32_t button, int pressed) {
|
||||
assert(x == 0 && y == 0 && relative == 1 && button >= 0x110 && button <= 0x112);
|
||||
assert(pressed == 1);
|
||||
motion_calls++;
|
||||
}
|
||||
#include "pointer_button.inc"
|
||||
#define BTN_LEFT 0x110
|
||||
#define MAX_TOUCH_POINTS 2
|
||||
struct touch_point { int pointer_fallback; };
|
||||
static struct touch_point g_touch_points[MAX_TOUCH_POINTS];
|
||||
struct seat_touch { struct wl_resource *touch, *focus; };
|
||||
static struct seat_touch g_touches[1];
|
||||
static int g_ntouches = 1, cancels;
|
||||
static void wl_touch_send_cancel(struct wl_resource *r) { (void)r; cancels++; }
|
||||
#include "touch_cancel_all.inc"
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
struct wl_resource surface = {0};
|
||||
struct wl_resource a = {.version = 5, .held = 7};
|
||||
struct wl_resource b = {.version = 4, .held = 7};
|
||||
struct wl_resource other = {.version = 5, .held = 7};
|
||||
g_ptrs[0] = (struct seat_pointer){&a, &surface};
|
||||
g_ptrs[1] = (struct seat_pointer){&b, &surface};
|
||||
g_ptrs[2] = (struct seat_pointer){&other, NULL};
|
||||
g_grab = &surface;
|
||||
if (!strcmp(argv[1], "fallback") || !strcmp(argv[1], "native")) {
|
||||
int fallback = !strcmp(argv[1], "fallback");
|
||||
g_touches[0] = (struct seat_touch){&a, &surface};
|
||||
g_touch_points[0].pointer_fallback = fallback;
|
||||
touch_cancel_all();
|
||||
assert(!motion_calls && cancels == 1 && !g_touches[0].focus);
|
||||
assert(!g_touch_points[0].pointer_fallback);
|
||||
assert(a.releases == fallback && a.held == (fallback ? 6u : 7u));
|
||||
for (uint32_t button = 0x110; button <= 0x112; button++) pointer_button(button, 0);
|
||||
assert(!motion_calls && !a.held && !b.held && !g_grab);
|
||||
} else if (!strcmp(argv[1], "press")) {
|
||||
pointer_button(0x110, 1);
|
||||
assert(motion_calls == 1 && !a.releases && g_grab == &surface);
|
||||
} else if (!strcmp(argv[1], "unfocused")) {
|
||||
g_ptrs[0].focus = g_ptrs[1].focus = NULL;
|
||||
pointer_button(0x110, 0);
|
||||
assert(!motion_calls && !a.releases && !b.releases && !other.releases);
|
||||
assert(!g_grab);
|
||||
} else if (!strcmp(argv[1], "cleanup")) {
|
||||
for (uint32_t button = 0x110; button <= 0x112; button++) pointer_button(button, 0);
|
||||
assert(!motion_calls && !a.held && !b.held && other.held == 7);
|
||||
assert(a.releases == 3 && b.releases == 3 && !other.releases);
|
||||
assert(!g_grab && flushes == 3);
|
||||
} else {
|
||||
assert(!strcmp(argv[1], "focused"));
|
||||
a.held = b.held = 1;
|
||||
pointer_button(0x110, 0);
|
||||
assert(!motion_calls && !a.held && !b.held);
|
||||
assert(a.releases == 1 && b.releases == 1 && !other.releases);
|
||||
assert(a.frames == 1 && !b.frames && !other.frames);
|
||||
assert(g_ptrs[0].focus == &surface && g_ptrs[1].focus == &surface);
|
||||
assert(!g_grab && flushes == 1);
|
||||
}
|
||||
puts("PASS");
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/sem.h>
|
||||
|
||||
int main(void) {
|
||||
int creator = semget(0x5eed0001, 1, IPC_CREAT | IPC_EXCL | 0600);
|
||||
if (creator < 0) { perror("semget"); return 1; }
|
||||
struct semid_ds ds;
|
||||
if (semctl(creator, 0, IPC_STAT, &ds) != 0 || ds.sem_otime != 0 || ds.sem_ctime == 0) {
|
||||
printf("FAIL: a new set has otime %ld ctime %ld\n", (long)ds.sem_otime, (long)ds.sem_ctime);
|
||||
return 1;
|
||||
}
|
||||
struct sembuf up = {0, 1, 0};
|
||||
if (semop(creator, &up, 1) != 0) { perror("semop"); return 1; }
|
||||
int other = semget(0x5eed0001, 1, 0600);
|
||||
if (other < 0 || semctl(other, 0, IPC_STAT, &ds) != 0 || ds.sem_otime == 0) {
|
||||
printf("FAIL: otime still 0 after semop\n");
|
||||
return 1;
|
||||
}
|
||||
if (semctl(other, 0, GETVAL) != 1) { printf("FAIL: value\n"); return 1; }
|
||||
semctl(creator, 0, IPC_RMID);
|
||||
printf("PASS: sysv otime\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -1,6 +1,3 @@
|
||||
// Drives Java_com_termux_terminal_JNI_createSubprocess against a mock JNIEnv that tracks local
|
||||
// references the way ART does, so the JNI hygiene of app/src/main/cpp/termux/termux.c can be
|
||||
// checked on the host. Built and run by tools/tests/test_termux_jni.py.
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -26,7 +23,6 @@ static jsize mock_array_length(JNIEnv* TERMUX_UNUSED(env), jarray array)
|
||||
static jobject mock_get_element(JNIEnv* TERMUX_UNUSED(env), jobjectArray TERMUX_UNUSED(array), jsize TERMUX_UNUSED(index))
|
||||
{
|
||||
if (++live_refs > peak_refs) peak_refs = live_refs;
|
||||
// ART aborts the process here: "local reference table overflow (max=512)".
|
||||
if (live_refs > LOCAL_REF_LIMIT) overflowed = 1;
|
||||
return (jobject) malloc(1);
|
||||
}
|
||||
@@ -53,7 +49,6 @@ static void mock_release_utf(JNIEnv* TERMUX_UNUSED(env), jstring string, const c
|
||||
{
|
||||
for (size_t i = 0; i < sizeof(pinned) / sizeof(pinned[0]); i++) {
|
||||
if (pinned[i].owner != NULL && pinned[i].chars == chars) {
|
||||
// Releasing chars against some other string is a JNI contract violation.
|
||||
if (pinned[i].owner != string) mismatched_releases++;
|
||||
free(pinned[i].chars);
|
||||
pinned[i].owner = NULL;
|
||||
@@ -83,7 +78,6 @@ int main(int argc, char** argv)
|
||||
jsize arg_count = atoi(argv[1]);
|
||||
jsize env_count = atoi(argv[2]);
|
||||
|
||||
// The struct is JNINativeInterface in the NDK's header and JNINativeInterface_ in the JDK's.
|
||||
__typeof__(**(JNIEnv*) 0) table = {
|
||||
.GetArrayLength = mock_array_length,
|
||||
.GetObjectArrayElement = mock_get_element,
|
||||
@@ -97,7 +91,6 @@ int main(int argc, char** argv)
|
||||
};
|
||||
const __typeof__(table)* env = &table;
|
||||
|
||||
// Arrays are modelled as their length; the caller's own references are not counted.
|
||||
jsize args = arg_count, envs = env_count;
|
||||
jint pid_slot[1] = {0};
|
||||
jstring cmd = (jstring) "cmd", cwd = (jstring) "cwd";
|
||||
|
||||
@@ -46,7 +46,6 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
"""
|
||||
|
||||
# Shell builtins only: anything it ran would be an x86 program, handed back to it.
|
||||
HANDLER = "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$HANDLER_LOG\"\nexit 7\n"
|
||||
|
||||
|
||||
@@ -61,7 +60,7 @@ class BinfmtPreloadTest(unittest.TestCase):
|
||||
cls.library = cls.tmp / "libbinfmt.so"
|
||||
subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-DBINFMT_TEST",
|
||||
'-DBINFMT_HANDLER="%s"' % cls.handler, "-o", str(cls.library),
|
||||
"-pthread"] + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c")] + ["-ldl"],
|
||||
"-pthread"] + [str(PRELOAD / name) for name in ("binfmt.c", "net.c", "udevmon.c", "pathcache.c", "webhelper.c")] + ["-ldl"],
|
||||
check=True)
|
||||
source = cls.tmp / "program.c"
|
||||
source.write_text(PROGRAM)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SRC = ROOT / 'app' / 'src' / 'main' / 'cpp' / 'waylandcomp' / 'src'
|
||||
TOOLS = ROOT / 'tools' / 'cardboard'
|
||||
|
||||
|
||||
def spirv_words(header: str) -> list[str]:
|
||||
return re.findall(r'0x[0-9a-fA-F]{8}', header)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which('cc'), 'needs a C compiler')
|
||||
class CardboardParamsTest(unittest.TestCase):
|
||||
def test_clamp_and_push_constant_layout(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
binary = str(Path(folder) / 'test-cardboard')
|
||||
subprocess.run(['cc', '-std=c11', '-Wall', '-Wextra', '-Werror', '-O2', '-DCARDBOARD_HOST_TEST',
|
||||
'-D_DEFAULT_SOURCE', f'-I{SRC}', f'-I{Path(folder)}', '-o', binary,
|
||||
str(TOOLS / 'test_cardboard_params.c'), str(SRC / 'cardboard.c'), '-lm'],
|
||||
check=True, cwd=folder, env=self._env(folder))
|
||||
result = subprocess.run([binary], capture_output=True, text=True, check=True, timeout=10)
|
||||
self.assertIn('PASS: cardboard params', result.stdout)
|
||||
|
||||
@staticmethod
|
||||
def _env(folder):
|
||||
import os
|
||||
stub = Path(folder) / 'vulkan'
|
||||
stub.mkdir(exist_ok=True)
|
||||
(stub / 'vulkan.h').write_text('typedef struct VkDevice_T *VkDevice; typedef struct VkImage_T *VkImage;\n'
|
||||
'typedef struct VkCommandBuffer_T *VkCommandBuffer;\n'
|
||||
'typedef struct { int unused; } VkPhysicalDeviceMemoryProperties;\n')
|
||||
return dict(os.environ)
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which('glslangValidator'), 'needs glslangValidator')
|
||||
class CardboardShaderTest(unittest.TestCase):
|
||||
def test_committed_spirv_matches_the_glsl(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
out = Path(folder) / 'cardboard_frag.h'
|
||||
subprocess.run(['glslangValidator', '-V', '--vn', 'cardboard_frag_code', '-o', str(out),
|
||||
str(SRC / 'cardboard.frag')], check=True, capture_output=True)
|
||||
self.assertEqual(spirv_words(out.read_text()), spirv_words((SRC / 'cardboard_frag.h').read_text()),
|
||||
'cardboard_frag.h is stale: regenerate it from cardboard.frag (see cardboard.c)')
|
||||
|
||||
def test_push_constants_fit_the_guaranteed_range(self):
|
||||
glsl = (SRC / 'cardboard.frag').read_text()
|
||||
block = glsl[glsl.index('uniform PC {'):glsl.index('} pc;')]
|
||||
self.assertLessEqual(16 * len(re.findall(r'\bvec4\b', block)), 128)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -16,7 +16,7 @@ class CdpGuardTest(unittest.TestCase):
|
||||
def setUpClass(cls):
|
||||
cls.build = tempfile.TemporaryDirectory()
|
||||
cls.library = Path(cls.build.name) / "net.so"
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), "-x", "c", "-", "-ldl",
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), str(SOURCE.parent / "webhelper.c"), "-x", "c", "-", "-ldl",
|
||||
"-o", str(cls.library)],
|
||||
input=b"int bl_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True)
|
||||
|
||||
|
||||
@@ -13,8 +13,6 @@ class DesktopRemovalInventoryTest(unittest.TestCase):
|
||||
self.assertIn('usr/bin/lxqt-session', paths)
|
||||
self.assertIn('usr/bin/labwc', paths)
|
||||
self.assertIn('usr/local/bin/steamdeck-desktop', paths)
|
||||
# The runtime pacman database did not protect libseat on the Thor. Removing it
|
||||
# made gamescope and every Steam/native session exit 127 after desktop cleanup.
|
||||
self.assertNotIn('usr/lib/libseat.so.1', paths)
|
||||
self.assertNotIn('usr/lib/libseat.so', paths)
|
||||
self.assertFalse(any(p.startswith('usr/lib/libSDL2') for p in paths))
|
||||
|
||||
@@ -21,7 +21,6 @@ FAKE = r"""
|
||||
|
||||
int real_opendirs;
|
||||
|
||||
/* COARSE=1: directory stats that never change, like NTFS's whole-second times and fixed size. */
|
||||
static void coarse(const char *path, struct stat *st) {
|
||||
if (getenv("COARSE") && strstr(path, "/fuse/") && S_ISDIR(st->st_mode)) {
|
||||
st->st_mtim = st->st_ctim = (struct timespec){1, 0};
|
||||
@@ -70,7 +69,6 @@ int statfs(const char *path, struct statfs *out) {
|
||||
return r;
|
||||
}
|
||||
|
||||
/* FASTPATH=1: open directories the way the fast-path preload does, through fdopendir. */
|
||||
DIR *opendir(const char *path) {
|
||||
static DIR *(*next)(const char *);
|
||||
if (!next) next = dlsym(RTLD_NEXT, "opendir");
|
||||
|
||||
@@ -91,6 +91,37 @@ class AgentTest(unittest.TestCase):
|
||||
self.assertFalse(path.exists(), "the request file is consumed")
|
||||
return json.loads((self.dir / "resp" / "req.json").read_text())
|
||||
|
||||
def vr_helper(self, body):
|
||||
helper = self.dir / "droiddeck-steamvr"
|
||||
helper.write_text("#!/bin/sh\n" + body)
|
||||
old = os.environ.get("DROIDDECK_VR_HELPER")
|
||||
os.environ["DROIDDECK_VR_HELPER"] = str(helper)
|
||||
self.addCleanup(lambda: os.environ.pop("DROIDDECK_VR_HELPER") if old is None
|
||||
else os.environ.__setitem__("DROIDDECK_VR_HELPER", old))
|
||||
return helper
|
||||
|
||||
def test_vr_status_is_parsed(self):
|
||||
self.vr_helper('echo "installed=1 running=0 installing=0 driver=1"\n')
|
||||
answer = self.ask({"kind": "vr", "action": "status"})
|
||||
self.assertTrue(answer["ok"])
|
||||
self.assertEqual((True, False, False, True),
|
||||
(answer["installed"], answer["running"], answer["installing"], answer["driver"]))
|
||||
|
||||
def test_vr_runs_only_its_own_actions(self):
|
||||
log = self.dir / "args"
|
||||
self.vr_helper('echo "$@" > %s\n' % log)
|
||||
self.assertTrue(self.ask({"kind": "vr", "action": "start"})["ok"])
|
||||
self.assertEqual("start", log.read_text().strip())
|
||||
answer = self.ask({"kind": "vr", "action": "rm -rf /"})
|
||||
self.assertFalse(answer["ok"])
|
||||
self.assertEqual("INVALID_REQUEST", answer["error"]["code"])
|
||||
|
||||
def test_vr_without_a_helper_is_unavailable(self):
|
||||
os.environ["DROIDDECK_VR_HELPER"] = str(self.dir / "missing")
|
||||
self.addCleanup(os.environ.pop, "DROIDDECK_VR_HELPER")
|
||||
answer = self.ask({"kind": "vr", "action": "status"})
|
||||
self.assertEqual("UNAVAILABLE", answer["error"]["code"])
|
||||
|
||||
def test_exec_output_and_status(self):
|
||||
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "echo out; echo err >&2; exit 3"], "env": {"X": "1"}})
|
||||
self.assertTrue(answer["ok"])
|
||||
@@ -224,6 +255,42 @@ class AgentTest(unittest.TestCase):
|
||||
answer = self.ask({"kind": "steam-selection"})
|
||||
self.assertEqual("INVALID_SELECTION", answer["error"]["code"])
|
||||
|
||||
def test_shortcut_cgameid_waits_for_exact_steam_overview_mapping(self):
|
||||
game_id = str((3551182975 << 32) | 0x02000000)
|
||||
self.assertEqual(3551182975, agent.steam_shortcut_app_id(game_id))
|
||||
self.assertIsNone(agent.steam_shortcut_app_id("413150"))
|
||||
self.assertIsNone(agent.steam_shortcut_app_id(str((3551182975 << 32) | 0x03000000)))
|
||||
clock = [0.0]
|
||||
with patch.object(agent, "cdp_eval", side_effect=[{"value": None}, {"value": "3551182975"}]) as evaluate, \
|
||||
patch.object(agent.time, "monotonic", side_effect=lambda: clock[0]), \
|
||||
patch.object(agent.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)):
|
||||
result = agent.wait_for_steam_shortcut_overview(self.dir, game_id, timeout=1)
|
||||
self.assertEqual({"supported": True, "ready": True, "appId": 3551182975}, result)
|
||||
expression = evaluate.call_args_list[0].args[1]
|
||||
self.assertIn("GetAppOverviewByGameID", expression)
|
||||
self.assertIn(json.dumps(game_id), expression)
|
||||
self.assertNotIn("RequestAppDetails", expression)
|
||||
self.assertFalse(evaluate.call_args_list[0].kwargs["await_promise"])
|
||||
|
||||
def test_wrong_overview_app_id_keeps_shortcut_url_held_until_timeout(self):
|
||||
game_id = str((3537741571 << 32) | 0x02000000)
|
||||
clock = [0.0]
|
||||
with patch.object(agent, "cdp_eval", return_value={"value": "646570"}) as evaluate, \
|
||||
patch.object(agent.time, "monotonic", side_effect=lambda: clock[0]), \
|
||||
patch.object(agent.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)):
|
||||
with self.assertRaises(agent.AgentError) as raised:
|
||||
agent.wait_for_steam_shortcut_overview(self.dir, game_id, timeout=0.5)
|
||||
self.assertEqual("STEAM_OVERVIEW_TIMEOUT", raised.exception.code)
|
||||
self.assertGreater(evaluate.call_count, 0)
|
||||
self.assertTrue(all("RequestAppDetails" not in call.args[1] for call in evaluate.call_args_list))
|
||||
|
||||
def test_normal_steam_ids_and_unknown_cgameids_skip_overview_wait(self):
|
||||
for game_id in ("413150", str((123456789 << 32) | 0x03000000), "18446744073709551616"):
|
||||
with self.subTest(game_id=game_id), patch.object(agent, "cdp_eval") as evaluate:
|
||||
result = agent.wait_for_steam_shortcut_overview(self.dir, game_id)
|
||||
self.assertFalse(result["supported"])
|
||||
evaluate.assert_not_called()
|
||||
|
||||
def test_cdp_exception(self):
|
||||
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
|
||||
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
|
||||
|
||||
@@ -499,19 +499,23 @@ class AppInfoTest(unittest.TestCase):
|
||||
table = struct.pack("<I", len(strings)) + b"".join(s.encode() + b"\0" for s in strings)
|
||||
return struct.pack("<IIq", magic, 1, table_at) + body + table
|
||||
|
||||
def test_linux_only_titles_are_sent_to_fex(self):
|
||||
def test_linux_only_titles_are_sent_to_fex_and_dual_platform_is_deferred(self):
|
||||
for magic in (0x07564427, 0x07564428, 0x07564429):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
steam = Path(tmp)
|
||||
(steam / "appcache").mkdir()
|
||||
(steam / "appcache/appinfo.vdf").write_bytes(self.appinfo({
|
||||
10: ("windows", "", "Game"), 20: ("linux", "64", "Game"), 30: ("windows,linux,macos", "", "game"),
|
||||
40: ("linux", "arm64", "game"), 50: ("linux", "", "Demo"), 70: ("linux", "", "Tool"), 80: ("linux", "", "config"),
|
||||
40: ("linux", "arm64", "game"), 41: ("windows,linux", "aarch64", "game"),
|
||||
50: ("linux", "", "Demo"), 70: ("linux", "", "Tool"), 80: ("linux", "", "config"),
|
||||
90: ("linux", "", ""),
|
||||
}, magic))
|
||||
self.COMPAT["APPINFO_CACHE"].clear()
|
||||
targets = self.COMPAT["native_targets"](str(steam), ["10", "20", "30", "40", "50", "70", "80", "90", "1628350", "60"])
|
||||
self.assertEqual(targets, {"20": "droiddeck-fex", "50": "droiddeck-fex"}, hex(magic))
|
||||
targets = self.COMPAT["native_targets"](str(steam), ["10", "20", "30", "40", "41", "50", "70", "80", "90", "1628350", "60"])
|
||||
self.assertEqual(targets, {
|
||||
"20": "droiddeck-fex", "30": self.COMPAT["NATIVE_CHOICE"],
|
||||
"40": None, "41": None, "50": "droiddeck-fex",
|
||||
}, hex(magic))
|
||||
|
||||
def test_titles_with_a_valve_pick_are_found_installed_or_not(self):
|
||||
def deck(oslist, runtime, kind="game"):
|
||||
@@ -545,14 +549,34 @@ class AppInfoTest(unittest.TestCase):
|
||||
self.assertEqual(changes, {"30": "GE-Proton11-7", "32": "GE-Proton11-7"})
|
||||
self.assertEqual(auto, {"30": "GE-Proton11-7", "32": "GE-Proton11-7"})
|
||||
|
||||
def test_the_mapping_sends_native_titles_to_fex_and_keeps_picks(self):
|
||||
def test_automatic_native_mapping_uses_fex_and_keeps_explicit_tools(self):
|
||||
tool, fex = self.COMPAT["TOOL"], self.COMPAT["FEX_TOOL"]
|
||||
changes, auto = self.COMPAT["plan_mapping"](
|
||||
{"0": tool, "20": "fex", "21": "steamlinuxruntime_sniper", "22": "GE-Proton11-7"},
|
||||
["20", "21", "22", "23", "24"], [tool, "GE-Proton11-7"], tool, {},
|
||||
{"20": fex, "21": fex, "22": fex, "23": fex})
|
||||
self.assertEqual(changes, {"20": fex, "21": fex, "23": fex, "24": tool})
|
||||
self.assertEqual(auto, {"20": fex, "21": fex, "23": fex, "24": tool})
|
||||
self.assertEqual(changes, {"23": fex, "24": tool})
|
||||
self.assertEqual(auto, {"23": fex, "24": tool})
|
||||
|
||||
def test_explicit_linux_runtime_and_fex_selections_survive_default_maintenance(self):
|
||||
tool, fex = self.COMPAT["TOOL"], self.COMPAT["FEX_TOOL"]
|
||||
changes, auto = self.COMPAT["plan_mapping"](
|
||||
{"0": tool, "20": "steamlinuxruntime_arm64", "21": fex},
|
||||
["20", "21"], [tool], tool, {}, {"20": None, "21": fex}, ["20", "21"])
|
||||
self.assertEqual(changes, {})
|
||||
self.assertEqual(auto, {})
|
||||
|
||||
def test_native_arm64_default_stays_unmapped_and_old_auto_proton_is_cleared(self):
|
||||
tool = self.COMPAT["TOOL"]
|
||||
changes, auto = self.COMPAT["plan_mapping"](
|
||||
{"0": tool, "20": tool}, ["20"], [tool], tool, {"20": tool}, {"20": None}, ["20"])
|
||||
self.assertEqual(changes, {"20": None})
|
||||
self.assertEqual(auto, {})
|
||||
|
||||
changes, auto = self.COMPAT["plan_mapping"](
|
||||
{"0": tool}, ["20"], [tool], tool, {}, {"20": None}, ["20"])
|
||||
self.assertEqual(changes, {})
|
||||
self.assertEqual(auto, {})
|
||||
|
||||
def test_the_tool_files(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
||||
@@ -12,6 +12,7 @@ import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
@@ -28,8 +29,6 @@ def load(name):
|
||||
ctl = load("droiddeckctl")
|
||||
scenario = load("droiddeck-scenario")
|
||||
|
||||
# A stand-in for adb: answers the provider's content calls from a JSON config (a list answers
|
||||
# successive calls), records every invocation, and fakes the few shell commands droiddeckctl uses.
|
||||
FAKE_ADB = textwrap.dedent('''\
|
||||
#!/usr/bin/env python3
|
||||
import base64, json, os, sys
|
||||
@@ -58,6 +57,8 @@ FAKE_ADB = textwrap.dedent('''\
|
||||
print(config.get("dumpsys_display", ""))
|
||||
elif args[:3] == ["shell", "dumpsys", "power"]:
|
||||
print(" mWakefulness=Awake")
|
||||
elif args[:3] == ["shell", "dumpsys", "SurfaceFlinger"] and "-dump" in args:
|
||||
print(config.get("timestats", ""))
|
||||
elif args[:2] == ["exec-out", "screencap"]:
|
||||
sys.stdout.buffer.write(b"\\x89PNG fake")
|
||||
with open(config["log"], "a") as log:
|
||||
@@ -80,6 +81,32 @@ DUMPSYS_DISPLAY = textwrap.dedent('''\
|
||||
''')
|
||||
|
||||
|
||||
def timestats_record(name, frames, histogram, hz):
|
||||
bins = " ".join(f"{ms}ms={histogram.get(ms, 0)}" for ms in (8, 16, 17, 25, 33, 50))
|
||||
return (f"displayRefreshRate = {hz} fps\nrenderRate = {hz} fps\nuid = 10479\nlayerName = {name}\n"
|
||||
f"packageName = \ntotalFrames = {frames}\ndroppedFrames = 0\n"
|
||||
f"present2present histogram is as below:\n{bins}\nlatch2present histogram is as below:\n8ms={frames}\n")
|
||||
|
||||
|
||||
# A capture where the panel went from 60 to 120 Hz: the game layer is split in two records. The
|
||||
# activity's own window and an unrelated app draw too, and must not count.
|
||||
TIMESTATS_SPLIT = "SurfaceFlinger TimeStats:\ntotalFrames = 2000\n" + "".join([
|
||||
timestats_record("droiddeck_wayland_game#6110", 900, {16: 700, 33: 199}, 60),
|
||||
timestats_record("droiddeck_wayland_game#6110", 900, {16: 850, 25: 49}, 120),
|
||||
timestats_record("com.droiddeck.launcher/com.droiddeck.launcher.SessionActivity#6097", 8, {16: 7}, 60),
|
||||
timestats_record("f291fb6 SurfaceView[com.droiddeck.launcher/com.droiddeck.launcher.SessionActivity]#6101",
|
||||
30, {33: 29}, 60),
|
||||
timestats_record("StatusBar#106", 1, {}, 60),
|
||||
])
|
||||
|
||||
# A build that presents the game on the session's SurfaceView instead of a layer of its own.
|
||||
TIMESTATS_SURFACEVIEW = "SurfaceFlinger TimeStats:\n" + "".join([
|
||||
timestats_record("a1b2c3 SurfaceView[com.droiddeck.launcher/com.droiddeck.launcher.SessionActivity]#77",
|
||||
1800, {16: 1796, 33: 3}, 120),
|
||||
timestats_record("a1b2c3 SurfaceView[com.other.app/com.other.app.Main]#12", 500, {8: 499}, 120),
|
||||
])
|
||||
|
||||
|
||||
def state(phase="READY", focused=None, focusable=()):
|
||||
focus = None if focused is None else {"focusedApp": focused, "focusableApps": list(focusable),
|
||||
"baselayerAppIds": [], "seq": 1, "t": 0}
|
||||
@@ -124,6 +151,15 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
self.assertEqual("INVALID_REQUEST", caught.exception.code)
|
||||
self.assertFalse(self.calls())
|
||||
|
||||
def test_a_variant_package_is_reached_through_its_own_provider_and_activity(self):
|
||||
with unittest.mock.patch.dict(os.environ, {"DROIDDECK_PACKAGE": "com.antutu.benchmark.full"}):
|
||||
variant = load("droiddeckctl")
|
||||
self.assertEqual("content://com.antutu.benchmark.full.agent", variant.AUTHORITY)
|
||||
with self.assertRaises(variant.ControlError): # the fake adb does not answer `am start`
|
||||
variant.start_agent_activity(str(self.adb), "fake-1", {"mode": "steam"})
|
||||
started = [e["args"] for e in self.calls() if e["args"][:3] == ["shell", "am", "start"]]
|
||||
self.assertIn("com.antutu.benchmark.full/com.droiddeck.launcher.agent.AgentStartActivity", started[0])
|
||||
|
||||
def test_state_passes_through_with_the_serial(self):
|
||||
self.configure({"state": state()})
|
||||
code, out = self.run_ctl("state")
|
||||
@@ -136,7 +172,6 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
"launch": {"ok": True, "command": "launch", "appId": "489830"},
|
||||
"state": [state(focused=769, focusable=[769]), state(focused=489830, focusable=[769])],
|
||||
})
|
||||
# Focus alone is not enough: the game must also be in the list Steam orders from.
|
||||
code, out = self.run_ctl("launch", "489830", "--wait", "--timeout", "1")
|
||||
self.assertEqual(5, code)
|
||||
self.assertEqual("TIMEOUT", out["error"]["code"])
|
||||
@@ -193,7 +228,7 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
code, out = self.run_ctl("run", "/usr/bin/sh", "--", "-c", "true")
|
||||
self.assertEqual(7, code)
|
||||
self.assertEqual("AGENT_COMMANDS_DISABLED", out["error"]["code"])
|
||||
self.assertIn("Debugging tools", out["error"]["message"])
|
||||
self.assertIn("Setup > Diagnostics > Debugging tools", out["error"]["message"])
|
||||
self.assertEqual(["access"], [c.get("method") for c in self.calls()])
|
||||
|
||||
def test_override_checks_names_before_pushing_any_file(self):
|
||||
@@ -236,6 +271,40 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
self.assertEqual(2, code)
|
||||
self.assertEqual("NO_SUCH_DISPLAY", out["error"]["code"])
|
||||
|
||||
def test_pacing_sums_split_records_of_the_game_layer_only(self):
|
||||
summary = ctl.pacing_summary(TIMESTATS_SPLIT, "com.droiddeck.launcher")
|
||||
self.assertEqual(["droiddeck_wayland_game"], summary["layers"])
|
||||
self.assertEqual(1800, summary["frames"])
|
||||
self.assertEqual([60, 120], summary["refreshRates"])
|
||||
self.assertEqual({"16": 1550, "25": 49, "33": 199}, summary["presentToPresentMs"])
|
||||
self.assertEqual(16, summary["cadenceMs"])
|
||||
self.assertEqual(248, summary["offCadence"])
|
||||
self.assertEqual(13.8, summary["offCadencePercent"])
|
||||
|
||||
def test_pacing_falls_back_to_the_sessions_surfaceview(self):
|
||||
summary = ctl.pacing_summary(TIMESTATS_SURFACEVIEW, "com.droiddeck.launcher")
|
||||
self.assertEqual(1, len(summary["layers"]))
|
||||
self.assertIn("SurfaceView[com.droiddeck.launcher/", summary["layers"][0])
|
||||
self.assertEqual(1800, summary["frames"])
|
||||
self.assertEqual(3, summary["offCadence"])
|
||||
|
||||
def test_pacing_captures_then_turns_timestats_off(self):
|
||||
self.configure({}, timestats=TIMESTATS_SURFACEVIEW)
|
||||
with unittest.mock.patch.object(ctl.time, "sleep"):
|
||||
code, out = self.run_ctl("pacing", "--seconds", "1")
|
||||
self.assertEqual(0, code)
|
||||
self.assertEqual("pacing", out["command"])
|
||||
self.assertIn("fpsOnScreen", out)
|
||||
sf = [c["args"][3:] for c in self.calls() if c["args"][:3] == ["shell", "dumpsys", "SurfaceFlinger"]]
|
||||
self.assertEqual([["--timestats", "-clear", "-enable"], ["--timestats", "-dump"], ["--timestats", "-disable"]], sf)
|
||||
|
||||
def test_pacing_without_a_session_on_screen_exits_4(self):
|
||||
self.configure({}, timestats="SurfaceFlinger TimeStats:\n" + timestats_record("StatusBar#1", 3, {16: 2}, 60))
|
||||
with unittest.mock.patch.object(ctl.time, "sleep"):
|
||||
code, out = self.run_ctl("pacing", "--seconds", "1")
|
||||
self.assertEqual(4, code)
|
||||
self.assertEqual("NO_FRAMES", out["error"]["code"])
|
||||
|
||||
def test_input_requests(self):
|
||||
self.configure({"input": {"ok": True, "command": "input"}})
|
||||
self.run_ctl("input", "tap", "0.5", "0.25", "--space", "fraction")
|
||||
@@ -333,7 +402,7 @@ class ScenarioTest(FakeAdbTest):
|
||||
"steps": [["state"], {"assert": "session.focus.focusedApp", "equals": 489830}]})
|
||||
code, report = self.run_scenario(path)
|
||||
self.assertEqual(1, code)
|
||||
self.assertEqual(1, len(report["runs"])) # stops at the first failure without --keep-going
|
||||
self.assertEqual(1, len(report["runs"]))
|
||||
self.assertIn("is 769", report["runs"][0]["error"])
|
||||
evidence = json.loads((Path(report["runs"][0]["folder"]) / "evidence.json").read_text())
|
||||
self.assertEqual(769, evidence["focus"]["focusedApp"])
|
||||
|
||||
@@ -29,7 +29,6 @@ class EffectsSourceCacheTest(unittest.TestCase):
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-effects-cache-')
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
folder = Path(cls.temp.name)
|
||||
# Copy only Vulkan headers so Android's libc headers cannot shadow the host's libc.
|
||||
shutil.copytree(headers, folder / 'include/vulkan', ignore=shutil.ignore_patterns('*.hpp'))
|
||||
if (headers.parent / 'vk_video').is_dir():
|
||||
shutil.copytree(headers.parent / 'vk_video', folder / 'include/vk_video')
|
||||
|
||||
@@ -156,9 +156,44 @@ class SystemGraphicsLaunchTest(unittest.TestCase):
|
||||
self.assertEqual(args, [path, *selected])
|
||||
self.assertEqual(actual_env["WINESERVER"], "/sync-pack/wineserver")
|
||||
self.assertEqual(actual_env["BL_SYNC_PACK"], "selected")
|
||||
class ReadConfigMappingTest(unittest.TestCase):
|
||||
def test_missing_parent_or_unbalanced_vdf_is_not_treated_as_absent_choices(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = Path(tmp) / "config.vdf"
|
||||
config.write_text('"InstallConfigStore" { "Software" { "Other" {} } }')
|
||||
self.assertIsNone(COMPAT["read_config_mapping"](str(config)))
|
||||
config.write_text('"InstallConfigStore" { "Software" { "Valve" { "Steam" {} }')
|
||||
self.assertIsNone(COMPAT["read_config_mapping"](str(config)))
|
||||
|
||||
def test_valid_steam_parent_without_compat_mapping_has_no_per_app_choices(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = Path(tmp) / "config.vdf"
|
||||
config.write_text('"InstallConfigStore" { "Software" { "Valve" { "Steam" {} } } }')
|
||||
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {})
|
||||
|
||||
|
||||
class GameEnvironmentTest(unittest.TestCase):
|
||||
def test_directaudio_capture_follows_the_session_microphone_setting(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
probe = home / "probe"
|
||||
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('BANNER_AUDIO_DIRECT_MIC', 'unset'))\n")
|
||||
probe.chmod(0o755)
|
||||
config = home / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
for enabled, override, expected in (("1", None, "1"), ("0", "1", "0"), ("1", "0", "0")):
|
||||
with self.subTest(enabled=enabled, override=override):
|
||||
profile = {} if override is None else {
|
||||
"BANNER_AUDIO_DIRECT_MIC": override, "BL_MIC_ENABLED": override,
|
||||
}
|
||||
config.write_text(json.dumps({"version": 1, "games": {"42": profile}}))
|
||||
env = dict(os.environ, HOME=tmp, BL_MIC_ENABLED=enabled,
|
||||
BANNER_AUDIO_DIRECT_MIC="1", STEAM_COMPAT_DATA_PATH="/compatdata/42")
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"),
|
||||
str(probe), "waitforexitandrun"],
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
self.assertEqual(result.stdout.strip(), expected)
|
||||
|
||||
def test_the_install_script_evaluator_gets_its_scripts_marked_first(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
@@ -317,6 +352,25 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
(other / "Other.exe").touch()
|
||||
self.assertEqual(MODULE["engine_fixes"](str(other / "Other.exe"), []), ({}, [], []))
|
||||
|
||||
def test_arkham_city_gets_full_x87_precision_over_the_preset(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
city = Path(tmp) / "Batman Arkham City GOTY/Binaries/Win32"
|
||||
city.mkdir(parents=True)
|
||||
for name in ("BatmanAC.exe", "BmLauncher.exe"):
|
||||
(city / name).touch()
|
||||
for exe in ("BatmanAC.exe", "BmLauncher.exe"):
|
||||
env, extra, notes = MODULE["engine_fixes"](str(city / exe), [])
|
||||
self.assertEqual((env, extra), ({"FEX_X87REDUCEDPRECISION": "0"}, []))
|
||||
config = {"version": 1, "shared": {"FEX_X87REDUCEDPRECISION": "1"}}
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "200260", env)["FEX_X87REDUCEDPRECISION"], "0")
|
||||
config["games"] = {"200260": {"FEX_X87REDUCEDPRECISION": "1"}}
|
||||
self.assertEqual(MODULE["apply_config"]({}, config, "200260", env)["FEX_X87REDUCEDPRECISION"], "1")
|
||||
asylum = Path(tmp) / "Batman Arkham Asylum GOTY/Binaries"
|
||||
asylum.mkdir(parents=True)
|
||||
for name in ("ShippingPC-BmGame.exe", "BmLauncher.exe"):
|
||||
(asylum / name).touch()
|
||||
self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], []))
|
||||
|
||||
def test_a_new_fix_only_needs_registering(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
(Path(tmp) / "Game.exe").touch()
|
||||
@@ -556,8 +610,6 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertIn("GE-Proton11-7", [entry["name"] for entry in COMPAT["tool_catalog"](str(home), None)])
|
||||
|
||||
def test_droiddeck_proton_is_adopted_and_labelled_like_any_other_extra(self):
|
||||
# Its folder has a space ("DroidDeck-Proton 11-7.5") and its internal name starts with
|
||||
# "DroidDeck-Proton-", which lower-cases to our own tools' prefix: neither may matter.
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
(home / "label").write_text("Compatible\n")
|
||||
@@ -585,15 +637,12 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
config.write_text(config_text([("0", COMPAT["TOOL"]), ("42", "DroidDeck-Proton-11-7.5")]))
|
||||
COMPAT["register_default"](str(config), ["42", "43"], protect=protect)
|
||||
self.assertEqual(mapping_of(config.read_text()), {"0": COMPAT["TOOL"], "42": "DroidDeck-Proton-11-7.5", "43": COMPAT["TOOL"]})
|
||||
# Once removed it is no longer runnable, and its games go back to the default.
|
||||
changes, _ = COMPAT["plan_mapping"]({"0": COMPAT["TOOL"], "42": "DroidDeck-Proton-11-7.5"}, ["42"], [COMPAT["TOOL"]], COMPAT["TOOL"], {})
|
||||
self.assertEqual(changes, {"42": COMPAT["TOOL"]})
|
||||
|
||||
def test_both_proton_wrappers_call_environment_launcher(self):
|
||||
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
|
||||
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
|
||||
# Started through bl_run, which execs it - or, for a store game with cloud saves, waits
|
||||
# for it so droiddeck-store-launch --exited can follow (test_store_launch.CloudHooks).
|
||||
self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', script)
|
||||
|
||||
def test_wrappers_preload_the_session_library_before_the_input_shim(self):
|
||||
@@ -635,6 +684,218 @@ class ProtonDefaultTest(unittest.TestCase):
|
||||
self.assertEqual(changes, {"0": "GE-Proton11-7", "10": "GE-Proton11-7", "11": "GE-Proton11-7", "14": "GE-Proton11-7"})
|
||||
self.assertEqual(auto, {"10": "GE-Proton11-7", "11": "GE-Proton11-7", "14": "GE-Proton11-7"})
|
||||
|
||||
def test_windows_only_titles_still_follow_the_default(self):
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
{"0": self.TOOL}, ["42"], self.NAMES, self.TOOL, {})
|
||||
self.assertEqual(changes, {"42": self.TOOL})
|
||||
self.assertEqual(auto, {"42": self.TOOL})
|
||||
|
||||
def test_native_arm64_default_clears_only_our_auto_mapping(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = Path(tmp) / "config.vdf"
|
||||
config.write_text(config_text([("0", self.TOOL), ("42", self.TOOL)]))
|
||||
(Path(tmp) / "state.json").write_text(json.dumps({
|
||||
"default": self.TOOL,
|
||||
"auto": {"42": self.TOOL},
|
||||
}))
|
||||
globals_ = COMPAT["register_default"].__globals__
|
||||
original_native_targets = globals_["native_targets"]
|
||||
globals_["native_targets"] = lambda _root, _apps: {"42": None}
|
||||
try:
|
||||
COMPAT["register_default"](
|
||||
str(config), ["42"], catalog=self.CATALOG, directory=tmp)
|
||||
first = config.read_bytes()
|
||||
self.assertEqual(mapping_of(first.decode()), {"0": self.TOOL})
|
||||
self.assertEqual(COMPAT["tokenize"](first.decode()),
|
||||
COMPAT["tokenize"](config_text([("0", self.TOOL)])))
|
||||
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["auto"], {})
|
||||
|
||||
COMPAT["register_default"](
|
||||
str(config), ["42"], catalog=self.CATALOG, directory=tmp)
|
||||
self.assertEqual(config.read_bytes(), first)
|
||||
finally:
|
||||
globals_["native_targets"] = original_native_targets
|
||||
|
||||
def test_saved_native_choice_survives_valve_pick_without_appinfo(self):
|
||||
app = "452280"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
steam = root / "Steam"
|
||||
config = steam / "config/config.vdf"
|
||||
config.parent.mkdir(parents=True)
|
||||
(steam / "steamapps").mkdir()
|
||||
(steam / "steamapps" / ("appmanifest_%s.acf" % app)).write_text("")
|
||||
config.write_text(config_text([("0", self.TOOL)]))
|
||||
(root / "state.json").write_text(json.dumps({
|
||||
"default": self.TOOL,
|
||||
"auto": {},
|
||||
"native": [app],
|
||||
}))
|
||||
|
||||
globals_ = COMPAT["register_default"].__globals__
|
||||
original_native_targets = globals_["native_targets"]
|
||||
globals_["native_targets"] = lambda _root, _apps: {}
|
||||
try:
|
||||
COMPAT["register_default"](
|
||||
str(config), [], catalog=self.CATALOG, directory=tmp, picks=[app])
|
||||
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL})
|
||||
state = json.loads((root / "state.json").read_text())
|
||||
self.assertEqual(state["auto"], {})
|
||||
self.assertEqual(state["native"], [app])
|
||||
finally:
|
||||
globals_["native_targets"] = original_native_targets
|
||||
|
||||
def test_shortcuts_scanner_keeps_native_choice_for_unrelated_app_list(self):
|
||||
app, added_shortcut = "452280", "3537741571"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
steam = root / "Steam"
|
||||
config = steam / "config/config.vdf"
|
||||
config.parent.mkdir(parents=True)
|
||||
(steam / "steamapps").mkdir()
|
||||
(steam / "steamapps" / ("appmanifest_%s.acf" % app)).write_text("")
|
||||
config.write_text(config_text([("0", self.TOOL)]))
|
||||
(root / "state.json").write_text(json.dumps({
|
||||
"default": self.TOOL,
|
||||
"auto": {},
|
||||
"native": [app],
|
||||
}))
|
||||
|
||||
globals_ = COMPAT["register_default"].__globals__
|
||||
original_native_targets = globals_["native_targets"]
|
||||
globals_["native_targets"] = lambda _root, wanted: {
|
||||
app: COMPAT["NATIVE_CHOICE"]
|
||||
} if app in wanted else {}
|
||||
try:
|
||||
COMPAT["register_default"](
|
||||
str(config), [app], catalog=self.CATALOG, directory=tmp)
|
||||
self.assertEqual(json.loads((root / "state.json").read_text())["native"], [app])
|
||||
|
||||
COMPAT["register_default"](
|
||||
str(config), [added_shortcut], catalog=self.CATALOG, directory=tmp)
|
||||
state = json.loads((root / "state.json").read_text())
|
||||
self.assertEqual(state["native"], [app])
|
||||
self.assertEqual(state["auto"], {added_shortcut: self.TOOL})
|
||||
self.assertEqual(mapping_of(config.read_text()), {
|
||||
"0": self.TOOL,
|
||||
added_shortcut: self.TOOL,
|
||||
})
|
||||
finally:
|
||||
globals_["native_targets"] = original_native_targets
|
||||
|
||||
def test_factorio_preserves_an_observed_native_choice_despite_ambiguous_metadata(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
steam = Path(tmp) / "Steam"
|
||||
config = steam / "config/config.vdf"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(config_text([("0", self.TOOL)]))
|
||||
state = {"default": self.TOOL, "auto": {}}
|
||||
(Path(tmp) / "state.json").write_text(json.dumps(state))
|
||||
|
||||
globals_ = COMPAT["native_targets"].__globals__
|
||||
original_platforms = globals_["appinfo_platforms"]
|
||||
globals_["appinfo_platforms"] = lambda _path, wanted: {
|
||||
"427520": ({"linux", "macos", "windows"}, "", "game")
|
||||
} if "427520" in wanted else {}
|
||||
try:
|
||||
native = COMPAT["native_targets"](str(steam), ["427520"])
|
||||
self.assertIs(native["427520"], COMPAT["NATIVE_CHOICE"])
|
||||
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
{"0": self.TOOL}, ["427520"], self.NAMES, self.TOOL, {}, native)
|
||||
self.assertEqual(changes, {"427520": self.TOOL})
|
||||
self.assertEqual(auto, {"427520": self.TOOL})
|
||||
|
||||
COMPAT["register_default"](
|
||||
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
|
||||
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL, "427520": self.TOOL})
|
||||
|
||||
state["auto"] = {"427520": self.TOOL}
|
||||
(Path(tmp) / "state.json").write_text(json.dumps(state))
|
||||
config.write_text(config_text([("0", self.TOOL)]))
|
||||
COMPAT["register_default"](
|
||||
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
|
||||
first = config.read_bytes()
|
||||
self.assertEqual(mapping_of(first.decode()), {"0": self.TOOL})
|
||||
self.assertEqual(COMPAT["tokenize"](first.decode()),
|
||||
COMPAT["tokenize"](config_text([("0", self.TOOL)])))
|
||||
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["auto"], {})
|
||||
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native"], ["427520"])
|
||||
|
||||
COMPAT["register_default"](
|
||||
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
|
||||
self.assertEqual(config.read_bytes(), first)
|
||||
|
||||
config.write_text(config_text([("0", self.TOOL), ("427520", "")]))
|
||||
COMPAT["register_default"](
|
||||
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
|
||||
native_choice = config.read_bytes()
|
||||
self.assertEqual(mapping_of(native_choice.decode()), {"0": self.TOOL, "427520": ""})
|
||||
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["auto"], {})
|
||||
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native"], ["427520"])
|
||||
COMPAT["register_default"](
|
||||
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
|
||||
self.assertEqual(config.read_bytes(), native_choice)
|
||||
|
||||
for choice in (COMPAT["FEX_TOOL"], COMPAT["TOOL_11"], "GE-Proton11-7"):
|
||||
config.write_text(config_text([("0", self.TOOL), ("427520", choice)]))
|
||||
COMPAT["register_default"](
|
||||
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
|
||||
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL, "427520": choice})
|
||||
self.assertEqual(json.loads((Path(tmp) / "state.json").read_text())["native"], [])
|
||||
|
||||
state = json.loads((Path(tmp) / "state.json").read_text())
|
||||
state["native"] = ["427520"]
|
||||
state["auto"] = {}
|
||||
(Path(tmp) / "state.json").write_text(json.dumps(state))
|
||||
config.write_text(config_text([("0", self.TOOL), ("427520", "proton_experimental")]))
|
||||
COMPAT["register_default"](
|
||||
str(config), ["427520"], catalog=self.CATALOG, directory=tmp)
|
||||
self.assertEqual(mapping_of(config.read_text()), {"0": self.TOOL, "427520": self.TOOL})
|
||||
saved = json.loads((Path(tmp) / "state.json").read_text())
|
||||
self.assertEqual(saved["native"], [])
|
||||
self.assertEqual(saved["auto"], {"427520": self.TOOL})
|
||||
finally:
|
||||
globals_["appinfo_platforms"] = original_platforms
|
||||
|
||||
def test_native_arm64_preserves_a_proton_mapping_without_managed_state(self):
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
{"0": self.TOOL, "42": self.TOOL}, ["42"], self.NAMES, self.TOOL,
|
||||
{"42": self.TOOL}, {"42": None}, managed=())
|
||||
self.assertEqual(changes, {})
|
||||
self.assertEqual(auto, {})
|
||||
|
||||
def test_native_arm64_keeps_a_chosen_valve_proton_through_its_wrapper(self):
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
{"0": self.TOOL, "42": "proton_experimental"}, ["42"], self.NAMES,
|
||||
self.TOOL, {}, {"42": None})
|
||||
self.assertEqual(changes, {"42": self.TOOL})
|
||||
self.assertEqual(auto, {})
|
||||
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
{"0": self.TOOL, "42": self.TOOL}, ["42"], self.NAMES,
|
||||
self.TOOL, {}, {"42": None})
|
||||
self.assertEqual(changes, {})
|
||||
self.assertEqual(auto, {})
|
||||
|
||||
def test_native_arm64_keeps_explicit_runtime_fex_and_proton_profiles(self):
|
||||
fex = COMPAT["FEX_TOOL"]
|
||||
current = {
|
||||
"0": self.TOOL,
|
||||
"42": COMPAT["TOOL_11"],
|
||||
"43": "GE-Proton11-7",
|
||||
"44": "steamlinuxruntime_arm64",
|
||||
"45": fex,
|
||||
"46": "",
|
||||
}
|
||||
changes, auto = COMPAT["plan_mapping"](
|
||||
current, ["42", "43", "44", "45", "46"], self.NAMES, self.TOOL, {},
|
||||
{app: None for app in ("42", "43", "44", "45", "46")},
|
||||
overrides={"46": "GE-Proton11-7"},
|
||||
)
|
||||
self.assertEqual(changes, {"46": "GE-Proton11-7"})
|
||||
self.assertEqual(auto, {})
|
||||
|
||||
def test_titles_following_the_default_move_with_it_and_picks_stay(self):
|
||||
current = {"0": self.TOOL, "10": self.TOOL, "11": "GE-Proton11-7", "12": self.TOOL}
|
||||
auto = {"10": self.TOOL, "11": self.TOOL, "12": self.TOOL}
|
||||
@@ -779,8 +1040,6 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
wine = self.tool / "files/bin-arm64/wine"
|
||||
wine.write_text("#!/bin/sh\necho wine-11.0-4c8f2e1 '(Staging)'\n")
|
||||
wine.chmod(0o755)
|
||||
# Proton's own winepulse.so names the audio interface: the classic table never imports
|
||||
# PsCreateSystemThread, the system-thread one (Proton-CachyOS) always does.
|
||||
(self.tool / "files/lib/wine/aarch64-unix").mkdir(parents=True)
|
||||
self.winepulse = self.tool / "files/lib/wine/aarch64-unix/winepulse.so"
|
||||
self.winepulse.write_bytes(b"\x7fELF classic wine 11 pulse driver")
|
||||
@@ -822,8 +1081,6 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
result = self.run_setup()
|
||||
self.assertIn("DirectAudio selected", result.stderr)
|
||||
self.assertIn("WINEDLLPATH=%s/lib/wine" % self.audio, result.stdout)
|
||||
# Proton-CachyOS's mmdevapi takes the driver list from this variable, and its launcher
|
||||
# pre-sets it to pulse,alsa unless it is already set.
|
||||
self.assertIn("WINE_AUDIO_DRIVER=directaudio,pulse\n", result.stdout)
|
||||
self.assertEqual(self.link("system32"), str(self.audio / "lib/wine/aarch64-windows/winedirectaudio.drv"))
|
||||
self.assertEqual(self.link("syswow64"), str(self.audio / "lib/wine/i386-windows/winedirectaudio.drv"))
|
||||
@@ -916,16 +1173,11 @@ class StartWithoutSteamTest(unittest.TestCase):
|
||||
game = [str(ge), "waitforexitandrun", "/games/Game.exe", "-windowed"]
|
||||
self.assertEqual(start(game, {}, "3384071994"), (game, {}))
|
||||
on = {"DROIDDECK_NO_STEAM": "1"}
|
||||
# An added game (a shortcut id) has no Steam fixes: UMU_ID 0. The command is unchanged.
|
||||
self.assertEqual(start(game, on, "3384071994"), (game, dict(on, UMU_ID="0")))
|
||||
# A Steam game keeps its protonfixes under its own id.
|
||||
self.assertEqual(start(game, on, "570940")[1]["UMU_ID"], "570940")
|
||||
# A UMU_ID the user set wins.
|
||||
self.assertEqual(start(game, dict(on, UMU_ID="umu-1"), "570940")[1]["UMU_ID"], "umu-1")
|
||||
# Valve's Proton has no umu launch: the game runs straight in the prefix.
|
||||
plain = [str(valve)] + game[1:]
|
||||
self.assertEqual(start(plain, on, "570940"), ([str(valve), "runinprefix", "/games/Game.exe", "-windowed"], on))
|
||||
# Only a game launch: the client's own runs and other verbs are left alone.
|
||||
for other in ([str(ge), "run", "/x.exe"], [str(ge), "waitforexitandrun"], [str(valve), "getcompatpath", "/x"]):
|
||||
self.assertEqual(start(other, on, "570940"), (other, on))
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ class LauncherCoresTest(unittest.TestCase):
|
||||
self.proc = self.root / 'proc'
|
||||
self.proc.mkdir()
|
||||
cpufreq = self.root / 'cpu'
|
||||
for cpu in ALL: # 0-5 one cluster, 6-7 the fast one
|
||||
for cpu in ALL:
|
||||
(cpufreq / f'cpu{cpu}/cpufreq').mkdir(parents=True)
|
||||
(cpufreq / f'cpu{cpu}/cpufreq/cpuinfo_max_freq').write_text('3532800\n' if cpu < 6 else '4320000\n')
|
||||
self.cores = FakeCores()
|
||||
@@ -118,7 +118,7 @@ class LauncherCoresTest(unittest.TestCase):
|
||||
self.process(100, LAUNCHER)
|
||||
self.process(200, HELPER)
|
||||
self.process(9, '/root/.local/share/Steam/steamrtarm64/steam')
|
||||
self.governor.tick() # no focus file yet
|
||||
self.governor.tick()
|
||||
self.focus_on(9, app=769)
|
||||
self.governor.tick()
|
||||
self.focus_on(100)
|
||||
@@ -141,7 +141,6 @@ class LauncherCoresTest(unittest.TestCase):
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
# A new thread, and a new helper process the held one started: both born held.
|
||||
self.thread(200, 203, {5}, NICE)
|
||||
self.process(500, HELPER, (501,), cpus={5}, nice=NICE)
|
||||
self.now += 10
|
||||
@@ -156,16 +155,16 @@ class LauncherCoresTest(unittest.TestCase):
|
||||
self.process(400, GAME)
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.cores.state[201] = (ALL, -5) # the program raised a thread's priority itself
|
||||
self.cores.state[201] = (ALL, -5)
|
||||
self.now += 5
|
||||
self.governor.tick()
|
||||
self.assertFalse(self.held(201)) # not looked at again before the rescan
|
||||
self.assertFalse(self.held(201))
|
||||
self.now += 5
|
||||
self.governor.tick()
|
||||
self.assertTrue(self.held(201))
|
||||
self.focus_on(200)
|
||||
self.governor.tick()
|
||||
self.assertEqual((ALL, 0), self.cores.state[201]) # its first state, not the program's
|
||||
self.assertEqual((ALL, 0), self.cores.state[201])
|
||||
|
||||
def test_a_steady_hold_is_not_rewritten(self):
|
||||
self.process(200, HELPER, (201,))
|
||||
@@ -182,7 +181,7 @@ class LauncherCoresTest(unittest.TestCase):
|
||||
self.process(200, HELPER, (201,))
|
||||
self.process(300, HELPER)
|
||||
self.process(400, GAME)
|
||||
del self.cores.state[201] # ended between the listing and the call
|
||||
del self.cores.state[201]
|
||||
self.focus_on(400)
|
||||
self.governor.tick()
|
||||
self.assertNotIn(201, self.holder.held[200])
|
||||
|
||||
@@ -22,6 +22,8 @@ IFACE = NAME + ".Manager"
|
||||
|
||||
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
|
||||
class SleepHandshakeTest(unittest.TestCase):
|
||||
ARGS = []
|
||||
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.dir = Path(self.directory.name)
|
||||
@@ -35,7 +37,7 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
lambda bus, sender, path, interface, name, body: self.signals.append(body.unpack()[0]))
|
||||
env = dict(os.environ, BL_LAUNCH_DIR=str(self.dir),
|
||||
DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"])
|
||||
self.process = subprocess.Popen(["/usr/bin/python3", str(SCRIPT)], env=env,
|
||||
self.process = subprocess.Popen(["/usr/bin/python3", str(SCRIPT), *self.ARGS], env=env,
|
||||
stdout=subprocess.DEVNULL)
|
||||
self.wait_for(lambda: (self.dir / "steam-sleep-ready").exists())
|
||||
|
||||
@@ -80,7 +82,7 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
token = self.suspend()
|
||||
self.assertTrue(self.preparing())
|
||||
self.state(token, "paused")
|
||||
self.state("0" * 32, "awake") # stale session acknowledgments cannot wake this one
|
||||
self.state("0" * 32, "awake")
|
||||
time.sleep(0.1)
|
||||
self.assertTrue(self.preparing())
|
||||
self.state(token, "awake")
|
||||
@@ -218,5 +220,22 @@ class SleepHandshakeTest(unittest.TestCase):
|
||||
self.call(IFACE, "PowerOff", GLib.Variant("(b)", (True,)))
|
||||
|
||||
|
||||
class WithNetworkManagerTest(SleepHandshakeTest):
|
||||
ARGS = ["--with-netmanager"]
|
||||
|
||||
def owner(self, name):
|
||||
return self.bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
|
||||
"GetConnectionUnixProcessID", GLib.Variant("(s)", (name,)), None,
|
||||
Gio.DBusCallFlags.NONE, 2000, None).unpack()[0]
|
||||
|
||||
def test_one_process_owns_login1_and_networkmanager(self):
|
||||
self.wait_for(lambda: self.bus.call_sync(
|
||||
"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner",
|
||||
GLib.Variant("(s)", ("org.freedesktop.NetworkManager",)), None,
|
||||
Gio.DBusCallFlags.NONE, 2000, None).unpack()[0])
|
||||
self.assertEqual(self.owner("org.freedesktop.NetworkManager"), self.process.pid)
|
||||
self.assertEqual(self.owner(NAME), self.process.pid)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -119,6 +119,32 @@ class LayoutTest(unittest.TestCase):
|
||||
inst.select()
|
||||
self.assertEqual(inst.included_components, {"Up", "Wide"})
|
||||
|
||||
def test_a_duplicate_onto_the_file_itself_is_skipped(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "cab" / "dotnet.exe"
|
||||
src.parent.mkdir()
|
||||
src.write_bytes(b"MZ")
|
||||
out = Path(tmp) / "out"
|
||||
inst = installer({
|
||||
"Directory": rows("Directory Directory_Parent DefaultDir",
|
||||
("TARGETDIR", "", "SourceDir"),
|
||||
("ProgramFilesFolder", "TARGETDIR", "PFiles"),
|
||||
("DOTNETHOME", "ProgramFilesFolder", "dotnet"),
|
||||
("DOTNETHOME_X86", "ProgramFilesFolder", "dotnet")),
|
||||
"Component": rows("Component Directory_ Attributes Condition KeyPath",
|
||||
("Host", "DOTNETHOME", "0", "", "DotnetExe")),
|
||||
"Feature": rows("Feature Feature_Parent Level", ("Main", "", "1")),
|
||||
"FeatureComponents": rows("Feature_ Component_", ("Main", "Host")),
|
||||
"File": rows("File Component_ FileName", ("DotnetExe", "Host", "dotnet.exe")),
|
||||
"DuplicateFile": rows("FileKey Component_ File_ DestName DestFolder",
|
||||
("Dup", "Host", "DotnetExe", "", "DOTNETHOME_X86")),
|
||||
}, out=str(out))
|
||||
inst.select()
|
||||
inst.install_files({"DotnetExe": src})
|
||||
placed = out / "drive_c/Program Files (x86)/dotnet/dotnet.exe"
|
||||
self.assertEqual(placed.read_bytes(), b"MZ")
|
||||
self.assertEqual(inst.counts["files"], 1)
|
||||
|
||||
def test_global_assembly_paths(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
dll = Path(tmp) / "a.dll"
|
||||
@@ -240,13 +266,11 @@ class RegistryApplyTest(unittest.TestCase):
|
||||
text = (self.pfx / "system.reg").read_text()
|
||||
self.assertIn('"Version"="4.0"', text)
|
||||
self.assertIn('"Kept"="mine"', text)
|
||||
# Through the Wow6432Node\Classes link into the shared Classes\Wow6432Node key, never under the link.
|
||||
self.assertIn('[Software\\\\Classes\\\\Wow6432Node\\\\CLSID\\\\{X}]', text)
|
||||
self.assertNotIn('[Software\\\\Wow6432Node\\\\Classes\\\\CLSID', text)
|
||||
self.assertIn('"PATH"=str(2):"C:\\\\PhysX;%SystemRoot%\\\\system32;%SystemRoot%"', text)
|
||||
self.assertNotIn("[System\\\\CurrentControlSet\\\\", text)
|
||||
self.assertIn('"Opt"=dword:00000002', (self.pfx / "user.reg").read_text())
|
||||
# The prefix's own spelling of Program Files (x86) is kept.
|
||||
self.assertTrue((self.pfx / "drive_c/program files (x86)/Microsoft XNA/xna.dll").is_file())
|
||||
self.assertFalse((self.pfx / "drive_c/Program Files (x86)").exists())
|
||||
|
||||
|
||||
@@ -117,7 +117,6 @@ class NetworkObjectsTest(unittest.TestCase):
|
||||
self.assertTrue(secured["RsnFlags"].unpack() & 0x100)
|
||||
self.assertTrue(secured["RsnFlags"].unpack() & 0x400)
|
||||
self.assertEqual(found[nm.ap_path(other["bssid"])][nm.NAME + ".AccessPoint"]["Flags"].unpack(), 0)
|
||||
# Keep nearby-network discovery while a cellular connection provides the default route.
|
||||
cellular = nm.objects(dict(CELLULAR, accessPoints=[other]))
|
||||
self.assertIn(nm.ap_path(other["bssid"]), cellular)
|
||||
self.assertEqual(cellular[nm.ROOT + "/Devices/Wifi"][nm.NAME + ".Device.Wireless"]["ActiveAccessPoint"].unpack(), "/")
|
||||
@@ -131,7 +130,6 @@ class NetworkBusTest(unittest.TestCase):
|
||||
self.write(WIFI)
|
||||
self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
||||
env = dict(os.environ, DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"])
|
||||
# Use the production service and only redirect its input file for the fixture.
|
||||
launch = "import runpy,sys; from pathlib import Path; n=runpy.run_path(sys.argv[1]); g=n['main'].__globals__; g['SNAPSHOT']=Path(sys.argv[2]); g['SCAN_REQUEST']=Path(sys.argv[2]).with_suffix('.request'); n['main']()"
|
||||
self.process = subprocess.Popen([sys.executable, "-c", launch, str(SCRIPT), str(self.snapshot)], env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
@@ -217,7 +215,6 @@ class NetworkBusTest(unittest.TestCase):
|
||||
self.assertTrue(any(interface == nm.OBJECT_MANAGER and member == "InterfacesRemoved" and args[0] == nm.AP
|
||||
for _, interface, member, args in signals))
|
||||
self.assertTrue(any(member == "AccessPointAdded" for _, _, member, _ in signals))
|
||||
# A missing/invalid snapshot is a transient input error, never a fake Ethernet handover.
|
||||
self.snapshot.write_text("{")
|
||||
time.sleep(1.2)
|
||||
self.assertEqual(self.prop(nm.ROOT, nm.NAME, "PrimaryConnectionType"), "802-11-wireless")
|
||||
@@ -250,8 +247,6 @@ class NetworkBusTest(unittest.TestCase):
|
||||
from gi.repository import NM
|
||||
except ValueError:
|
||||
self.skipTest("requires gir1.2-nm-1.0")
|
||||
# libnm is a real consumer of the same API Steam reads. It caches objects by path,
|
||||
# so the handover must replace the Wi-Fi device with a modem rather than mutate its type.
|
||||
previous = os.environ.get("DBUS_SYSTEM_BUS_ADDRESS")
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = os.environ["DBUS_SESSION_BUS_ADDRESS"]
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Test the renderer's actual map and inverse map without a Vulkan device."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class GameTopMappingTest(unittest.TestCase):
|
||||
def test_letterbox_alignment_and_touch_inverse(self):
|
||||
cc = shutil.which(os.environ.get('CC', 'cc'))
|
||||
if not cc:
|
||||
self.skipTest('A host C compiler is required')
|
||||
source = (REPO / 'app/src/main/cpp/waylandcomp/src/vk_present.c').read_text()
|
||||
header = (REPO / 'app/src/main/cpp/waylandcomp/src/vk_present.h').read_text()
|
||||
enums = header[header.index('enum vkp_scale_mode'):header.index('void vk_present_set_scale_mode')]
|
||||
state = source[source.index('static volatile int g_mode'):source.index('static int64_t g_swap_retry_at_ns')]
|
||||
def function(signature):
|
||||
start = source.index(signature)
|
||||
return source[start:source.index('\n}\n', start) + 3]
|
||||
funcs = '\n'.join(function(name) for name in ['static const char *mode_name(',
|
||||
'static const char *align_name(', 'static void update_map(', 'int vkp_output_to_scene(', 'int vkp_game_picture_rect('])
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
code = '#include <assert.h>\n#include <math.h>\n#include <stdio.h>\n#include <string.h>\n#include <pthread.h>\n'
|
||||
code += '#define droiddeck_log(...) ((void)0)\nstatic struct { unsigned width, height; } g_extent;\n'
|
||||
code += enums + state + funcs
|
||||
code += r'''
|
||||
static void near(double a, double b) { assert(fabs(a - b) < 0.01); }
|
||||
static void check(int sw, int sh, int ow, int oh, int alignment) {
|
||||
g_extent.width = ow; g_extent.height = oh;
|
||||
g_mode = VKP_MODE_FIT; g_align = alignment;
|
||||
update_map(sw, sh);
|
||||
float rect[4];
|
||||
assert(vkp_game_picture_rect(rect));
|
||||
double top = alignment == VKP_ALIGN_PICTURE_TOP ? 0 : oh - sh * g_map.ky;
|
||||
near(rect[0], g_map.off_x); near(rect[1], top);
|
||||
near(rect[2], g_map.off_x + sw * g_map.kx);
|
||||
near(rect[3], top + sh * g_map.ky);
|
||||
near(g_map.off_y, top);
|
||||
double sx, sy;
|
||||
assert(vkp_output_to_scene(g_map.off_x + sw * g_map.kx / 2,
|
||||
top + sh * g_map.ky / 2, &sx, &sy));
|
||||
near(sx, sw / 2.0); near(sy, sh / 2.0);
|
||||
near(g_map.kx, g_map.ky);
|
||||
assert(sh * g_map.ky <= oh + 0.01);
|
||||
g_align = VKP_ALIGN_CENTER; update_map(sw, sh);
|
||||
assert(!vkp_game_picture_rect(rect));
|
||||
near(g_map.off_y, (int)((oh - sh * g_map.ky) * 0.5));
|
||||
}
|
||||
int main(void) {
|
||||
for (int alignment = VKP_ALIGN_PICTURE_TOP; alignment <= VKP_ALIGN_PICTURE_BOTTOM; alignment++) {
|
||||
check(1240, 1100, 2480, 2200, alignment);
|
||||
check(1280, 720, 2480, 2200, alignment);
|
||||
check(1024, 768, 2480, 2200, alignment);
|
||||
check(1920, 1080, 2400, 1080, alignment);
|
||||
check(1240, 1100, 2480, 1394, alignment);
|
||||
}
|
||||
g_align = VKP_ALIGN_TOP; update_map(1280, 720);
|
||||
assert(g_map.rh == 697 && g_map.ry == 0);
|
||||
puts("PASS");
|
||||
}
|
||||
'''
|
||||
(tmp / 'map.c').write_text(code)
|
||||
subprocess.run([cc, '-std=c11', str(tmp / 'map.c'), '-lm', '-o', str(tmp / 'map')], check=True, capture_output=True, text=True)
|
||||
result = subprocess.run([str(tmp / 'map')], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Exercise the compositor's real button dispatcher with a recording Wayland sink."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class PointerReleaseTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = shutil.which(os.environ.get('CC', 'cc'))
|
||||
if compiler is None:
|
||||
raise unittest.SkipTest('A host C compiler is required')
|
||||
source = (REPO / 'app/src/main/cpp/waylandcomp/src/compositor.c').read_text()
|
||||
start = source.index('static void pointer_button(uint32_t button, int pressed) {')
|
||||
end = source.index('\n}\n', start) + 3
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-pointer-release-')
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
folder = Path(cls.temp.name)
|
||||
(folder / 'pointer_button.inc').write_text(source[start:end])
|
||||
start = source.index('static void touch_cancel_all(void) {')
|
||||
end = source.index('\n}\n', start) + 3
|
||||
(folder / 'touch_cancel_all.inc').write_text(source[start:end])
|
||||
cls.binary = folder / 'pointer-test'
|
||||
subprocess.run([compiler, '-std=c11', '-Wall', '-I', str(folder),
|
||||
str(REPO / 'tools/tests/pointer_release_harness.c'),
|
||||
'-o', str(cls.binary)], check=True, capture_output=True, text=True)
|
||||
|
||||
def check_case(self, case):
|
||||
result = subprocess.run([str(self.binary), case], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
def test_cleanup_releases_all_buttons_without_motion(self):
|
||||
self.check_case('cleanup')
|
||||
|
||||
def test_release_without_focus_does_not_select_a_window(self):
|
||||
self.check_case('unfocused')
|
||||
|
||||
def test_release_reaches_each_focused_pointer_and_clears_grab(self):
|
||||
self.check_case('focused')
|
||||
|
||||
def test_touch_fallback_cancel_releases_without_motion(self):
|
||||
self.check_case('fallback')
|
||||
|
||||
def test_native_touch_cancel_then_cleanup_releases_stale_buttons(self):
|
||||
self.check_case('native')
|
||||
|
||||
def test_press_keeps_existing_routing(self):
|
||||
self.check_case('press')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,133 @@
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
PROOT = Path(__file__).resolve().parents[1] / "proot"
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include "statx_mnt_id.h"
|
||||
|
||||
static int fdinfo_mnt_id(int fd, uint64_t *out) {
|
||||
char path[64], line[256];
|
||||
snprintf(path, sizeof path, "/proc/self/fdinfo/%d", fd);
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) return 0;
|
||||
int found = 0;
|
||||
while (fgets(line, sizeof line, f)) {
|
||||
unsigned long long id;
|
||||
if (sscanf(line, "mnt_id:%llu", &id) == 1) {
|
||||
*out = (uint64_t)id;
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
return found;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
char name[] = "/tmp/droiddeck-statx-mnt-id-XXXXXX";
|
||||
int fd = mkstemp(name);
|
||||
if (fd < 0) return 1;
|
||||
|
||||
struct stat st;
|
||||
if (fstat(fd, &st) < 0) return 2;
|
||||
uint64_t expected;
|
||||
if (!fdinfo_mnt_id(fd, &expected) || expected == 0) return 3;
|
||||
|
||||
/* Model a successful pre-5.8 statx: inode fields are present, MNT_ID is absent. */
|
||||
struct statx result = {0};
|
||||
result.stx_mask = STATX_TYPE | STATX_INO;
|
||||
result.stx_mode = st.st_mode;
|
||||
result.stx_ino = st.st_ino;
|
||||
result.stx_dev_major = major(st.st_dev);
|
||||
result.stx_dev_minor = minor(st.st_dev);
|
||||
unsigned flags = AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW;
|
||||
unsigned mask = STATX_TYPE | STATX_INO | STATX_MNT_ID;
|
||||
if (!droiddeck_proot_statx_fill_mnt_id(getpid(), fd, flags, "", mask, &result)) return 4;
|
||||
if (!(result.stx_mask & STATX_MNT_ID) || result.stx_mnt_id != expected) return 5;
|
||||
|
||||
/* A reused fd can name the same inode number on another device. Inode alone is not identity. */
|
||||
result.stx_mask = STATX_TYPE | STATX_INO;
|
||||
result.stx_dev_major = major(st.st_dev) ^ 1U;
|
||||
result.stx_dev_minor = minor(st.st_dev);
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), fd, flags, "", mask, &result)) return 6;
|
||||
if (result.stx_mask & STATX_MNT_ID) return 7;
|
||||
|
||||
/* Only ordinary MNT_ID is reconstructed; never claim the newer UNIQUE bit. */
|
||||
result.stx_ino = st.st_ino;
|
||||
result.stx_dev_major = major(st.st_dev);
|
||||
result.stx_dev_minor = minor(st.st_dev);
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), fd, flags, "", 0x4000U, &result)) return 8;
|
||||
if (result.stx_mask & STATX_MNT_ID) return 9;
|
||||
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), AT_FDCWD, flags, "", mask, &result)) return 10;
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), -1, flags, "", mask, &result)) return 11;
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), fd, AT_SYMLINK_NOFOLLOW, "", mask, &result)) return 12;
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), fd, flags, "file", mask, &result)) return 13;
|
||||
int stale = dup(fd);
|
||||
if (stale < 0 || close(stale) < 0) return 14;
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), stale, flags, "", mask, &result)) return 15;
|
||||
|
||||
/* Pin the original referent, then reuse its tracee fd number. The pin's fdinfo stays stable,
|
||||
* while recovery against the reused number must reject the different inode/device. */
|
||||
char replacement_name[] = "/tmp/droiddeck-statx-mnt-id-replacement-XXXXXX";
|
||||
int replacement = mkstemp(replacement_name);
|
||||
if (replacement < 0) return 16;
|
||||
int pinned;
|
||||
char path[64];
|
||||
snprintf(path, sizeof path, "/proc/%ld/fd/%d", (long)getpid(), fd);
|
||||
pinned = open(path, O_PATH | O_CLOEXEC);
|
||||
if (pinned < 0) return 17;
|
||||
uint64_t pinned_mnt_id, pinned_ino;
|
||||
if (!droiddeck_proot_read_fdinfo(pinned, &pinned_mnt_id, &pinned_ino) ||
|
||||
pinned_mnt_id != expected || pinned_ino != st.st_ino) return 18;
|
||||
|
||||
struct stat replacement_st;
|
||||
if (fstat(replacement, &replacement_st) < 0) return 19;
|
||||
if (replacement_st.st_dev == st.st_dev && replacement_st.st_ino == st.st_ino) return 20;
|
||||
unlink(name);
|
||||
if (close(fd) < 0 || dup2(replacement, fd) != fd) return 21;
|
||||
close(replacement);
|
||||
unlink(replacement_name);
|
||||
|
||||
result.stx_mask = STATX_TYPE | STATX_INO;
|
||||
result.stx_ino = st.st_ino;
|
||||
result.stx_dev_major = major(st.st_dev);
|
||||
result.stx_dev_minor = minor(st.st_dev);
|
||||
if (droiddeck_proot_statx_fill_mnt_id(getpid(), fd, flags, "", mask, &result)) return 22;
|
||||
if (result.stx_mask & STATX_MNT_ID) return 23;
|
||||
if (!droiddeck_proot_read_fdinfo(pinned, &pinned_mnt_id, &pinned_ino) ||
|
||||
pinned_mnt_id != expected || pinned_ino != st.st_ino) return 24;
|
||||
|
||||
close(pinned);
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc") and sys.platform.startswith("linux"), "requires Linux and a C compiler")
|
||||
class ProotStatxMountIdTest(unittest.TestCase):
|
||||
def test_missing_mount_id_is_recovered_only_for_the_same_open_inode(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
source = Path(tmp) / "test.c"
|
||||
program = Path(tmp) / "test"
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-I", str(PROOT), "-o", str(program), str(source)], check=True)
|
||||
subprocess.run([str(program)], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -29,7 +29,7 @@ class ProtonExtraTest(unittest.TestCase):
|
||||
def test_sources_and_their_arm64_assets(self):
|
||||
self.assertEqual(list(EXTRA["SOURCES"]), ["ge", "cachyos", "droiddeck"])
|
||||
repo, pattern = EXTRA["SOURCES"]["droiddeck"]
|
||||
self.assertEqual(repo, "The412Banner/DroidDeck-Proton")
|
||||
self.assertEqual(repo, "Droid-Deck/DroidDeck-Proton")
|
||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-7.5-aarch64.tar.gz"))
|
||||
self.assertTrue(pattern.search("DroidDeck-Proton-11-8-aarch64.tar.xz"))
|
||||
self.assertFalse(pattern.search("DroidDeck-Proton-11-7.5-aarch64.sha512sum"))
|
||||
@@ -49,7 +49,7 @@ class ProtonExtraTest(unittest.TestCase):
|
||||
asked = []
|
||||
with mock.patch.dict(GLOBALS, {"fetch_json": lambda url: asked.append(url) or droiddeck_release("11-7.5")}):
|
||||
tag, url, sums = EXTRA["release_asset"]("droiddeck", "DroidDeck-Proton-11-7.5")
|
||||
self.assertEqual(asked, ["https://api.github.com/repos/The412Banner/DroidDeck-Proton/releases/tags/DroidDeck-Proton-11-7.5"])
|
||||
self.assertEqual(asked, ["https://api.github.com/repos/Droid-Deck/DroidDeck-Proton/releases/tags/DroidDeck-Proton-11-7.5"])
|
||||
self.assertTrue(url.endswith(".tar.gz") and sums.endswith(".sha512sum"))
|
||||
|
||||
def test_a_ge_style_sha512_file_verifies_the_download(self):
|
||||
@@ -89,7 +89,6 @@ class ProtonExtraTest(unittest.TestCase):
|
||||
steam = Path(tmp) / "Steam"
|
||||
adopted = []
|
||||
real = subprocess.call
|
||||
# tar runs for real; steam-compatibility (the adoption step) is only recorded.
|
||||
fake = lambda args, **kw: adopted.append(args) or 0 if args[0] == "steam-compatibility" else real(args, **kw)
|
||||
with mock.patch.object(GLOBALS["subprocess"], "call", fake), contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
with mock.patch.object(GLOBALS["sys"], "argv", ["droiddeck-proton-extra", str(steam), str(tarball)]):
|
||||
@@ -98,7 +97,6 @@ class ProtonExtraTest(unittest.TestCase):
|
||||
self.assertEqual(sorted(os.listdir(tools)), [".droiddeck-download", "DroidDeck-Proton 11-7.5"])
|
||||
self.assertTrue((tools / "DroidDeck-Proton 11-7.5" / "toolmanifest.vdf").is_file())
|
||||
self.assertEqual(adopted, [["steam-compatibility", str(steam)]])
|
||||
# The app reads the folder from this line, space and all.
|
||||
self.assertIn("droiddeck-proton-extra: installed DroidDeck-Proton 11-7.5\n", said.getvalue())
|
||||
self.assertEqual(EXTRA["installed"](str(tools)), ["DroidDeck-Proton 11-7.5"])
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which('cc'), 'needs a C compiler')
|
||||
class QuestBackdropTest(unittest.TestCase):
|
||||
def test_first_frame_requires_client_content(self):
|
||||
# Compile the real entrypoint with controlled layer outcomes, including the
|
||||
# successful no-op that previously dismissed the loading UI on a black frame.
|
||||
source = (ROOT / 'app/src/main/cpp/waylandcomp/src/vk_present.c').read_text()
|
||||
start = source.index('\nint vkp_render(')
|
||||
end = source.index('\nint vkp_render_hdr(', start)
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
work = Path(folder)
|
||||
(work / 'vkp_render_under_test.inc').write_text(source[start:end])
|
||||
binary = work / 'test-first-frame'
|
||||
subprocess.run(['cc', '-std=c11', '-Wall', '-Wextra',
|
||||
'-Wno-unused-parameter', '-Wno-unused-function', f'-I{work}',
|
||||
str(ROOT / 'tools/quest/test_first_frame.c'), '-o', str(binary)],
|
||||
check=True, capture_output=True, text=True)
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn('PASS: Quest first-frame', result.stdout)
|
||||
|
||||
def test_backdrop_lifecycle_and_failed_buffer_initialization(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
work = Path(folder)
|
||||
android = work / 'android'
|
||||
android.mkdir()
|
||||
(android / 'rect.h').write_text('''#pragma once
|
||||
#include <stdint.h>
|
||||
typedef struct ARect { int32_t left, top, right, bottom; } ARect;
|
||||
''')
|
||||
(android / 'native_window.h').write_text('''#pragma once
|
||||
typedef struct ANativeWindow ANativeWindow;
|
||||
''')
|
||||
(android / 'hardware_buffer.h').write_text('''#pragma once
|
||||
#include <stdint.h>
|
||||
#include "rect.h"
|
||||
typedef struct AHardwareBuffer AHardwareBuffer;
|
||||
typedef struct { uint32_t width,height,layers,format; uint64_t usage;
|
||||
uint32_t stride,rfu0; uint64_t rfu1; } AHardwareBuffer_Desc;
|
||||
#define AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM 1
|
||||
#define AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM 0x2b
|
||||
#define AHARDWAREBUFFER_USAGE_CPU_READ_RARELY 2ULL
|
||||
#define AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY 32ULL
|
||||
#define AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE 256ULL
|
||||
#define AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT 512ULL
|
||||
#define AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY 2048ULL
|
||||
int AHardwareBuffer_allocate(const AHardwareBuffer_Desc *, AHardwareBuffer **);
|
||||
void AHardwareBuffer_describe(const AHardwareBuffer *, AHardwareBuffer_Desc *);
|
||||
int AHardwareBuffer_lock(AHardwareBuffer *, uint64_t, int32_t, const ARect *, void **);
|
||||
int AHardwareBuffer_unlock(AHardwareBuffer *, int32_t *);
|
||||
void AHardwareBuffer_release(AHardwareBuffer *);
|
||||
''')
|
||||
binary = work / 'test-presentation'
|
||||
subprocess.run(['cc', '-std=c11', '-O1', '-g', '-Wall', '-Wextra',
|
||||
'-Wno-unused-parameter', '-Wno-unused-function',
|
||||
'-ffunction-sections', '-fdata-sections', '-Wl,--gc-sections',
|
||||
'-fsanitize=address,undefined', f'-I{work}',
|
||||
f'-I{ROOT}/app/src/main/cpp/waylandcomp/prebuilt/include',
|
||||
str(ROOT / 'tools/quest/test_presentation.c'), '-ldl', '-pthread',
|
||||
'-o', str(binary)], check=True, capture_output=True, text=True)
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn('PASS: Quest backdrop', result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -22,8 +22,6 @@ GAME_SCRIPT = r'''"InstallScript"
|
||||
}
|
||||
'''
|
||||
|
||||
# Red Dead Redemption 2's own script: Proton needs Khronos' vulkan-1.dll for it, which only the
|
||||
# Vulkan runtime installer puts in the prefix.
|
||||
VULKAN_SCRIPT = r'''"InstallScript"
|
||||
{
|
||||
"Run Process"
|
||||
@@ -102,6 +100,53 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.run_seed()
|
||||
self.assertIn('"VCRedist2022"=dword:00000001', self.reg.read_text())
|
||||
|
||||
def test_markers_a_replaced_registry_lost_are_seeded_again(self):
|
||||
self.game()
|
||||
stock = self.reg.read_text()
|
||||
self.run_seed()
|
||||
ledger = (self.reg.parent / ".droiddeck-redists").read_text()
|
||||
self.assertIn("VCRedist2022", ledger)
|
||||
self.reg.write_text(stock)
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
self.assertEqual(reg.count('"VCRedist2022"=dword:00000001'), 2, "both views again")
|
||||
self.assertIn("[Software\\\\Microsoft\\\\VisualStudio\\\\14.0\\\\VC\\\\Runtimes\\\\x86]", reg)
|
||||
self.assertEqual(sorted((self.reg.parent / ".droiddeck-redists").read_text().splitlines()), sorted(ledger.splitlines()))
|
||||
self.run_seed()
|
||||
self.assertEqual(reg, self.reg.read_text())
|
||||
|
||||
def test_a_marker_kept_in_only_one_view_is_seeded_again(self):
|
||||
self.game()
|
||||
self.run_seed()
|
||||
wow = "[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022]"
|
||||
blocks = self.reg.read_text().split("\n\n")
|
||||
self.reg.write_text("\n\n".join(b for b in blocks if not (b.startswith(wow) and '"VCRedist2022"' in b)))
|
||||
self.assertEqual(self.reg.read_text().count('"VCRedist2022"'), 1)
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
self.assertEqual(reg.count('"VCRedist2022"'), 3, "the one left plus both views again")
|
||||
self.assertTrue(any(b.startswith(wow) and '"VCRedist2022"' in b for b in reg.split("\n\n")))
|
||||
|
||||
def test_a_vc_runtime_another_architecture_lost_is_seeded_again(self):
|
||||
self.run_seed()
|
||||
arm64 = "[Software\\\\Wow6432Node\\\\Microsoft\\\\VisualStudio\\\\14.0\\\\VC\\\\Runtimes\\\\arm64]"
|
||||
blocks = self.reg.read_text().split("\n\n")
|
||||
self.reg.write_text("\n\n".join(b for b in blocks if not b.startswith(arm64)))
|
||||
self.assertNotIn(arm64, self.reg.read_text())
|
||||
self.run_seed()
|
||||
reg = self.reg.read_text()
|
||||
self.assertIn(arm64, reg)
|
||||
self.assertEqual(reg.count("[Software\\\\Microsoft\\\\VisualStudio\\\\14.0\\\\VC\\\\Runtimes\\\\x86]"), 2)
|
||||
|
||||
def test_a_marker_written_in_one_view_only_is_kept_as_it_is(self):
|
||||
self.game(script=GAME_SCRIPT.replace("Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2022", "SOFTWARE\\\\AGEIA Technologies").replace("VCRedist2022", "PhysX Version"))
|
||||
self.run_seed()
|
||||
once = self.reg.read_text()
|
||||
self.assertEqual(once.count('"PhysX Version"=dword:00000001'), 1)
|
||||
result = self.run_seed()
|
||||
self.assertEqual(once, self.reg.read_text())
|
||||
self.assertNotIn("gone", result.stdout)
|
||||
|
||||
def test_an_evaluator_script_nested_deeper_is_read(self):
|
||||
script = self.tmp / "legacycompat/evaluatorscript_409710.vdf"
|
||||
script.parent.mkdir(parents=True)
|
||||
@@ -148,7 +193,6 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.assertIn('"Other"=dword:00000001', reg)
|
||||
self.assertNotIn("Vulkan111080", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
self.assertEqual(int(self.reg.stat().st_mtime), 1_000_000_000)
|
||||
# The client writes the marker itself once the installer has run; that one is left alone.
|
||||
with self.reg.open("a") as out:
|
||||
out.write('\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1174180] 1791730000\n"Vulkan111080"=dword:00000001\n')
|
||||
self.run_seed()
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""The XTest cursor path is enabled only for Steam sessions."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
SOURCE = SESSION.read_text()
|
||||
MATCH = re.search(
|
||||
r'^ if \[ "\$mode" = steam \]; then\n.*?^ fi\n', SOURCE, re.M | re.S)
|
||||
assert MATCH is not None
|
||||
CURSOR_SETUP = MATCH.group(0)
|
||||
|
||||
|
||||
class SessionCursorRoutingTest(unittest.TestCase):
|
||||
def run_setup(self, mode, initial=None):
|
||||
env = dict(os.environ, mode=mode)
|
||||
if initial is not None:
|
||||
env['gamescope_cursor_composite'] = initial
|
||||
else:
|
||||
env.pop('gamescope_cursor_composite', None)
|
||||
result = subprocess.run(
|
||||
['bash', '-c', CURSOR_SETUP + 'printf "%s\n" "${gamescope_cursor_composite-}"'],
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
return result.stdout.strip()
|
||||
|
||||
def test_steam_enables_manual_composition_for_the_nested_cursor(self):
|
||||
self.assertEqual('2', self.run_setup('steam'))
|
||||
|
||||
def test_other_sessions_keep_their_existing_cursor_composition(self):
|
||||
self.assertEqual('', self.run_setup('desktop'))
|
||||
self.assertEqual('1', self.run_setup('run', '1'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -53,8 +53,6 @@ class SessionGuestCommandTest(unittest.TestCase):
|
||||
def test_child_receives_its_package_socket_after_environment_is_cleared(self):
|
||||
for package in PACKAGES:
|
||||
with self.subTest(package=package):
|
||||
# env with no command prints the environment it would pass to the
|
||||
# session. A misplaced assignment fails at exec, before it runs.
|
||||
result = subprocess.run(
|
||||
guest_prefix(package), capture_output=True, text=True, check=True,
|
||||
timeout=5, env={"DROIDDECK_BWRAP_SOCKET": "wrong.bwrap", "STALE_HOST": "1"})
|
||||
|
||||
@@ -12,7 +12,7 @@ SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/d
|
||||
STEAM = ["mangohud.Ab3dE6gH", ".com.valvesoftware.Steam.x1Y2z3/", "steam_chrome_shmem_uid10480_0", "steamADfAnd/"]
|
||||
CHROMIUM = ["scoped_dir3yu9Xt/SingletonSocket"]
|
||||
APPIMAGE = ["droiddeck-appimage.19PoOD"]
|
||||
BUS = ["dbus-1zWfOP1IaR="] # = a socket
|
||||
BUS = ["dbus-1zWfOP1IaR="]
|
||||
KDE = ["plasma-csd-generator.BVWIWA/"]
|
||||
STALE = STEAM + CHROMIUM + APPIMAGE + BUS + KDE
|
||||
KEPT = ["droiddeck-mangohud.conf", ".X11-unix/", "steamworks", "steamABCDEF/inside", "notes.txt",
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Cold shortcut launches wait for Steam's CGameID-to-app overview mapping."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
SOURCE = SESSION.read_text()
|
||||
END = SOURCE.index(
|
||||
' if [ -s "$HOME/.bl-autolaunch" ]; then',
|
||||
SOURCE.index(" _bl_launch_ready="),
|
||||
)
|
||||
START = SOURCE.rfind(
|
||||
' if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ]; then',
|
||||
0,
|
||||
END,
|
||||
)
|
||||
assert START >= 0
|
||||
LAUNCH_BLOCK = textwrap.dedent(SOURCE[START:END])
|
||||
|
||||
|
||||
class SteamColdLaunchTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.launch_dir = self.root / "session"
|
||||
self.launch_dir.mkdir()
|
||||
self.bin = self.root / "bin"
|
||||
self.bin.mkdir()
|
||||
self.agent_args = self.root / "agent-args"
|
||||
self.sleep_args = self.root / "sleep-args"
|
||||
|
||||
xprop = self.bin / "xprop"
|
||||
xprop.write_text("#!/bin/sh\necho 'GAMESCOPE_FOCUSED_APP(CARDINAL) = 769'\n")
|
||||
xprop.chmod(0o755)
|
||||
agent = self.bin / "droiddeck-agent"
|
||||
agent.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$AGENT_ARGS\"\nexit \"$AGENT_STATUS\"\n")
|
||||
agent.chmod(0o755)
|
||||
sleep = self.bin / "sleep"
|
||||
sleep.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$SLEEP_ARGS\"\n")
|
||||
sleep.chmod(0o755)
|
||||
self.block = LAUNCH_BLOCK.replace("/usr/local/bin/droiddeck-agent", str(agent))
|
||||
|
||||
def run_launch(self, target, helper_status):
|
||||
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch_dir),
|
||||
PATH=str(self.bin) + os.pathsep + os.environ["PATH"],
|
||||
AGENT_ARGS=str(self.agent_args), SLEEP_ARGS=str(self.sleep_args),
|
||||
AGENT_STATUS=str(helper_status))
|
||||
script = self.block + "\nprintf 'ARG:%s\\n' \"$@\"\nwait\n"
|
||||
url = target if target.startswith("steam://") else "steam://rungameid/" + target
|
||||
result = subprocess.run(["bash", "-c", script, "cold-launch", url],
|
||||
env=env, text=True, capture_output=True, timeout=10)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return result
|
||||
|
||||
def test_shortcut_overview_gate_releases_original_64_bit_cgameid_without_fixed_sleep(self):
|
||||
game_id = str((3551182975 << 32) | 0x02000000)
|
||||
result = self.run_launch(game_id, 0)
|
||||
self.assertEqual("steam-game", (self.launch_dir / "steam-game").name)
|
||||
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip())
|
||||
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
|
||||
self.assertFalse(self.sleep_args.exists(), result.stdout)
|
||||
|
||||
def test_native_app_id_keeps_legacy_bounded_launch_path(self):
|
||||
game_id = "413150"
|
||||
self.run_launch(game_id, 3)
|
||||
self.assertEqual(game_id, (self.launch_dir / "steam-game").read_text().strip())
|
||||
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
|
||||
self.assertEqual("4", self.sleep_args.read_text().strip())
|
||||
|
||||
def test_shortcut_without_the_expected_overview_does_not_forward_cgameid(self):
|
||||
game_id = str((3551182975 << 32) | 0x02000000)
|
||||
result = self.run_launch(game_id, 1)
|
||||
self.assertFalse((self.launch_dir / "steam-game").exists(), result.stdout)
|
||||
self.assertEqual(["--wait-steam-shortcut-overview", game_id, "45"], self.agent_args.read_text().splitlines())
|
||||
self.assertFalse(self.sleep_args.exists())
|
||||
|
||||
def test_non_game_steam_urls_remain_on_the_original_startup_arguments(self):
|
||||
url = "steam://open/library"
|
||||
result = self.run_launch(url, 0)
|
||||
self.assertIn("ARG:" + url, result.stdout)
|
||||
self.assertFalse((self.launch_dir / "steam-game").exists())
|
||||
self.assertFalse(self.agent_args.exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -221,6 +221,187 @@ class ReconcileTest(unittest.TestCase):
|
||||
self.assertEqual(page.sets, [("10", TOOL_11), ("11", TOOL)])
|
||||
self.assertEqual(state["auto"], {"11": TOOL})
|
||||
|
||||
def test_native_arm64_title_drops_auto_proton_once_and_keeps_explicit_choices(self):
|
||||
(self.steam / "steamapps/appmanifest_11.acf").unlink()
|
||||
(self.state / "state.json").write_text(json.dumps({
|
||||
"default": TOOL,
|
||||
"auto": {"10": TOOL},
|
||||
}))
|
||||
page = FakePage({"0": TOOL, "10": TOOL}, [TOOL, TOOL_11])
|
||||
original_native_targets = COMPAT["native_targets"]
|
||||
COMPAT["native_targets"] = lambda _root, _apps: {"10": None}
|
||||
try:
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("10", "")])
|
||||
self.assertEqual(page.mapping["10"], "")
|
||||
self.assertEqual(state["auto"], {})
|
||||
|
||||
page.sets.clear()
|
||||
self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
|
||||
(self.state / "games.json").write_text(json.dumps({
|
||||
"version": 1,
|
||||
"games": {"10": {"valve": True, "dir": "Proton 11.0 (ARM64)"}},
|
||||
}))
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [("10", TOOL_11)])
|
||||
self.assertEqual(page.mapping["10"], TOOL_11)
|
||||
self.assertEqual(state["auto"], {})
|
||||
(self.state / "games.json").unlink()
|
||||
|
||||
page.sets.clear()
|
||||
page.mapping["10"] = "steamlinuxruntime_arm64"
|
||||
self.reconcile(page)
|
||||
self.assertEqual(page.mapping["10"], "steamlinuxruntime_arm64")
|
||||
self.assertEqual(page.sets, [])
|
||||
|
||||
page.mapping["10"] = TOOL_11
|
||||
self.reconcile(page)
|
||||
self.assertEqual(page.mapping["10"], TOOL_11)
|
||||
self.assertEqual(page.sets, [])
|
||||
|
||||
page.mapping["10"] = COMPAT["FEX_TOOL"]
|
||||
self.reconcile(page)
|
||||
self.assertEqual(page.mapping["10"], COMPAT["FEX_TOOL"])
|
||||
self.assertEqual(page.sets, [])
|
||||
|
||||
page.mapping["10"] = "GE-Proton11-7"
|
||||
self.reconcile(page)
|
||||
self.assertEqual(page.mapping["10"], "GE-Proton11-7")
|
||||
self.assertEqual(page.sets, [])
|
||||
finally:
|
||||
COMPAT["native_targets"] = original_native_targets
|
||||
|
||||
def test_factorio_native_choice_survives_inherited_live_selection_and_restart(self):
|
||||
app = "427520"
|
||||
(self.steam / ("steamapps/appmanifest_%s.acf" % app)).write_text("")
|
||||
config = self.steam / "config/config.vdf"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL)
|
||||
(self.state / "state.json").write_text(json.dumps({
|
||||
"default": TOOL,
|
||||
"auto": {app: TOOL},
|
||||
}))
|
||||
|
||||
original_native_targets = COMPAT["native_targets"]
|
||||
COMPAT["native_targets"] = lambda _root, apps: {
|
||||
app: COMPAT["NATIVE_CHOICE"]
|
||||
} if app in apps else {}
|
||||
try:
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL, app: "proton"}, [TOOL, TOOL_11])
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["auto"], {})
|
||||
self.assertEqual(state["native"], [app])
|
||||
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {"0": TOOL})
|
||||
|
||||
page.sets.clear()
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native"], [app])
|
||||
restarted = LIVE["Helper"](str(self.steam), 1)
|
||||
restarted.page = page
|
||||
restarted.reconcile()
|
||||
state = json.loads((self.state / "state.json").read_text())
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native"], [app])
|
||||
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } '
|
||||
'"%s" { "name" "GE-Proton11-7" } } } } } }' % (TOOL, app))
|
||||
page.mapping[app] = "GE-Proton11-7"
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.mapping[app], "GE-Proton11-7")
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native"], [])
|
||||
|
||||
for choice in ("steamlinuxruntime", COMPAT["FEX_TOOL"], TOOL_11):
|
||||
(self.state / "state.json").write_text(json.dumps({
|
||||
"default": TOOL,
|
||||
"auto": {},
|
||||
"native": [app],
|
||||
}))
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } '
|
||||
'"%s" { "name" "%s" } } } } } }' % (TOOL, app, choice))
|
||||
page.mapping[app] = choice
|
||||
page.sets.clear()
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.mapping[app], choice)
|
||||
self.assertEqual(page.sets, [])
|
||||
self.assertEqual(state["native"], [], choice)
|
||||
finally:
|
||||
COMPAT["native_targets"] = original_native_targets
|
||||
|
||||
def test_saved_native_choice_survives_live_restart_without_manifest_or_appinfo(self):
|
||||
app = "452280"
|
||||
config = self.steam / "config/config.vdf"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL)
|
||||
(self.state / "state.json").write_text(json.dumps({
|
||||
"default": TOOL,
|
||||
"auto": {},
|
||||
"native": [app],
|
||||
}))
|
||||
|
||||
original_native_targets = COMPAT["native_targets"]
|
||||
COMPAT["native_targets"] = lambda _root, _apps: {}
|
||||
try:
|
||||
page = FakePage({"0": TOOL, app: "proton"}, [TOOL, TOOL_11])
|
||||
state = self.reconcile(page)
|
||||
self.assertNotIn(app, self.helper.installed)
|
||||
self.assertEqual(state["native"], [app])
|
||||
self.assertNotIn(app, state["auto"])
|
||||
self.assertNotIn((app, TOOL), page.sets)
|
||||
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {"0": TOOL})
|
||||
|
||||
config.write_text('"InstallConfigStore" { "Software" { "Other" {} } }')
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(state["native"], [app])
|
||||
self.assertNotIn((app, TOOL), page.sets)
|
||||
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } '
|
||||
'"%s" { "name" "GE-Proton11-7" } } } } } }' % (TOOL, app))
|
||||
page.mapping[app] = "proton"
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(state["native"], [])
|
||||
self.assertNotIn((app, TOOL), page.sets)
|
||||
self.assertEqual(COMPAT["read_config_mapping"](str(config))[app], "GE-Proton11-7")
|
||||
finally:
|
||||
COMPAT["native_targets"] = original_native_targets
|
||||
|
||||
def test_factorio_without_prior_auto_state_uses_the_default_proton(self):
|
||||
app = "427520"
|
||||
(self.steam / ("steamapps/appmanifest_%s.acf" % app)).write_text("")
|
||||
config = self.steam / "config/config.vdf"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL)
|
||||
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {}}))
|
||||
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL, app: "proton"}, [TOOL, TOOL_11])
|
||||
original_native_targets = COMPAT["native_targets"]
|
||||
COMPAT["native_targets"] = lambda _root, apps: {
|
||||
app: COMPAT["NATIVE_CHOICE"]
|
||||
} if app in apps else {}
|
||||
try:
|
||||
state = self.reconcile(page)
|
||||
self.assertEqual(page.sets, [(app, TOOL)])
|
||||
self.assertEqual(state["auto"], {app: TOOL})
|
||||
self.assertEqual(state["native"], [])
|
||||
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {"0": TOOL})
|
||||
finally:
|
||||
COMPAT["native_targets"] = original_native_targets
|
||||
|
||||
def test_missing_per_game_proton_stays_deferred_live(self):
|
||||
page = FakePage({"0": TOOL, "10": "GE-Proton9-1", "11": TOOL_11}, [TOOL, TOOL_11])
|
||||
(self.state / "games.json").write_text(json.dumps({
|
||||
|
||||
@@ -107,7 +107,7 @@ class DesktopSteamLaunchTest(unittest.TestCase):
|
||||
|
||||
def test_cef_software_is_scoped_to_the_kde_client(self):
|
||||
source = (BIN / 'droiddeck-session').read_text()
|
||||
setup = source[source.index(' _bl_ui=(-gamepadui)'):source.index(' # Deck mode, always')]
|
||||
setup = source[source.index(' _bl_ui=(-gamepadui)'):source.index(' if [ "${BL_STEAM_UI:-}" != desktop ]; then')]
|
||||
for desktop, ui, software in [('1', 'desktop', True), ('1', 'bigpicture', False), ('', 'desktop', False)]:
|
||||
with self.subTest(desktop=desktop, ui=ui):
|
||||
env = dict(self.env, BL_DESKTOP=desktop, BL_STEAM_UI=ui)
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
|
||||
|
||||
class SteamExitStatusTest(unittest.TestCase):
|
||||
def run_session(self, child_status, compositor_status=0, report=True, report_value=None,
|
||||
stale_status=None):
|
||||
source = SESSION.read_text()
|
||||
function = re.search(r'^run_gamescope\(\) \(\n.*?^\)\n', source, re.M | re.S)
|
||||
self.assertIsNotNone(function)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
stale_file = root / 'droiddeck-steam-exit.stale'
|
||||
if stale_status is not None:
|
||||
stale_file.write_text(str(stale_status) + '\n')
|
||||
compositor = root / 'gamescope'
|
||||
compositor.write_text('#!/bin/bash\n"$@"\nexit ' + str(compositor_status) + '\n')
|
||||
compositor.chmod(0o755)
|
||||
child = root / 'steam'
|
||||
report_arg = '"$1"' if report_value is None else '"$2"'
|
||||
report_line = ('printf "%s\\n" ' + report_arg + ' > "$BL_STEAM_EXIT_FILE"\n'
|
||||
if report else '')
|
||||
child.write_text('#!/bin/bash\n' + report_line + 'exit "$1"\n')
|
||||
child.chmod(0o755)
|
||||
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
|
||||
XDG_RUNTIME_DIR=str(root))
|
||||
result = subprocess.run(['bash', '-c', function.group() + '\nrun_gamescope "$@"',
|
||||
'session', str(child), str(child_status),
|
||||
str(report_value) if report_value is not None else ''], env=env,
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(list(root.glob('droiddeck-steam-exit.??????')), [])
|
||||
if stale_status is not None:
|
||||
self.assertEqual(stale_file.read_text(), str(stale_status) + '\n')
|
||||
return result.returncode
|
||||
|
||||
def test_steam_crash_survives_successful_compositor_shutdown(self):
|
||||
self.assertEqual(self.run_session(139), 139)
|
||||
|
||||
def test_clean_steam_shutdown_remains_success(self):
|
||||
self.assertEqual(self.run_session(0), 0)
|
||||
|
||||
def test_compositor_failure_remains_visible(self):
|
||||
self.assertEqual(self.run_session(0, compositor_status=1), 1)
|
||||
|
||||
def test_early_child_failure_preserves_compositor_result(self):
|
||||
self.assertEqual(self.run_session(127, compositor_status=127, report=False), 127)
|
||||
|
||||
def test_no_report_does_not_invent_a_failure(self):
|
||||
self.assertEqual(self.run_session(0, report=False), 0)
|
||||
|
||||
def test_invalid_report_cannot_become_a_shell_exit_status(self):
|
||||
self.assertEqual(self.run_session(999), 0)
|
||||
|
||||
def test_malformed_report_is_ignored(self):
|
||||
self.assertEqual(self.run_session(0, report_value='not-an-exit-code'), 0)
|
||||
|
||||
def test_stale_marker_does_not_affect_a_new_launch(self):
|
||||
self.assertEqual(self.run_session(0, report=False, stale_status=139), 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -55,6 +55,35 @@ class ImportsTest(unittest.TestCase):
|
||||
self.assertEqual(self.folder, (self.steam / 'steamapps/common/DroidDeck-42').resolve())
|
||||
self.assertEqual(b'game', self.exe.read_bytes())
|
||||
|
||||
def test_store_installs_stay_shortcuts_even_when_owned_on_steam(self):
|
||||
self.snapshot()
|
||||
game = dict(self.game, store='amazon')
|
||||
games, routes = imports.route(self.steam, self.acct, [game])
|
||||
self.assertEqual([game], games)
|
||||
self.assertEqual({}, routes)
|
||||
self.assertFalse((self.steam / 'steamapps/appmanifest_42.acf').exists())
|
||||
self.assertFalse(os.path.lexists(self.steam / 'steamapps/common/DroidDeck-42'))
|
||||
|
||||
def test_store_installs_imported_earlier_are_released(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
unrelated = self.steam / 'steamapps/appmanifest_7.acf'
|
||||
unrelated.write_text('"AppState"\n{\n "appid" "7"\n "installdir" "Other"\n}\n')
|
||||
games, routes = imports.route(self.steam, self.acct, [dict(self.game, store='epic')])
|
||||
self.assertEqual({}, routes)
|
||||
self.assertEqual(1, len(games))
|
||||
self.assertFalse((self.steam / 'steamapps/appmanifest_42.acf').exists())
|
||||
self.assertFalse(os.path.lexists(self.steam / 'steamapps/common/DroidDeck-42'))
|
||||
self.assertTrue(unrelated.is_file())
|
||||
self.assertEqual(b'game', self.exe.read_bytes())
|
||||
|
||||
def test_watch_never_looks_up_store_installs(self):
|
||||
listing = self.root / 'games.json'
|
||||
listing.write_text(json.dumps([dict(self.game, store='gog')]))
|
||||
with patch.object(imports, 'identify') as identify:
|
||||
imports.watch(str(self.steam), str(listing))
|
||||
identify.assert_not_called()
|
||||
|
||||
def test_migrates_only_unchanged_legacy_import_manifests(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
|
||||
@@ -25,7 +25,6 @@ class SteamInstallTest(unittest.TestCase):
|
||||
self.requests = self.root / 'requests'
|
||||
self.bin = self.root / 'bin'
|
||||
self.bin.mkdir()
|
||||
# Only the network is faked: exercise real manifest parsing, checksums and zip extraction.
|
||||
curl = self.bin / 'curl'
|
||||
curl.write_text('''#!/bin/bash
|
||||
set -eu
|
||||
@@ -33,7 +32,6 @@ printf '%s\\n' "$2" >> "$TEST_REQUESTS"
|
||||
cp "$TEST_CDN/${2##*/}" "$4"
|
||||
''')
|
||||
curl.chmod(0o755)
|
||||
# macOS has shasum; the guest and Linux CI have sha256sum.
|
||||
if shutil.which('sha256sum') is None:
|
||||
sha = self.bin / 'sha256sum'
|
||||
sha.write_text('#!/bin/bash\nexec shasum -a 256 "$@"\n')
|
||||
@@ -78,7 +76,6 @@ cp "$TEST_CDN/${2##*/}" "$4"
|
||||
self.assert_installed()
|
||||
|
||||
def test_an_install_from_another_branch_is_left_for_steam_to_move(self):
|
||||
# An older app could install publicbeta; droiddeck-session moves the client at its start.
|
||||
self.assert_installed()
|
||||
requests = self.requests.read_text()
|
||||
(self.steam / 'package/beta').write_text('publicbeta\n')
|
||||
|
||||
@@ -37,7 +37,6 @@ def value(text, *path):
|
||||
STEAM = ('Registry', 'HKCU', 'Software', 'Valve', 'Steam', 'language')
|
||||
GLOBAL = ('Registry', 'HKCU', 'Software', 'Valve', 'Steamsteamglobal', 'language')
|
||||
|
||||
# As the client leaves it on a device (trimmed): both keys, other values beside them, and HKLM.
|
||||
CLIENT = '''"Registry"
|
||||
{
|
||||
"HKLM"
|
||||
|
||||
@@ -13,7 +13,7 @@ class SteamPresentationTest(unittest.TestCase):
|
||||
def launch(self, enabled=None, inherited=None):
|
||||
source = SESSION.read_text()
|
||||
begin = source.index(" bl_steam_path=$PATH")
|
||||
end = source.index("\n # Decky", begin)
|
||||
end = source.index("\n decky_loader=", begin)
|
||||
command = source.index(' PATH="$bl_steam_path"')
|
||||
command_end = source.index("\n rc=$?", command)
|
||||
script = (source[begin:end] + '\n_bl_ui=(-gamepadui); _bl_cdp=(); _bl_lang=()\n'
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import re
|
||||
import subprocess
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
|
||||
def stuck_function():
|
||||
match = re.search(r"^steam_update_stuck\(\) \{\n.*?^\}\n", SESSION.read_text(), re.M | re.S)
|
||||
return match.group(0) if match else None
|
||||
|
||||
|
||||
class SteamRestartCapTest(unittest.TestCase):
|
||||
def restarts(self, *seconds_up):
|
||||
function = stuck_function()
|
||||
self.assertIsNotNone(function, "droiddeck-session has no steam_update_stuck()")
|
||||
script = function + "steam_updates=0\nfor up in %s; do\n" % " ".join(map(str, seconds_up))
|
||||
script += " if steam_update_stuck \"$up\"; then echo stop; else echo restart; fi\ndone\n"
|
||||
return subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30,
|
||||
check=True).stdout.split()
|
||||
|
||||
def test_an_update_that_keeps_asking_at_once_is_stopped_on_the_third(self):
|
||||
self.assertEqual(["restart", "restart", "stop"], self.restarts(11, 13, 9))
|
||||
|
||||
def test_restarts_of_a_client_that_stayed_up_are_never_stopped(self):
|
||||
self.assertEqual(["restart"] * 5, self.restarts(75, 4000, 90, 600, 61))
|
||||
|
||||
def test_a_run_that_stayed_up_starts_the_count_again(self):
|
||||
self.assertEqual(["restart", "restart", "restart", "restart", "stop"], self.restarts(12, 10, 300, 14, 8))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -172,7 +172,6 @@ class ShortcutsTest(unittest.TestCase):
|
||||
self.assertEqual('Example: Renamed', entry['AppName'])
|
||||
self.assertEqual('"%s/data"' % GUEST, entry['StartDir'])
|
||||
self.assertEqual('-dx11', entry['LaunchOptions'])
|
||||
# One shortcut, the same appid.
|
||||
self.assertEqual([APPID], list(self.run_writer(game)))
|
||||
|
||||
def test_a_target_chosen_in_the_app_updates_the_same_shortcut(self):
|
||||
|
||||
@@ -56,7 +56,6 @@ class Detection(unittest.TestCase):
|
||||
def test_anything_else_is_left_alone(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root)
|
||||
# The exe of a store game is one too (a GOG game without a launcher); a stray file is not.
|
||||
self.assertEqual(folder, store.find_store_game([str(folder / 'Metalstorm.exe')])[0])
|
||||
self.assertIsNone(store.find_store_game([str(Path(root) / 'elsewhere/readme.txt')]))
|
||||
(folder / '.droiddeck-store.json').unlink()
|
||||
@@ -65,7 +64,6 @@ class Detection(unittest.TestCase):
|
||||
def test_only_epic_asks_for_a_code(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog')
|
||||
# Cloud saves off: GOG still prepares achievements, never an Epic exchange code.
|
||||
sc = json.loads((folder / '.droiddeck-store.json').read_text()); sc['cloud'] = False
|
||||
(folder / '.droiddeck-store.json').write_text(json.dumps(sc))
|
||||
os.environ['BL_LAUNCH_DIR'] = str(Path(root) / 'session')
|
||||
@@ -136,7 +134,6 @@ class Prefix(unittest.TestCase):
|
||||
text = self.reg.read_text()
|
||||
self.assertIn('[Software\\\\Wine\\\\WineBrowser] ', text)
|
||||
self.assertIn('"Browsers"="/usr/local/bin/droiddeck-open-url,xdg-open"', text)
|
||||
# A second launch adds nothing: the last word already says so.
|
||||
store.provision_prefix(str(self.compat))
|
||||
self.assertEqual(text, self.reg.read_text())
|
||||
|
||||
@@ -158,7 +155,6 @@ class Choices(unittest.TestCase):
|
||||
folder = game(root)
|
||||
sidecar = json.loads((folder / '.droiddeck-store.json').read_text())
|
||||
self.assertEqual({'eos': True, 'offline': False}, store.options(sidecar))
|
||||
# An earlier build's overlay field is read past.
|
||||
self.assertEqual({'eos': True, 'offline': False}, store.options({'epic': {'v': 2, 'overlay': True}}))
|
||||
sidecar['epic'] = {'eos': True, 'offline': True}
|
||||
sidecar['cloud'] = False
|
||||
@@ -175,7 +171,6 @@ class Choices(unittest.TestCase):
|
||||
finally:
|
||||
del os.environ['BL_LAUNCH_DIR']
|
||||
del os.environ['STEAM_COMPAT_DATA_PATH']
|
||||
# Offline: no request was made and no code is left; the old overlay pointer is gone.
|
||||
self.assertFalse((Path(root) / 'session/stores/req').exists())
|
||||
self.assertFalse((folder / '.droiddeck-epic-code').exists())
|
||||
text = reg.read_text()
|
||||
@@ -200,7 +195,6 @@ class Browser(unittest.TestCase):
|
||||
|
||||
class ExeTarget(unittest.TestCase):
|
||||
def test_a_game_started_by_its_exe_is_found_from_a_subfolder(self):
|
||||
# Most GOG games have no launcher .bat: Steam runs the exe, which may sit in a subfolder.
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1207664643')
|
||||
(folder / 'bin/x64').mkdir(parents=True)
|
||||
@@ -222,7 +216,6 @@ class CloudHooks(unittest.TestCase):
|
||||
original = store.ask
|
||||
asked = []
|
||||
store.ask = lambda channel, request, timeout=5.0: asked.append((request, timeout)) or {'ok': True, 'files': 2, 'reason': 'ok'}
|
||||
# 10: the launcher waits for Proton and calls --exited afterwards.
|
||||
self.assertEqual(store.STORE_GAME, store.main([bat]))
|
||||
self.assertEqual(0, store.main(['--exited', bat]))
|
||||
finally:
|
||||
@@ -309,7 +302,6 @@ class GogAchievements(unittest.TestCase):
|
||||
self.assertTrue((data / 'pfx/.droiddeck-comet-service').is_file())
|
||||
self.assertEqual('ready', store.provision_galaxy(str(data), str(proton)))
|
||||
self.assertEqual(1, len(seen))
|
||||
# A recreated prefix must be provisioned again, even with the same Proton.
|
||||
__import__('shutil').rmtree(data / 'pfx')
|
||||
self.assertEqual('ready', store.provision_galaxy(str(data), str(proton)))
|
||||
self.assertEqual(2, len(seen))
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / 'linuxfs' / 'preload'
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'linux' and shutil.which('gcc'), 'needs Linux and gcc')
|
||||
class SysvPreloadTest(unittest.TestCase):
|
||||
def test_semop_sets_otime_for_waiters(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
binary = str(Path(folder) / 'test-sysv')
|
||||
subprocess.run(['gcc', '-Wall', '-Wextra', '-O2', '-pthread', '-o', binary,
|
||||
str(Path(__file__).resolve().parent / 'sysv_otime_harness.c'), str(PRELOAD / 'sysv.c')], check=True)
|
||||
env = dict(os.environ, BL_SYSV_DIR=folder)
|
||||
result = subprocess.run([binary], capture_output=True, text=True, timeout=10, env=env)
|
||||
self.assertIn('PASS: sysv otime', result.stdout, result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -59,8 +59,6 @@ class TermuxJniTest(unittest.TestCase):
|
||||
return {key: int(value) for key, value in re.findall(r"(\w+)=(\d+)", line)}
|
||||
|
||||
def test_a_long_argv_and_environment_stay_under_the_local_reference_limit(self):
|
||||
# 300 + 300 is under 512 for each loop on its own but over it together, as the issue says:
|
||||
# ART aborts with "local reference table overflow (max=512)".
|
||||
stats = self.run_harness(300, 300)
|
||||
self.assertEqual(stats["overflowed"], 0, stats)
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("gcc"), "needs gcc on a Linux host")
|
||||
class VrclientLoaderTest(unittest.TestCase):
|
||||
def test_vrclient_keeps_syscall_interposition_without_changing_other_dsos(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
module = root / "module.c"
|
||||
module.write_text(r"""
|
||||
#include <errno.h>
|
||||
#include <stddef.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/syscall.h>
|
||||
long syscall(long number, ...) { (void)number; errno = ENOSYS; return -1; }
|
||||
int probe(void) {
|
||||
void *head = NULL; size_t length = 0;
|
||||
return syscall(SYS_get_robust_list, 0L, &head, &length) == 0 && head && length > 0;
|
||||
}
|
||||
""")
|
||||
subprocess.run(["gcc", "-shared", "-fPIC", "-O2", str(module), "-o",
|
||||
str(root / "vrclient.so")], check=True)
|
||||
shutil.copy(root / "vrclient.so", root / "ordinary.so")
|
||||
robust = Path(__file__).resolve().parents[1] / "linuxfs/preload/robust.c"
|
||||
harness = root / "loader.c"
|
||||
harness.write_text(r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <assert.h>
|
||||
#include <dlfcn.h>
|
||||
int bl_fsync_syscall(long n, const long *a, long *r) { (void)n; (void)a; (void)r; return 0; }
|
||||
#include """ + '"' + robust.as_posix() + '"' + r"""
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 3);
|
||||
void *ordinary = dlopen(argv[1], RTLD_NOW | RTLD_DEEPBIND);
|
||||
assert(ordinary);
|
||||
int (*probe)(void) = dlsym(ordinary, "probe");
|
||||
assert(probe && probe() == 0);
|
||||
dlclose(ordinary);
|
||||
void *vr = dlopen(argv[2], RTLD_NOW | RTLD_DEEPBIND);
|
||||
assert(vr);
|
||||
probe = dlsym(vr, "probe");
|
||||
assert(probe && probe() == 1);
|
||||
dlclose(vr);
|
||||
}
|
||||
""")
|
||||
subprocess.run(["gcc", "-O2", "-rdynamic", "-pthread", str(harness),
|
||||
"-ldl", "-o", str(root / "loader")], check=True)
|
||||
subprocess.run([str(root / "loader"), str(root / "ordinary.so"),
|
||||
str(root / "vrclient.so")], check=True, timeout=10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,69 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <stdio.h>
|
||||
char *const *bl_webhelper_argv(const char *path, char *const argv[]);
|
||||
int main(int argc, char **argv) {
|
||||
char *const *out = bl_webhelper_argv(argv[1], argv + 1);
|
||||
for (int i = 0; out[i]; i++) printf("%s\n", out[i]);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
WEBHELPER = "/root/.local/share/Steam/steamrtarm64/steamwebhelper"
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs cc")
|
||||
class WebhelperPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
source = cls.tmp / "program.c"
|
||||
source.write_text(PROGRAM)
|
||||
cls.program = cls.tmp / "program"
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.program), str(source),
|
||||
str(PRELOAD / "webhelper.c")], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def argv(self, *args, spec=None):
|
||||
env = {k: v for k, v in os.environ.items() if k != "BL_WEBHELPER_ARGS"}
|
||||
if spec is not None:
|
||||
env["BL_WEBHELPER_ARGS"] = spec
|
||||
result = subprocess.run([str(self.program), *args], env=env, capture_output=True, text=True, check=True)
|
||||
return result.stdout.splitlines()
|
||||
|
||||
def test_the_browser_process_keeps_its_helpers_in_process(self):
|
||||
out = self.argv(WEBHELPER, "-lang=en_US", "--enable-features=A", "--no-sandbox", "--disable-features=B,C")
|
||||
self.assertEqual(out, [WEBHELPER, "-lang=en_US", "--no-sandbox", "--no-zygote", "--in-process-gpu",
|
||||
"--enable-features=A", "--disable-features=B,C,AudioServiceOutOfProcess"])
|
||||
|
||||
def test_feature_lists_are_added_when_steam_passes_none(self):
|
||||
out = self.argv(WEBHELPER, spec="+X -Y")
|
||||
self.assertEqual(out, [WEBHELPER, "--enable-features=X", "--disable-features=Y"])
|
||||
|
||||
def test_child_processes_and_other_programs_are_left_alone(self):
|
||||
child = [WEBHELPER, "--type=renderer", "--enable-features=A"]
|
||||
self.assertEqual(self.argv(*child), child)
|
||||
other = ["/usr/bin/steam", "--enable-features=A"]
|
||||
self.assertEqual(self.argv(*other), other)
|
||||
|
||||
def test_stock_turns_it_off(self):
|
||||
args = [WEBHELPER, "--enable-features=A"]
|
||||
self.assertEqual(self.argv(*args, spec="stock"), args)
|
||||
|
||||
def test_an_empty_setting_means_the_default(self):
|
||||
self.assertIn("--no-zygote", self.argv(WEBHELPER, spec=""))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -98,7 +98,7 @@ class WinComponentsTest(unittest.TestCase):
|
||||
self.pick("vc")
|
||||
self.apply()
|
||||
self.assertEqual(installer.read_bytes(), b"ours")
|
||||
self.apply() # a second launch keeps the first backup, not ours
|
||||
self.apply()
|
||||
self.pick()
|
||||
names, notes = self.apply()
|
||||
self.assertEqual(installer.read_bytes(), b"from a real installer")
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static const char *ctl;
|
||||
static size_t size, page;
|
||||
static volatile int stop;
|
||||
static unsigned char *shared;
|
||||
|
||||
static long status(const char *key) {
|
||||
FILE *f = fopen("/proc/self/status", "r");
|
||||
char line[256];
|
||||
long v = -1;
|
||||
while (f && fgets(line, sizeof(line), f))
|
||||
if (!strncmp(line, key, strlen(key))) v = atol(line + strlen(key));
|
||||
if (f) fclose(f);
|
||||
return v;
|
||||
}
|
||||
|
||||
static void request(char mode) {
|
||||
int fd = open(ctl, O_WRONLY | O_TRUNC);
|
||||
if (fd < 0 || write(fd, &mode, 1) != 1) exit(3);
|
||||
close(fd);
|
||||
kill(getpid(), SIGURG);
|
||||
}
|
||||
|
||||
static uint64_t sum(const unsigned char *p, size_t n) {
|
||||
uint64_t s = 0;
|
||||
for (size_t i = 0; i < n; i += 64) s = s * 31 + p[i];
|
||||
return s;
|
||||
}
|
||||
|
||||
static void *writer(void *arg) {
|
||||
unsigned char *mine = shared + (size_t)(uintptr_t)arg * (size / 4);
|
||||
for (unsigned char round = 1; !stop; round++) {
|
||||
for (size_t i = 0; i < size / 4; i += page) {
|
||||
if (round > 1 && mine[i] != (unsigned char)(round - 1)) {
|
||||
printf("corrupt\n");
|
||||
exit(4);
|
||||
}
|
||||
mine[i] = round;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
ctl = argv[1];
|
||||
size = strtoul(argv[2], NULL, 0) << 20;
|
||||
int cycles = atoi(argv[3]);
|
||||
page = (size_t)sysconf(_SC_PAGESIZE);
|
||||
unsigned char *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
for (size_t i = 0; i < size; i++) data[i] = (unsigned char)(i * 7 + i / 4096);
|
||||
uint64_t before = sum(data, size);
|
||||
shared = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
memset(shared, 0, size);
|
||||
pthread_t t[2];
|
||||
for (uintptr_t i = 0; i < 2; i++) pthread_create(&t[i], NULL, writer, (void *)i);
|
||||
struct sigaction sa;
|
||||
sigaction(SIGURG, NULL, &sa);
|
||||
printf("handler %d\n", (sa.sa_flags & SA_SIGINFO) ? 1 : 0);
|
||||
if (argc > 4) {
|
||||
unsigned char *ro = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
memset(ro, 0x5a, size);
|
||||
mprotect(ro, size, PROT_READ);
|
||||
madvise(ro, size, 21);
|
||||
printf("elsewhere %ld\n", status("VmSwap:"));
|
||||
request('0');
|
||||
printf("back %ld\n", status("VmSwap:"));
|
||||
}
|
||||
for (int c = 0; c < cycles; c++) {
|
||||
request('1');
|
||||
printf("out %ld\n", status("VmSwap:"));
|
||||
request('0');
|
||||
printf("back %ld\n", status("VmSwap:"));
|
||||
}
|
||||
stop = 1;
|
||||
for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
|
||||
printf("intact %d\n", sum(data, size) == before);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def swap_total_kb():
|
||||
for line in Path("/proc/meminfo").read_text().splitlines():
|
||||
if line.startswith("SwapTotal:"):
|
||||
return int(line.split()[1])
|
||||
return 0
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class ZramPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.dir = Path(tempfile.mkdtemp())
|
||||
cls.ctl = cls.dir / "ctl"
|
||||
build = cls.dir / "build"
|
||||
build.mkdir()
|
||||
(build / "program.c").write_text(PROGRAM)
|
||||
cls.lib = build / "libblsession.so"
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-DZR_CTL=\"%s\"" % cls.ctl,
|
||||
"-o", str(cls.lib), *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
|
||||
cls.steam = cls.dir / "steam"
|
||||
subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.steam), str(build / "program.c")], check=True)
|
||||
cls.game = cls.dir / "game"
|
||||
shutil.copy(cls.steam, cls.game)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.dir, True)
|
||||
|
||||
def setUp(self):
|
||||
self.ctl.write_text("0")
|
||||
|
||||
def run_program(self, program=None, mb=48, cycles=1, *extra):
|
||||
environment = dict(os.environ, LD_PRELOAD=str(self.lib))
|
||||
result = subprocess.run([str(program or self.steam), str(self.ctl), str(mb), str(cycles), *extra], env=environment,
|
||||
capture_output=True, text=True, check=True, timeout=120)
|
||||
out = {}
|
||||
for line in result.stdout.splitlines():
|
||||
key, value = line.split()
|
||||
out.setdefault(key, []).append(int(value))
|
||||
return out
|
||||
|
||||
def test_only_the_client_takes_the_signal(self):
|
||||
self.assertEqual([1], self.run_program()["handler"])
|
||||
self.assertEqual([0], self.run_program(self.game)["handler"])
|
||||
|
||||
def test_nothing_is_installed_without_the_control_file(self):
|
||||
self.ctl.unlink()
|
||||
try:
|
||||
self.assertEqual([0], self.run_program(cycles=0)["handler"])
|
||||
finally:
|
||||
self.ctl.write_text("0")
|
||||
|
||||
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
|
||||
def test_pages_out_and_reads_back(self):
|
||||
out = self.run_program(mb=48)
|
||||
self.assertGreater(out["out"][0], 32 * 1024)
|
||||
self.assertLess(out["back"][0], out["out"][0] // 4)
|
||||
self.assertEqual([1], out["intact"])
|
||||
|
||||
@unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap")
|
||||
def test_reads_back_what_the_kernel_swapped_elsewhere(self):
|
||||
out = self.run_program(None, 32, 0, "read-only")
|
||||
self.assertGreater(out["elsewhere"][0], 16 * 1024)
|
||||
self.assertLess(out["back"][0], out["elsewhere"][0] // 4)
|
||||
|
||||
def test_memory_stays_intact_under_writers(self):
|
||||
out = self.run_program(mb=32, cycles=6)
|
||||
self.assertEqual([1], out["intact"])
|
||||
self.assertEqual(6, len(out["out"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user