mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 22:36:00 +00:00
Merge upstream PC input and dual-screen updates
This commit is contained in:
commit
68b0396dfe
819 files changed
+43953
-6186
No files matched your search
@@ -0,0 +1,61 @@
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "cursor_constants.inc"
|
||||
#include "cursor_scene_positions.inc"
|
||||
#include "cursor_clip_to_eye.inc"
|
||||
|
||||
int main(void) {
|
||||
int out[2];
|
||||
int dx, sx, dw;
|
||||
|
||||
assert(cursor_scene_positions(1920, CARDBOARD_SOURCE_SCREEN, 100, 0, out) == 1);
|
||||
assert(out[0] == 100);
|
||||
|
||||
assert(cursor_scene_positions(1920, CARDBOARD_SOURCE_FLAT, 100, 0, out) == 1);
|
||||
assert(out[0] == 100);
|
||||
|
||||
assert(cursor_scene_positions(1, CARDBOARD_SOURCE_SBS, 0, 0, out) == 1);
|
||||
|
||||
assert(cursor_scene_positions(3840, CARDBOARD_SOURCE_SBS, 100, 0, out) == 2);
|
||||
assert(out[0] == 100 && out[1] == 2020);
|
||||
|
||||
assert(cursor_scene_positions(3840, CARDBOARD_SOURCE_SBS, 2000, 0, out) == 2);
|
||||
assert(out[0] == 2000 && out[1] == 80);
|
||||
|
||||
assert(cursor_scene_positions(3840, CARDBOARD_SOURCE_SBS, 1919, 0, out) == 2);
|
||||
assert(out[0] == 1919 && out[1] == 3839);
|
||||
|
||||
assert(cursor_scene_positions(3840, CARDBOARD_SOURCE_SBS, 1920, 0, out) == 2);
|
||||
assert(out[0] == 1920 && out[1] == 0);
|
||||
|
||||
assert(cursor_scene_positions(1920, CARDBOARD_SOURCE_SBS, 960, 32, out) == 2);
|
||||
assert(out[0] == 928 && out[1] == -32);
|
||||
|
||||
assert(cursor_scene_positions(1920, CARDBOARD_SOURCE_SBS, 959, 32, out) == 2);
|
||||
assert(out[0] == 927 && out[1] == 1887);
|
||||
|
||||
assert(cursor_clip_to_eye(1920, -1, 100, 32, &dx, &sx, &dw) == 1);
|
||||
assert(dx == 100 && sx == 0 && dw == 32);
|
||||
|
||||
assert(cursor_clip_to_eye(1920, 0, 100, 32, &dx, &sx, &dw) == 1);
|
||||
assert(dx == 100 && sx == 0 && dw == 32);
|
||||
|
||||
assert(cursor_clip_to_eye(1920, 0, 950, 32, &dx, &sx, &dw) == 1);
|
||||
assert(dx == 950 && sx == 0 && dw == 10);
|
||||
|
||||
assert(cursor_clip_to_eye(1920, 1, 950, 32, &dx, &sx, &dw) == 1);
|
||||
assert(dx == 960 && sx == 10 && dw == 22);
|
||||
|
||||
assert(cursor_clip_to_eye(1920, 1, 960, 32, &dx, &sx, &dw) == 1);
|
||||
assert(dx == 960 && sx == 0 && dw == 32);
|
||||
|
||||
assert(cursor_clip_to_eye(1920, 0, 928, 32, &dx, &sx, &dw) == 1);
|
||||
assert(dx == 928 && sx == 0 && dw == 32);
|
||||
|
||||
assert(cursor_clip_to_eye(1920, 1, 928, 32, &dx, &sx, &dw) == 0);
|
||||
assert(cursor_clip_to_eye(1920, 0, -32, 32, &dx, &sx, &dw) == 0);
|
||||
|
||||
puts("PASS: cursor stereo placement");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "kgsl_busy.h"
|
||||
#include "kgsl_layout.h"
|
||||
|
||||
#define ENTRIES 819
|
||||
|
||||
static uint32_t memstore[ENTRIES * KGSL_BUSY_ENTRY_WORDS];
|
||||
|
||||
static void stamp(int entry, uint32_t sop, uint32_t eop) {
|
||||
memstore[entry * KGSL_BUSY_ENTRY_WORDS + KGSL_BUSY_SOP] = sop;
|
||||
memstore[entry * KGSL_BUSY_ENTRY_WORDS + KGSL_BUSY_EOP] = eop;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
assert(kgsl_busy_first_slot(8 * 4096) == 813);
|
||||
assert(kgsl_busy_first_slot(8 * 16384) == 3270);
|
||||
assert(kgsl_busy_first_slot(7 * 40) == -1);
|
||||
|
||||
int first = kgsl_busy_first_slot(sizeof(memstore));
|
||||
uint32_t last[KGSL_BUSY_SLOTS] = {0};
|
||||
int moved = 0;
|
||||
|
||||
stamp(first, 100, 100);
|
||||
stamp(first + 2, 7, 7);
|
||||
assert(kgsl_busy_sample(memstore, first, last, &moved) == 0);
|
||||
assert(moved == 1 && last[0] == 100 && last[2] == 7);
|
||||
|
||||
moved = 0;
|
||||
assert(kgsl_busy_sample(memstore, first, last, &moved) == 0);
|
||||
assert(moved == 0);
|
||||
|
||||
stamp(first + 2, 8, 7);
|
||||
assert(kgsl_busy_sample(memstore, first, last, &moved) == 1);
|
||||
assert(moved == 1);
|
||||
|
||||
moved = 0;
|
||||
stamp(first + 2, 8, 8);
|
||||
assert(kgsl_busy_sample(memstore, first, last, &moved) == 0);
|
||||
assert(moved == 0);
|
||||
|
||||
stamp(first + 4, 3, 2);
|
||||
assert(kgsl_busy_sample(memstore, first, last, &moved) == 1);
|
||||
|
||||
memset(memstore, 0, sizeof(memstore));
|
||||
stamp(first - 1, 5, 4);
|
||||
stamp(first + KGSL_BUSY_SLOTS, 9, 8);
|
||||
memset(last, 0, sizeof(last));
|
||||
moved = 0;
|
||||
assert(kgsl_busy_sample(memstore, first, last, &moved) == 0);
|
||||
assert(moved == 0);
|
||||
|
||||
puts("PASS: kgsl memstore busy");
|
||||
|
||||
// Hardware-scheduled kernels: ringbuffer entries stay 0, contexts carry the stamps.
|
||||
memset(memstore, 0, sizeof(memstore));
|
||||
static uint32_t seen[ENTRIES], ctx_last[ENTRIES];
|
||||
int live[KGSL_BUSY_MAX_LIVE];
|
||||
stamp(3, 50, 50);
|
||||
stamp(9, 21, 20);
|
||||
stamp(first - 1, 4, 4);
|
||||
int count = kgsl_busy_scan_contexts(memstore, first, seen, live, KGSL_BUSY_MAX_LIVE);
|
||||
assert(count == 3 && live[0] == 3 && live[1] == 9 && live[2] == first - 1);
|
||||
moved = 0;
|
||||
assert(kgsl_busy_sample_contexts(memstore, live, count, ctx_last, &moved) == 1);
|
||||
assert(moved == 1 && ctx_last[9] == 21);
|
||||
|
||||
// Busy or newly started contexts come first; idle ones that have run work stay in the list.
|
||||
stamp(9, 21, 21);
|
||||
stamp(5, 2, 1);
|
||||
count = kgsl_busy_scan_contexts(memstore, first, seen, live, KGSL_BUSY_MAX_LIVE);
|
||||
assert(count == 4 && live[0] == 5 && live[1] == 3 && live[2] == 9 && live[3] == first - 1);
|
||||
moved = 0;
|
||||
assert(kgsl_busy_sample_contexts(memstore, live, count, ctx_last, &moved) == 1);
|
||||
assert(moved == 1);
|
||||
moved = 0;
|
||||
assert(kgsl_busy_sample_contexts(memstore, live, count, ctx_last, &moved) == 1);
|
||||
assert(moved == 0);
|
||||
stamp(5, 2, 2);
|
||||
assert(kgsl_busy_sample_contexts(memstore, live, count, ctx_last, &moved) == 0);
|
||||
|
||||
// Entry 0 (global) and the ringbuffer entries are not contexts; the live list is capped.
|
||||
memset(memstore, 0, sizeof(memstore));
|
||||
memset(seen, 0, sizeof(seen));
|
||||
stamp(0, 8, 7);
|
||||
stamp(first, 8, 7);
|
||||
assert(kgsl_busy_scan_contexts(memstore, first, seen, live, KGSL_BUSY_MAX_LIVE) == 0);
|
||||
for (int id = 1; id <= KGSL_BUSY_MAX_LIVE + 10; id++) stamp(id, 1, 1);
|
||||
assert(kgsl_busy_scan_contexts(memstore, first, seen, live, KGSL_BUSY_MAX_LIVE) == KGSL_BUSY_MAX_LIVE);
|
||||
assert(kgsl_busy_scan_contexts(memstore, first, seen, live, KGSL_BUSY_MAX_LIVE) == KGSL_BUSY_MAX_LIVE);
|
||||
stamp(KGSL_BUSY_MAX_LIVE + 5, 2, 1);
|
||||
assert(kgsl_busy_scan_contexts(memstore, first, seen, live, KGSL_BUSY_MAX_LIVE) == KGSL_BUSY_MAX_LIVE);
|
||||
assert(live[0] == KGSL_BUSY_MAX_LIVE + 5);
|
||||
stamp(KGSL_BUSY_MAX_LIVE + 5, 0, 0);
|
||||
count = kgsl_busy_scan_contexts(memstore, first, seen, live, KGSL_BUSY_MAX_LIVE);
|
||||
count = kgsl_busy_scan_contexts(memstore, first, seen, live, KGSL_BUSY_MAX_LIVE);
|
||||
for (int i = 0; i < count; i++) assert(live[i] != KGSL_BUSY_MAX_LIVE + 5);
|
||||
puts("PASS: kgsl memstore contexts");
|
||||
|
||||
assert(kgsl_layout_for(0x44050001u) == &KGSL_LAYOUT_A8XX); // Adreno 830
|
||||
assert(kgsl_layout_for(0x44030a20u) == &KGSL_LAYOUT_A8XX); // Adreno 829
|
||||
assert(kgsl_layout_for(0x43020100u) == &KGSL_LAYOUT_A7XX); // Adreno 722
|
||||
assert(kgsl_layout_for(0x43050a01u) == &KGSL_LAYOUT_A7XX); // Adreno 740
|
||||
assert(kgsl_layout_for(0x07010000u) == &KGSL_LAYOUT_A7XX); // Adreno 710
|
||||
assert(kgsl_layout_for(0x06030001u) == &KGSL_LAYOUT_A7XX); // Adreno 630
|
||||
assert(kgsl_layout_for(0x45000000u) == NULL);
|
||||
assert(KGSL_LAYOUT_A8XX.always_on == 0x8e7u && KGSL_LAYOUT_A8XX.cycles == 1u);
|
||||
assert(KGSL_LAYOUT_A7XX.always_on == 0x980u && KGSL_LAYOUT_A7XX.cycles == 0u);
|
||||
puts("PASS: kgsl counter layout");
|
||||
return 0;
|
||||
}
|
||||
@@ -23,8 +23,6 @@ static void wl_pointer_send_button(struct wl_resource *r, uint32_t serial,
|
||||
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);
|
||||
|
||||
@@ -293,11 +293,13 @@ class ProcessTest(Temp):
|
||||
def test_battle_nets_own_processes_are_those_under_its_folders(self):
|
||||
for argv in (["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe", "--type=renderer"],
|
||||
["C:/ProgramData/Battle.net/Agent/Agent.9824/Agent.exe"],
|
||||
["C:\\Program Files (x86)\\Battle.net\\Battle.net Launcher.exe"]):
|
||||
["C:\\Program Files (x86)\\Battle.net\\Battle.net Launcher.exe"],
|
||||
["C:\\Program Files (x86)\\Battle.net\\Battle.net.17952\\BlizzardError.exe"]):
|
||||
with self.subTest(argv):
|
||||
self.assertTrue(BNET["is_battlenet"](argv))
|
||||
for argv in (["Z:\\root\\.cache\\droiddeck\\battlenet\\Battle.net-Setup.exe"],
|
||||
["Z:\\root\\Games\\Stores\\Battle.net\\Hearthstone\\Hearthstone.exe"],
|
||||
["C:\\Program Files (x86)\\Battle.net\\World of Warcraft\\_forever_\\Wow-arm64.exe"],
|
||||
["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe"], ["C:\\windows\\system32\\services.exe"], []):
|
||||
with self.subTest(argv):
|
||||
self.assertFalse(BNET["is_battlenet"](argv))
|
||||
@@ -305,6 +307,8 @@ class ProcessTest(Temp):
|
||||
def test_a_game_battle_net_launched_carries_its_uid(self):
|
||||
self.assertTrue(BNET["launched"](["C:\\Program Files (x86)\\Diablo II Resurrected\\D2R.exe", "-uid", "osi"]))
|
||||
self.assertTrue(BNET["launched"](["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe", "-launch", "-UID", "fenris"]))
|
||||
self.assertTrue(BNET["launched"](["C:\\Program Files (x86)\\Battle.net\\World of Warcraft\\_forever_\\Wow-arm64.exe",
|
||||
"-launcherlogin", "-uid", "wowf"]))
|
||||
for argv in (["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe"],
|
||||
["C:\\Program Files (x86)\\Diablo IV\\vc_redist.x64.exe", "/quiet"],
|
||||
["C:\\Program Files (x86)\\Battle.net\\Battle.net.exe", "-uid", "battle.net"]):
|
||||
@@ -831,6 +835,15 @@ class LaunchTest(Harness):
|
||||
self.assertEqual(BNET["launch"](self.root, "Fen"), 0)
|
||||
self.assertEqual([c for c in self.calls if c[0] == "stop"], [("stop", [10, 11, 12, 13, 14, 30])])
|
||||
|
||||
def test_a_game_installed_in_battle_nets_folder_is_followed_not_stopped(self):
|
||||
self.install()
|
||||
up = self.clients() + [(30, self.AGENT)]
|
||||
wow = (40, ["C:\\Program Files (x86)\\Battle.net\\World of Warcraft\\_forever_\\Wow-arm64.exe", "-launcherlogin", "-uid", "wowf"])
|
||||
wine = (50, ["C:\\windows\\system32\\services.exe"])
|
||||
self.states = [[], [], up, up + [wow], [wow, wine], [wow, wine], [wine], [wine]]
|
||||
self.assertEqual(BNET["launch"](self.root, "WoWF"), 0)
|
||||
self.assertEqual([c for c in self.calls if c[0] == "stop"], [("stop", [50])])
|
||||
|
||||
def test_battle_net_closing_itself_as_it_launches_the_game_is_not_an_end(self):
|
||||
game = (40, self.GAME + ["-uid", "fenris"])
|
||||
self.states = [[], [game], [game], [], []]
|
||||
@@ -896,6 +909,27 @@ class LaunchTest(Harness):
|
||||
self.assertEqual(image.read_bytes(), b"BM1152x720")
|
||||
self.assertIn('"WallpaperStyle"="2"', (pfx / "user.reg").read_text())
|
||||
|
||||
def test_a_large_desktop_scales_battle_net_to_fit_it(self):
|
||||
sizes = {("1280", "720"): 96, ("1920", "1080"): 96, ("2400", "1504"): 120, ("2448", "1848"): 120,
|
||||
("1080", "2400"): 96, ("3840", "2160"): 192, ("2560", "1600"): 120}
|
||||
for (width, height), want in sizes.items():
|
||||
with mock.patch.dict(os.environ, {"BL_WIDTH": width, "BL_HEIGHT": height}):
|
||||
self.assertEqual(BNET["desktop_dpi"](), want, (width, height))
|
||||
|
||||
def test_battle_nets_desktop_scale_is_written_once_and_follows_the_size(self):
|
||||
self.install()
|
||||
pfx = Path(self.root) / ("steamapps/compatdata/%s/pfx" % BNET["APP_ID"])
|
||||
(pfx / "user.reg").write_text('WINE REGISTRY Version 2\n\n[Control Panel\\\\Desktop] 1\n"LogPixels"=dword:00000060\n')
|
||||
with mock.patch.dict(os.environ, {"BL_WIDTH": "1280", "BL_HEIGHT": "720"}):
|
||||
self.assertTrue(BNET["dpi"](self.root))
|
||||
self.assertEqual((pfx / "user.reg").read_text().count("LogPixels"), 1)
|
||||
with mock.patch.dict(os.environ, {"BL_WIDTH": "2448", "BL_HEIGHT": "1848"}):
|
||||
self.assertTrue(BNET["dpi"](self.root))
|
||||
self.assertTrue(BNET["dpi"](self.root))
|
||||
reg = (pfx / "user.reg").read_text()
|
||||
self.assertEqual(reg.count('"LogPixels"=dword:00000078'), 1)
|
||||
self.assertTrue(reg.rstrip().endswith('"LogPixels"=dword:00000078'))
|
||||
|
||||
def test_an_open_battle_net_is_handed_the_game(self):
|
||||
self.install()
|
||||
up = self.clients()
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import os
|
||||
import runpy
|
||||
import shutil
|
||||
import struct
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap"
|
||||
|
||||
|
||||
def elf(path, machine):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"\x7fELF\x02\x01\x01" + bytes(11) + struct.pack("<H", machine) + bytes(64))
|
||||
path.chmod(0o755)
|
||||
|
||||
|
||||
class BwrapFexTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, True)
|
||||
self.shim = runpy.run_path(str(BWRAP))
|
||||
self.fex = self.dir / "fex"
|
||||
for name in ("bin/FEX", "bin/FEXServer", "lib/libxxhash.so.0"):
|
||||
elf(self.fex / name, 183)
|
||||
self.shim["through_fex"].__globals__["OWN_FEX"] = str(self.fex)
|
||||
self.runtime = self.dir / "runtime"
|
||||
self.app = self.dir / "app"
|
||||
elf(self.runtime / "bin/ldconfig", 62)
|
||||
elf(self.runtime / "bin/bash", 62)
|
||||
os.symlink("bash", self.runtime / "bin/sh")
|
||||
elf(self.runtime / "bin/arm-tool", 183)
|
||||
(self.app / "bin").mkdir(parents=True)
|
||||
(self.app / "bin/r2modman").write_text("#!/bin/sh\nexec /app/r2modman \"$@\"\n")
|
||||
|
||||
def spec(self, command, path="/app/bin:/usr/bin"):
|
||||
s = self.shim["Spec"]()
|
||||
s.env = {"PATH": path, "XDG_CACHE_HOME": "/home/user/.var/app/x/cache", "FEX_ROOTFS": "/sniper"}
|
||||
s.ops = [
|
||||
{"t": "bind", "src": str(self.runtime), "dest": "/usr", "try": False, "ro": True},
|
||||
{"t": "bind", "src": str(self.app), "dest": "/app", "try": False, "ro": True},
|
||||
{"t": "symlink", "target": "usr/bin", "dest": "/bin"},
|
||||
]
|
||||
s.command = command
|
||||
return s
|
||||
|
||||
def test_an_x86_64_program_found_on_path_runs_through_fex(self):
|
||||
s = self.spec(["ldconfig", "-X", "-C", "/run/cache"])
|
||||
self.assertTrue(self.shim["through_fex"](s))
|
||||
self.assertEqual(["/run/droiddeck-fex/bin/FEX", "/usr/bin/ldconfig", "-X", "-C", "/run/cache"], s.command)
|
||||
dests = {op["dest"]: op["src"] for op in s.ops if op["t"] == "bind"}
|
||||
self.assertEqual(str(self.fex / "bin/FEX"), dests["/run/droiddeck-fex/bin/FEX"])
|
||||
self.assertEqual(str(self.fex / "lib/libxxhash.so.0"), dests["/run/droiddeck-fex/lib/libxxhash.so.0"])
|
||||
self.assertIn("/usr/lib/aarch64-linux-gnu", dests)
|
||||
self.assertIn("/usr/lib/ld-linux-aarch64.so.1", dests)
|
||||
self.assertNotIn("FEX_ROOTFS", s.env)
|
||||
self.assertEqual("/home/user/.var/app/x/cache/droiddeck-fex/", s.env["FEX_APP_DATA_LOCATION"])
|
||||
|
||||
def test_a_script_whose_interpreter_is_x86_64_runs_through_fex(self):
|
||||
s = self.spec(["r2modman", "--flag"])
|
||||
self.assertTrue(self.shim["through_fex"](s))
|
||||
self.assertEqual(["/run/droiddeck-fex/bin/FEX", "/app/bin/r2modman", "--flag"], s.command)
|
||||
|
||||
def test_a_program_reached_through_a_sandbox_symlink_is_checked(self):
|
||||
s = self.spec(["/bin/sh", "-c", "true"])
|
||||
self.assertTrue(self.shim["through_fex"](s))
|
||||
self.assertEqual("/bin/sh", s.command[1])
|
||||
|
||||
def test_a_bind_whose_source_is_a_symlink_resolves_from_the_source(self):
|
||||
real = self.dir / "store" / "tool-real"
|
||||
elf(real, 62)
|
||||
os.symlink("tool-real", self.dir / "store" / "tool-link")
|
||||
s = self.spec(["/opt/tool"])
|
||||
s.ops.append({"t": "bind", "src": str(self.dir / "store" / "tool-link"), "dest": "/opt/tool", "try": False,
|
||||
"ro": True})
|
||||
self.assertTrue(self.shim["through_fex"](s))
|
||||
self.assertEqual("/opt/tool", s.command[1])
|
||||
|
||||
def test_a_relative_path_entry_is_searched_from_the_working_directory(self):
|
||||
s = self.spec(["r2modman"], path="bin")
|
||||
s.cwd = "/app"
|
||||
self.assertTrue(self.shim["through_fex"](s))
|
||||
self.assertEqual("/app/bin/r2modman", s.command[1])
|
||||
|
||||
def test_an_arm64_program_runs_as_it_is(self):
|
||||
s = self.spec(["arm-tool"])
|
||||
self.assertFalse(self.shim["through_fex"](s))
|
||||
self.assertEqual(["arm-tool"], s.command)
|
||||
self.assertEqual(3, len(s.ops))
|
||||
|
||||
def test_a_missing_program_is_left_alone(self):
|
||||
s = self.spec(["nothing-here"])
|
||||
self.assertFalse(self.shim["through_fex"](s))
|
||||
self.assertEqual(["nothing-here"], s.command)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -82,7 +82,7 @@ class CiChecksTest(unittest.TestCase):
|
||||
gate = jobs['checks']
|
||||
self.assertEqual(gate['name'], 'Compile and test APK')
|
||||
self.assertEqual(set(gate['needs']), {'build', 'python-tests'})
|
||||
self.assertIn('always()', gate['if'])
|
||||
self.assertIn('!cancelled()', gate['if'])
|
||||
for build, python in itertools.product(('success', 'failure', 'cancelled', 'skipped'), repeat=2):
|
||||
with self.subTest(build=build, python=python):
|
||||
result = subprocess.run(
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Single-core Steam affinity is rechecked even if its thread count stayed the same."""
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
@@ -43,6 +43,41 @@ class ClientZramFocusTest(unittest.TestCase):
|
||||
self.assertEqual('', result.stderr)
|
||||
self.assertEqual('5000010 5000011 5000012|5000013 5000014 5000015|1| 413150', result.stdout.strip())
|
||||
|
||||
def scan_fake(self, tasks):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for pid, argv in tasks:
|
||||
self.write_cmd(Path(tmp), pid, argv)
|
||||
source = function_source('bl_zram_scan').replace('/proc/[0-9]*', tmp + '/[0-9]*')
|
||||
return run_bash(source + '\nbl_zram_scan\necho "${_bl_pids[*]}|${_bl_others[*]}|$_bl_game"')
|
||||
|
||||
def test_battlenet_is_compressed_with_the_client_while_one_of_its_games_runs(self):
|
||||
launcher = [
|
||||
(6000010, ['/s/steamrtarm64/steam', '-gamepadui']),
|
||||
(6000011, ['/s/reaper', 'SteamLaunch', 'AppId=2899116412', '--', 'droiddeck-battlenet']),
|
||||
(6000012, ['C:\\Program Files (x86)\\Battle.net\\Battle.net.exe', '--exec=launch S1']),
|
||||
(6000013, ['C:\\Program Files (x86)\\Battle.net\\Battle.net.15511\\Battle.net Helper.exe', '--type=renderer']),
|
||||
(6000014, ['C:\\ProgramData\\Battle.net\\Agent\\Agent.9324\\Agent.exe', '--internalclienttools']),
|
||||
(6000015, ['C:\\windows\\system32\\services.exe']),
|
||||
(6000016, ['C:\\windows\\system32\\winedevice.exe', '-uid']),
|
||||
]
|
||||
game = [(6000017, ['S:\\Games\\StarCraft\\x86\\StarCraft.exe', '-launch', '-uid', 's1'])]
|
||||
before = self.scan_fake(launcher)
|
||||
during = self.scan_fake(launcher + game)
|
||||
for result in (before, during):
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('', result.stderr)
|
||||
self.assertEqual('6000010|6000015 6000016 6000012 6000013 6000014|1', before.stdout.strip())
|
||||
self.assertEqual('6000010 6000012 6000013 6000014|6000015 6000016 6000017|1', during.stdout.strip())
|
||||
|
||||
def test_a_game_without_a_battlenet_uid_leaves_battlenet_alone(self):
|
||||
result = self.scan_fake([
|
||||
(6000020, ['C:\\Program Files (x86)\\Battle.net\\Battle.net.exe']),
|
||||
(6000021, ['D:\\Games\\Other\\Game.exe', '-windowed']),
|
||||
(6000022, ['/usr/bin/wine', 'game.exe', '-uid']),
|
||||
])
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('|6000021 6000022 6000020|0', result.stdout.strip())
|
||||
|
||||
def test_refocus_restarts_the_delay_and_game_exit_restores_a_packed_client(self):
|
||||
source = SCRIPT.read_text()
|
||||
start = source.index(' if [ "$_bl_game" = 1 ] && bl_game_focused; then')
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <linux/futex.h>
|
||||
#include <pthread.h>
|
||||
#include <semaphore.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/timerfd.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int64_t ns(clockid_t clock) {
|
||||
struct timespec ts;
|
||||
clock_gettime(clock, &ts);
|
||||
return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
|
||||
}
|
||||
|
||||
static struct timespec in(clockid_t clock, int64_t delay) {
|
||||
int64_t t = ns(clock) + delay;
|
||||
struct timespec ts = {(time_t)(t / 1000000000LL), (long)(t % 1000000000LL)};
|
||||
return ts;
|
||||
}
|
||||
|
||||
static int64_t start;
|
||||
static void begin(void) { start = ns(CLOCK_BOOTTIME); }
|
||||
static void end(const char *name) { printf("%s %lld\n", name, (long long)((ns(CLOCK_BOOTTIME) - start) / 1000000LL)); }
|
||||
|
||||
int main(void) {
|
||||
const int64_t wait = 60000000LL;
|
||||
printf("gap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ns(CLOCK_MONOTONIC)) / 1000000LL));
|
||||
struct timespec raw;
|
||||
syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &raw);
|
||||
printf("rawgap %lld\n", (long long)((ns(CLOCK_BOOTTIME) - ((int64_t)raw.tv_sec * 1000000000LL + raw.tv_nsec)) / 1000000LL));
|
||||
|
||||
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
pthread_condattr_t attr;
|
||||
pthread_cond_t mono, real;
|
||||
pthread_condattr_init(&attr);
|
||||
pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
|
||||
pthread_cond_init(&mono, &attr);
|
||||
pthread_cond_init(&real, NULL);
|
||||
struct timespec ts;
|
||||
|
||||
pthread_mutex_lock(&mutex);
|
||||
ts = in(CLOCK_MONOTONIC, wait); begin(); pthread_cond_timedwait(&mono, &mutex, &ts); end("cond_mono");
|
||||
ts = in(CLOCK_REALTIME, wait); begin(); pthread_cond_timedwait(&real, &mutex, &ts); end("cond_real");
|
||||
ts = in(CLOCK_MONOTONIC, wait); begin(); pthread_cond_clockwait(&real, &mutex, CLOCK_MONOTONIC, &ts); end("clockwait");
|
||||
pthread_mutex_unlock(&mutex);
|
||||
|
||||
sem_t sem;
|
||||
sem_init(&sem, 0, 0);
|
||||
ts = in(CLOCK_MONOTONIC, wait); begin(); sem_clockwait(&sem, CLOCK_MONOTONIC, &ts); end("sem");
|
||||
|
||||
ts = in(CLOCK_MONOTONIC, wait); begin(); clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL); end("nanosleep");
|
||||
|
||||
int fd = timerfd_create(CLOCK_MONOTONIC, 0);
|
||||
struct itimerspec it = {{0, 0}, in(CLOCK_MONOTONIC, wait)};
|
||||
uint64_t ticks;
|
||||
timerfd_settime(fd, TFD_TIMER_ABSTIME, &it, NULL);
|
||||
begin(); if (read(fd, &ticks, sizeof(ticks)) < 0) ticks = 0; end("timerfd");
|
||||
|
||||
static uint32_t word;
|
||||
ts = in(CLOCK_MONOTONIC, wait); begin();
|
||||
syscall(SYS_futex, &word, FUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG, 0, &ts, NULL, FUTEX_BITSET_MATCH_ANY);
|
||||
end("futex");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
SHIFT_MS = 10000
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class ClockPausePreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp = tempfile.TemporaryDirectory()
|
||||
cls.dir = Path(cls.temp.name)
|
||||
cls.control = cls.dir / "clock"
|
||||
build = cls.dir / "build"
|
||||
build.mkdir()
|
||||
(build / "program.c").write_text(PROGRAM)
|
||||
cls.preload = build / "libblsession.so"
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-DBL_CLOCK_ANY_ARCH",
|
||||
'-DCP_CTL="%s"' % cls.control, "-o", str(cls.preload),
|
||||
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
|
||||
cls.shell = build / "plasmashell"
|
||||
subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.shell), str(build / "program.c")], check=True)
|
||||
cls.other = build / "kwin_wayland"
|
||||
shutil.copy(cls.shell, cls.other)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.temp.cleanup()
|
||||
|
||||
def run_program(self, program, shift_ms, preload=True):
|
||||
self.control.write_bytes(struct.pack("<q", shift_ms * 1000000))
|
||||
env = dict(os.environ)
|
||||
if preload:
|
||||
env["LD_PRELOAD"] = str(self.preload)
|
||||
result = subprocess.run([str(program)], env=env, capture_output=True, text=True, check=True, timeout=30)
|
||||
return {name: int(value) for name, value in (line.split() for line in result.stdout.splitlines())}
|
||||
|
||||
def test_the_shell_sees_monotonic_time_stopped_for_the_pause(self):
|
||||
plain = self.run_program(self.shell, 0)
|
||||
paused = self.run_program(self.shell, SHIFT_MS)
|
||||
self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50)
|
||||
self.assertAlmostEqual(paused["rawgap"] - plain["rawgap"], SHIFT_MS, delta=50)
|
||||
|
||||
def test_timed_waits_last_as_long_as_asked_after_a_pause(self):
|
||||
paused = self.run_program(self.shell, SHIFT_MS)
|
||||
for name in ("cond_mono", "cond_real", "clockwait", "sem", "nanosleep", "timerfd", "futex"):
|
||||
self.assertGreaterEqual(paused[name], 50, name)
|
||||
self.assertLess(paused[name], 1000, name)
|
||||
|
||||
def test_other_programs_keep_the_real_clock(self):
|
||||
plain = self.run_program(self.other, 0, preload=False)
|
||||
paused = self.run_program(self.other, SHIFT_MS)
|
||||
self.assertAlmostEqual(paused["gap"], plain["gap"], delta=50)
|
||||
for name in ("cond_mono", "clockwait", "sem", "nanosleep", "timerfd", "futex"):
|
||||
self.assertGreaterEqual(paused[name], 50, name)
|
||||
self.assertLess(paused[name], 1000, name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,112 @@
|
||||
import errno
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
SHIM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int close(int fd) {
|
||||
char link[64], path[PATH_MAX];
|
||||
snprintf(link, sizeof link, "/proc/self/fd/%d", fd);
|
||||
ssize_t n = readlink(link, path, sizeof path - 1);
|
||||
path[n > 0 ? n : 0] = 0;
|
||||
long r = syscall(SYS_close, fd);
|
||||
if (r == 0 && n > 4 && !strcmp(path + n - 4, ".eio")) {
|
||||
errno = EIO;
|
||||
return -1;
|
||||
}
|
||||
return (int)r;
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void check(const char *name, const char *path, int flags) {
|
||||
int fd = open(path, flags);
|
||||
if (fd < 0) { printf("%s open-failed\n", name); return; }
|
||||
char b[4];
|
||||
if (read(fd, b, sizeof b) < 0) {}
|
||||
errno = 0;
|
||||
int r = close(fd);
|
||||
int error = r ? errno : 0;
|
||||
int still_open = fcntl(fd, F_GETFD) >= 0;
|
||||
printf("%s %d %d %d\n", name, r, error, still_open);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
check("readonly", argv[1], O_RDONLY);
|
||||
check("readwrite", argv[1], O_RDWR);
|
||||
check("plain", argv[2], O_RDONLY);
|
||||
errno = 0;
|
||||
int r = close(-1);
|
||||
printf("badfd %d %d\n", r, errno == EBADF);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
|
||||
class CloseEioPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp = tempfile.TemporaryDirectory()
|
||||
cls.dir = Path(cls.temp.name)
|
||||
(cls.dir / "shim.c").write_text(SHIM)
|
||||
(cls.dir / "program.c").write_text(PROGRAM)
|
||||
cls.preload = cls.dir / "libblsession.so"
|
||||
cls.shim = cls.dir / "libshim.so"
|
||||
cls.program = cls.dir / "program"
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-DBL_CLOCK_ANY_ARCH",
|
||||
'-DCP_CTL="%s"' % (cls.dir / "clock"), "-o", str(cls.preload),
|
||||
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.shim), str(cls.dir / "shim.c")], check=True)
|
||||
subprocess.run(["cc", "-O2", "-o", str(cls.program), str(cls.dir / "program.c")], check=True)
|
||||
(cls.dir / "data.eio").write_bytes(b"data")
|
||||
(cls.dir / "plain").write_bytes(b"data")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.temp.cleanup()
|
||||
|
||||
def run_program(self, preloads):
|
||||
env = dict(os.environ, LD_PRELOAD=":".join(map(str, preloads)))
|
||||
result = subprocess.run([str(self.program), str(self.dir / "data.eio"), str(self.dir / "plain")],
|
||||
env=env, capture_output=True, text=True, check=True, timeout=30)
|
||||
return {line.split()[0]: line.split()[1:] for line in result.stdout.splitlines()}
|
||||
|
||||
def test_a_flush_error_on_a_read_only_file_is_not_a_close_failure(self):
|
||||
out = self.run_program([self.preload, self.shim])
|
||||
self.assertEqual(["0", "0", "0"], out["readonly"])
|
||||
|
||||
def test_a_flush_error_after_writing_access_is_still_reported(self):
|
||||
out = self.run_program([self.preload, self.shim])
|
||||
self.assertEqual(["-1", str(errno.EIO), "0"], out["readwrite"])
|
||||
|
||||
def test_other_closes_are_unchanged(self):
|
||||
out = self.run_program([self.preload, self.shim])
|
||||
self.assertEqual(["0", "0", "0"], out["plain"])
|
||||
self.assertEqual(["-1", "1"], out["badfd"])
|
||||
|
||||
def test_without_the_session_library_the_error_reaches_the_program(self):
|
||||
out = self.run_program([self.shim])
|
||||
self.assertEqual("-1", out["readonly"][0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -57,6 +57,26 @@ class ComponentPrepareTest(unittest.TestCase):
|
||||
script.write_text(script.read_text() + '\nprintf changed\n')
|
||||
self.assertNotEqual(changed, components.identity('fake', self.root))
|
||||
|
||||
def test_identity_follows_a_submodule_commit(self):
|
||||
library = self.root / 'library'
|
||||
subprocess.run(['git', 'init', '-q', str(library)], check=True)
|
||||
def commit(text):
|
||||
(library / 'source.c').write_text(text)
|
||||
subprocess.run(['git', '-C', str(library), 'add', '.'], check=True)
|
||||
subprocess.run(['git', '-C', str(library), '-c', 'user.name=Test Developer', '-c', 'user.email=test@example.test',
|
||||
'commit', '-qm', text], check=True)
|
||||
return subprocess.check_output(['git', '-C', str(library), 'rev-parse', 'HEAD'], text=True).strip()
|
||||
first = commit('int a;\n')
|
||||
subprocess.run(['git', '-C', str(self.root), 'add', 'library'], check=True)
|
||||
spec = dict(script='tools/components/recipes/fake.sh', inputs=['library'], outputs=[])
|
||||
(self.root / components.REGISTRY).write_text(json.dumps(dict(fake=spec)))
|
||||
original = components.identity('fake', self.root)
|
||||
commit('int b;\n')
|
||||
self.assertEqual(original, components.identity('fake', self.root))
|
||||
subprocess.run(['git', '-C', str(self.root), 'add', 'library'], check=True)
|
||||
self.assertNotEqual(original, components.identity('fake', self.root))
|
||||
self.assertNotEqual(first, subprocess.check_output(['git', '-C', str(library), 'rev-parse', 'HEAD'], text=True).strip())
|
||||
|
||||
def test_tool_requirements_are_installed_in_one_union(self):
|
||||
definitions = dict(one=dict(packages=['gcc', 'cmake']), two=dict(packages=['gcc', 'qemu-user']))
|
||||
with patch.object(components, 'registry', return_value=definitions), patch.object(components.subprocess, 'run') as run:
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class CursorCompositeTest(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')
|
||||
header = (REPO / 'app/src/main/cpp/waylandcomp/src/cardboard.h').read_text()
|
||||
sources = dict(re.findall(r'CARDBOARD_SOURCE_(SCREEN|SBS|FLAT)\s*=\s*(\d+)', header))
|
||||
for name in ('SCREEN', 'SBS', 'FLAT'):
|
||||
if name not in sources:
|
||||
raise AssertionError(f'cardboard.h no longer defines CARDBOARD_SOURCE_{name}')
|
||||
if sources['SBS'] != '1':
|
||||
raise AssertionError(f'CARDBOARD_SOURCE_SBS is {sources["SBS"]}, expected 1')
|
||||
|
||||
source = (REPO / 'app/src/main/cpp/waylandcomp/src/compositor.c').read_text()
|
||||
start = source.index('static int cursor_scene_positions(int scene_w, int source, int ptr_x, int hx, int out[2]) {')
|
||||
end = source.index('\n}\n', start) + 3
|
||||
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-cursor-composite-')
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
folder = Path(cls.temp.name)
|
||||
(folder / 'cursor_scene_positions.inc').write_text(source[start:end])
|
||||
start = source.index('static int cursor_clip_to_eye(int scene_w, int eye, int x0, int w, int *dx, int *sx, int *dw) {')
|
||||
end = source.index('\n}\n', start) + 3
|
||||
(folder / 'cursor_clip_to_eye.inc').write_text(source[start:end])
|
||||
(folder / 'cursor_constants.inc').write_text(
|
||||
f'#define CARDBOARD_SOURCE_SCREEN {sources["SCREEN"]}\n'
|
||||
f'#define CARDBOARD_SOURCE_SBS {sources["SBS"]}\n'
|
||||
f'#define CARDBOARD_SOURCE_FLAT {sources["FLAT"]}\n')
|
||||
cls.binary = folder / 'cursor-composite-test'
|
||||
subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror', '-I', str(folder),
|
||||
str(REPO / 'tools/tests/cursor_composite_harness.c'),
|
||||
'-o', str(cls.binary)], check=True, capture_output=True, text=True)
|
||||
|
||||
def test_cursor_is_drawn_once_for_one_eye_and_mirrored_for_sbs(self):
|
||||
result = subprocess.run([str(self.binary)], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn('PASS: cursor stereo placement', result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -32,6 +32,7 @@ class DesktopGpuWindowTest(unittest.TestCase):
|
||||
def test_on_the_desktop_the_game_gets_a_window_of_its_own(self):
|
||||
run = self.run_gpu(WAYLAND_DISPLAY="wayland-1", MESA_VK_WSI_DEBUG="sw,linear")
|
||||
self.assertEqual(run["args"][:2], ["--backend", "sdl"])
|
||||
self.assertIn("--follow-game-window-mode", run["args"])
|
||||
self.assertNotIn("-f", run["args"])
|
||||
self.assertEqual(run["args"][-2:], ["/usr/local/bin/droiddeck-gpu-window", "game.exe"])
|
||||
self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-1")
|
||||
@@ -44,6 +45,7 @@ class DesktopGpuWindowTest(unittest.TestCase):
|
||||
for env in ({"WAYLAND_DISPLAY": "wayland-1", "BL_DESKTOP_GPU_WINDOW": "0"}, {"WAYLAND_DISPLAY": "wayland-0"}, {}):
|
||||
run = self.run_gpu(**env)
|
||||
self.assertEqual(run["args"][:2], ["--backend", "wayland"])
|
||||
self.assertNotIn("--follow-game-window-mode", run["args"])
|
||||
self.assertIn("-f", run["args"])
|
||||
self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-0")
|
||||
self.assertIsNone(run["env"]["MESA_VK_WSI_DEBUG"])
|
||||
|
||||
@@ -316,7 +316,6 @@ class GameFolderTest(Temp):
|
||||
|
||||
|
||||
def appinfo(apps):
|
||||
"""appinfo.vdf as the client writes it (format 29: keys in a string table)."""
|
||||
strings = []
|
||||
|
||||
def key(name):
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""The guest agent: its request files, exec, errors and the DevTools client, without a session."""
|
||||
import base64
|
||||
import hashlib
|
||||
import importlib.machinery
|
||||
@@ -26,7 +25,6 @@ loader.exec_module(agent)
|
||||
|
||||
|
||||
class FakeDevTools(threading.Thread):
|
||||
"""GET /json lists one target; its WebSocket answers Runtime.evaluate the way Chromium does."""
|
||||
|
||||
def __init__(self, answer):
|
||||
super().__init__(daemon=True)
|
||||
@@ -857,7 +855,6 @@ class VrFocusTest(unittest.TestCase):
|
||||
self.assertEqual(focus.order([42, 9, 7], [7, 42], None), [9, 7])
|
||||
self.assertIsNone(focus.order([9, 7], [7], 42))
|
||||
self.assertEqual(focus.order([9, 7], [7, 42], 42), [42, 9, 7])
|
||||
# Do not overwrite a different focus order installed after our last write.
|
||||
self.assertIsNone(focus.order([123, 7], [7, 42], None))
|
||||
|
||||
def test_scene_requires_live_server_and_game_environment(self):
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""droiddeckctl and droiddeck-scenario against a fake adb: the JSON contract and exit codes."""
|
||||
import base64
|
||||
import contextlib
|
||||
import importlib.machinery
|
||||
@@ -61,6 +60,16 @@ FAKE_ADB = textwrap.dedent('''\
|
||||
print(config.get("timestats", ""))
|
||||
elif args[:2] == ["exec-out", "screencap"]:
|
||||
sys.stdout.buffer.write(b"\\x89PNG fake")
|
||||
elif args[:3] == ["shell", "dumpsys", "battery"]:
|
||||
temperatures = config.get("battery", [""])
|
||||
count = config.setdefault("counts", {}).get("battery", 0)
|
||||
config["counts"]["battery"] = count + 1
|
||||
json.dump(config, open(config_path, "w"))
|
||||
print(temperatures[min(count, len(temperatures) - 1)])
|
||||
elif args[:3] == ["shell", "dumpsys", "thermalservice"]:
|
||||
print(config.get("thermalservice", ""))
|
||||
elif args[:3] == ["shell", "grep", "."]:
|
||||
print(config.get("cpufreq", ""))
|
||||
with open(config["log"], "a") as log:
|
||||
log.write(json.dumps(entry) + "\\n")
|
||||
''')
|
||||
@@ -88,8 +97,6 @@ def timestats_record(name, frames, histogram, hz):
|
||||
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),
|
||||
@@ -99,7 +106,6 @@ TIMESTATS_SPLIT = "SurfaceFlinger TimeStats:\ntotalFrames = 2000\n" + "".join([
|
||||
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),
|
||||
@@ -107,6 +113,25 @@ TIMESTATS_SURFACEVIEW = "SurfaceFlinger TimeStats:\n" + "".join([
|
||||
])
|
||||
|
||||
|
||||
THERMALSERVICE = textwrap.dedent('''\
|
||||
IsStatusOverride: false
|
||||
Thermal Status: 2
|
||||
Cached temperatures:
|
||||
\tTemperature{mValue=41.3, mType=3, mName=skin, mStatus=2}
|
||||
''')
|
||||
|
||||
CPUFREQ = textwrap.dedent('''\
|
||||
/sys/devices/system/cpu/cpufreq/policy0/scaling_max_freq:3532800
|
||||
/sys/devices/system/cpu/cpufreq/policy6/scaling_max_freq:2918400
|
||||
/sys/devices/system/cpu/cpufreq/policy0/cpuinfo_max_freq:3532800
|
||||
/sys/devices/system/cpu/cpufreq/policy6/cpuinfo_max_freq:4473600
|
||||
''')
|
||||
|
||||
|
||||
def battery(tenths):
|
||||
return f"Current Battery Service state:\n level: 80\n temperature: {tenths}\n technology: Li-poly"
|
||||
|
||||
|
||||
def state(phase="READY", focused=None, focusable=()):
|
||||
focus = None if focused is None else {"focusedApp": focused, "focusableApps": list(focusable),
|
||||
"baselayerAppIds": [], "seq": 1, "t": 0}
|
||||
@@ -155,7 +180,7 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
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`
|
||||
with self.assertRaises(variant.ControlError):
|
||||
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])
|
||||
@@ -449,6 +474,40 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
self.assertEqual(7, code)
|
||||
self.assertFalse([c for c in self.calls() if c["args"][:1] == ["push"]])
|
||||
|
||||
def test_thermal_reads_battery_status_and_cpu_caps(self):
|
||||
self.configure({}, battery=[battery(386)], thermalservice=THERMALSERVICE, cpufreq=CPUFREQ)
|
||||
code, out = self.run_ctl("thermal")
|
||||
self.assertEqual(0, code, out)
|
||||
self.assertEqual(38.6, out["batteryC"])
|
||||
self.assertEqual([2, "MODERATE"], [out["status"], out["statusName"]])
|
||||
self.assertEqual({"policy0": {"maxKHz": 3532800, "hardwareMaxKHz": 3532800, "capped": False},
|
||||
"policy6": {"maxKHz": 2918400, "hardwareMaxKHz": 4473600, "capped": True}}, out["cpu"])
|
||||
|
||||
def test_thermal_without_readings_answers_nulls(self):
|
||||
code, out = self.run_ctl("thermal")
|
||||
self.assertEqual(0, code, out)
|
||||
self.assertEqual([None, None, None, {}], [out["batteryC"], out["status"], out["statusName"], out["cpu"]])
|
||||
|
||||
def test_wait_cool_polls_until_the_battery_is_below(self):
|
||||
self.configure({}, battery=[battery(412), battery(395), battery(379)], thermalservice=THERMALSERVICE)
|
||||
with unittest.mock.patch.object(ctl.time, "sleep") as slept:
|
||||
code, out = self.run_ctl("wait", "cool", "--below", "38", "--timeout", "600")
|
||||
self.assertEqual(0, code, out)
|
||||
self.assertEqual(["wait", 37.9], [out["command"], out["batteryC"]])
|
||||
self.assertEqual(2, slept.call_count)
|
||||
|
||||
def test_wait_cool_times_out_with_exit_5(self):
|
||||
self.configure({}, battery=[battery(412)])
|
||||
code, out = self.run_ctl("wait", "cool", "--below", "38", "--timeout", "0")
|
||||
self.assertEqual(5, code)
|
||||
self.assertIn("41.2", out["error"]["message"])
|
||||
|
||||
def test_wait_cool_needs_below_and_a_battery_temperature(self):
|
||||
code, out = self.run_ctl("wait", "cool")
|
||||
self.assertEqual(["INVALID_ARGUMENTS", 2], [out["error"]["code"], code])
|
||||
code, out = self.run_ctl("wait", "cool", "--below", "38")
|
||||
self.assertEqual("THERMAL_FAILED", out["error"]["code"])
|
||||
|
||||
|
||||
class ScenarioTest(FakeAdbTest):
|
||||
def write(self, body):
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-flatpak"
|
||||
|
||||
|
||||
class FakeRef:
|
||||
def __init__(self, arch):
|
||||
self.arch = arch
|
||||
|
||||
def get_name(self):
|
||||
return "io.github.ebkr.r2modman"
|
||||
|
||||
def get_arch(self):
|
||||
return self.arch
|
||||
|
||||
|
||||
def load(bundle_arch, installs):
|
||||
flatpak = types.SimpleNamespace(
|
||||
get_default_arch=lambda: "aarch64",
|
||||
BundleRef=types.SimpleNamespace(new=lambda bundle: FakeRef(bundle_arch)),
|
||||
)
|
||||
repository = types.ModuleType("gi.repository")
|
||||
repository.Flatpak = flatpak
|
||||
repository.Gio = types.SimpleNamespace(File=types.SimpleNamespace(new_for_path=lambda path: path))
|
||||
repository.GLib = types.SimpleNamespace(Error=RuntimeError)
|
||||
gi = types.ModuleType("gi")
|
||||
gi.require_version = lambda *args: None
|
||||
gi.repository = repository
|
||||
saved = {name: sys.modules.get(name) for name in ("gi", "gi.repository")}
|
||||
sys.modules["gi"] = gi
|
||||
sys.modules["gi.repository"] = repository
|
||||
try:
|
||||
loader = importlib.machinery.SourceFileLoader("droiddeck_flatpak", str(SCRIPT))
|
||||
module = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
|
||||
loader.exec_module(module)
|
||||
finally:
|
||||
for name, value in saved.items():
|
||||
if value is None:
|
||||
sys.modules.pop(name, None)
|
||||
else:
|
||||
sys.modules[name] = value
|
||||
module.installation = lambda: object()
|
||||
module.app_ref = lambda inst, app_id: None
|
||||
|
||||
def transaction(inst):
|
||||
installs.append("bundle")
|
||||
raise AssertionError("the bundle reached a transaction")
|
||||
|
||||
module.transaction = transaction
|
||||
return module
|
||||
|
||||
|
||||
class FlatpakBundleArchTest(unittest.TestCase):
|
||||
def run_install(self, arch):
|
||||
installs = []
|
||||
module = load(arch, installs)
|
||||
out = io.StringIO()
|
||||
with redirect_stdout(out):
|
||||
try:
|
||||
rc = module.install_bundle("/tmp/r2modman.flatpak")
|
||||
except AssertionError:
|
||||
rc = None
|
||||
return rc, [json.loads(line) for line in out.getvalue().splitlines()], installs
|
||||
|
||||
def test_a_bundle_for_an_architecture_fex_cannot_run_is_refused_before_installing(self):
|
||||
rc, events, installs = self.run_install("riscv64")
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertEqual(installs, [])
|
||||
self.assertEqual(events[0]["e"], "error")
|
||||
self.assertEqual(events[0]["code"], "arch")
|
||||
self.assertEqual(events[0]["arch"], "riscv64")
|
||||
self.assertEqual(events[0]["id"], "io.github.ebkr.r2modman")
|
||||
|
||||
def test_a_bundle_for_this_device_goes_on_to_install(self):
|
||||
rc, events, installs = self.run_install("aarch64")
|
||||
self.assertEqual(installs, ["bundle"])
|
||||
self.assertEqual(events, [])
|
||||
|
||||
def test_an_x86_64_bundle_goes_on_to_install_for_fex(self):
|
||||
rc, events, installs = self.run_install("x86_64")
|
||||
self.assertEqual(installs, ["bundle"])
|
||||
self.assertEqual(events, [])
|
||||
|
||||
def test_flathub_falls_back_to_the_x86_64_build(self):
|
||||
module = load("aarch64", [])
|
||||
asked = []
|
||||
|
||||
class Remote:
|
||||
def __init__(self, branch):
|
||||
self.branch = branch
|
||||
|
||||
def get_branch(self):
|
||||
return self.branch
|
||||
|
||||
class Installation:
|
||||
def fetch_remote_ref_sync(self, remote, kind, app_id, arch, branch, cancellable):
|
||||
asked.append((arch, branch))
|
||||
if arch == "x86_64" and branch == "stable":
|
||||
return Remote("stable")
|
||||
raise RuntimeError("not found")
|
||||
|
||||
added = []
|
||||
|
||||
class Transaction:
|
||||
def add_install(self, remote, ref, subpaths):
|
||||
added.append(ref)
|
||||
|
||||
module.Flatpak.RefKind = types.SimpleNamespace(APP=0)
|
||||
module.installation = lambda: Installation()
|
||||
installed = []
|
||||
module.app_ref = lambda inst, app_id: (installed[0] if installed else None)
|
||||
module.transaction = lambda inst: (Transaction(), {})
|
||||
|
||||
def run(t, state, report_done=True):
|
||||
installed.append(object())
|
||||
return 0
|
||||
|
||||
module.run = run
|
||||
out = io.StringIO()
|
||||
with redirect_stdout(out):
|
||||
rc = module.install("io.github.ebkr.r2modman")
|
||||
self.assertEqual(rc, 0)
|
||||
self.assertEqual(asked, [("aarch64", "stable"), ("aarch64", "master"), ("x86_64", "stable")])
|
||||
self.assertEqual(added, ["app/io.github.ebkr.r2modman/x86_64/stable"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,199 @@
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-flatpak"
|
||||
|
||||
|
||||
def load():
|
||||
repository = types.ModuleType("gi.repository")
|
||||
repository.Flatpak = types.SimpleNamespace()
|
||||
repository.Gio = types.SimpleNamespace()
|
||||
repository.GLib = types.SimpleNamespace(Error=RuntimeError)
|
||||
gi = types.ModuleType("gi")
|
||||
gi.require_version = lambda *args: None
|
||||
gi.repository = repository
|
||||
saved = {name: sys.modules.get(name) for name in ("gi", "gi.repository")}
|
||||
sys.modules["gi"] = gi
|
||||
sys.modules["gi.repository"] = repository
|
||||
try:
|
||||
loader = importlib.machinery.SourceFileLoader("droiddeck_flatpak_bus", str(SCRIPT))
|
||||
module = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
|
||||
loader.exec_module(module)
|
||||
finally:
|
||||
for name, value in saved.items():
|
||||
if value is None:
|
||||
sys.modules.pop(name, None)
|
||||
else:
|
||||
sys.modules[name] = value
|
||||
return module
|
||||
|
||||
|
||||
class FakeDaemon:
|
||||
started = []
|
||||
|
||||
def __init__(self, argv, **kwargs):
|
||||
conf = next(a for a in argv if a.startswith("--config-file=")).split("=", 1)[1]
|
||||
text = open(conf).read()
|
||||
self.path = text.split("<listen>unix:path=", 1)[1].split("</listen>", 1)[0]
|
||||
self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.server.bind(self.path)
|
||||
self.server.listen(4)
|
||||
self.running = True
|
||||
FakeDaemon.started.append(self)
|
||||
|
||||
def poll(self):
|
||||
return None if self.running else 0
|
||||
|
||||
def terminate(self):
|
||||
self.running = False
|
||||
self.server.close()
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return 0
|
||||
|
||||
def kill(self):
|
||||
self.terminate()
|
||||
|
||||
|
||||
class FlatpakSystemBusTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.module = load()
|
||||
self.tmp = tempfile.mkdtemp()
|
||||
self.env = mock.patch.dict(os.environ, {"DBUS_SYSTEM_BUS_ADDRESS": "unix:path=" + os.path.join(self.tmp, "missing")})
|
||||
self.env.start()
|
||||
FakeDaemon.started = []
|
||||
|
||||
def tearDown(self):
|
||||
self.env.stop()
|
||||
os.rmdir(self.tmp)
|
||||
|
||||
def test_a_reachable_system_bus_is_used_as_it_is(self):
|
||||
path = os.path.join(self.tmp, "system")
|
||||
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
server.bind(path)
|
||||
server.listen(1)
|
||||
try:
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=" + path
|
||||
with mock.patch.object(self.module.subprocess, "Popen", FakeDaemon):
|
||||
self.assertIsNone(self.module.private_system_bus())
|
||||
self.assertEqual([], FakeDaemon.started)
|
||||
finally:
|
||||
server.close()
|
||||
os.unlink(path)
|
||||
|
||||
def test_without_a_system_bus_a_private_one_runs_for_the_command_and_is_removed_after(self):
|
||||
with mock.patch.object(self.module.shutil, "which", return_value="/usr/bin/dbus-daemon"), \
|
||||
mock.patch.object(self.module.subprocess, "Popen", FakeDaemon):
|
||||
bus = self.module.private_system_bus()
|
||||
self.assertIsNotNone(bus)
|
||||
_, work, conf, path = bus
|
||||
self.assertEqual("unix:path=" + path, os.environ["DBUS_SYSTEM_BUS_ADDRESS"])
|
||||
self.assertTrue(self.module.bus_reachable(path))
|
||||
self.module.stop_system_bus(bus)
|
||||
self.assertFalse(os.path.exists(work))
|
||||
|
||||
def test_any_reachable_address_in_a_list_counts_as_the_system_bus(self):
|
||||
path = os.path.join(self.tmp, "system")
|
||||
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
server.bind(path)
|
||||
server.listen(1)
|
||||
try:
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=%s;unix:guid=1,path=%s" % (os.path.join(self.tmp, "missing"), path)
|
||||
with mock.patch.object(self.module.subprocess, "Popen", FakeDaemon):
|
||||
self.assertIsNone(self.module.private_system_bus())
|
||||
self.assertEqual([], FakeDaemon.started)
|
||||
finally:
|
||||
server.close()
|
||||
os.unlink(path)
|
||||
|
||||
def test_escaped_and_abstract_addresses_are_probed_as_dbus_reads_them(self):
|
||||
path = os.path.join(self.tmp, "sys-bus")
|
||||
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
server.bind(path)
|
||||
server.listen(1)
|
||||
abstract = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
abstract.bind(b"\0droiddeck-flatpak-test-%d\xff" % os.getpid())
|
||||
abstract.listen(1)
|
||||
try:
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=" + path.replace("-", "%2D")
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=%s;unix:abstract=droiddeck-flatpak-test-%d%%FF" % (os.path.join(self.tmp, "missing"), os.getpid())
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:abstract=droiddeck-flatpak-missing-%d" % os.getpid()
|
||||
self.assertFalse(self.module.system_bus_reachable())
|
||||
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(8)
|
||||
port = listener.getsockname()[1]
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:abstract=droiddeck-flatpak-missing-%d;tcp:host=127.0.0.1,port=%d" % (os.getpid(), port)
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "tcp:host=127.0.0.1,port=" + "".join("%%%02X" % ord(c) for c in str(port))
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "tcp:host=127.0.0.1,port=000%d" % port
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
listener.close()
|
||||
self.assertFalse(self.module.system_bus_reachable())
|
||||
for bad in ("%C2%B2", "65536", "0", "000", "x", "9" * 5000):
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "tcp:host=127.0.0.1,port=" + bad
|
||||
self.assertEqual([], self.module.system_bus_paths())
|
||||
self.assertFalse(self.module.system_bus_reachable())
|
||||
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "launchd:env=DBUS_LAUNCHD_SESSION_BUS_SOCKET"
|
||||
self.assertTrue(self.module.system_bus_reachable())
|
||||
finally:
|
||||
abstract.close()
|
||||
server.close()
|
||||
os.unlink(path)
|
||||
|
||||
def test_a_daemon_that_cannot_launch_leaves_no_files_and_warns(self):
|
||||
made = []
|
||||
real = tempfile.mkdtemp
|
||||
|
||||
def mkdtemp(**kwargs):
|
||||
made.append(real(**kwargs))
|
||||
return made[-1]
|
||||
|
||||
with mock.patch.object(self.module.shutil, "which", return_value="/usr/bin/dbus-daemon"), \
|
||||
mock.patch.object(self.module.tempfile, "mkdtemp", mkdtemp), \
|
||||
mock.patch.object(self.module.subprocess, "Popen", side_effect=OSError("exec failed")), \
|
||||
mock.patch.object(self.module, "emit") as emit:
|
||||
self.assertIsNone(self.module.private_system_bus())
|
||||
emit.assert_called_once()
|
||||
self.assertFalse(os.path.exists(made[0]))
|
||||
|
||||
def test_without_dbus_daemon_the_command_still_runs_and_warns(self):
|
||||
with mock.patch.object(self.module.shutil, "which", return_value=None), \
|
||||
mock.patch.object(self.module, "emit") as emit:
|
||||
self.assertIsNone(self.module.private_system_bus())
|
||||
emit.assert_called_once()
|
||||
|
||||
def test_every_command_that_changes_apps_gets_a_system_bus(self):
|
||||
calls = []
|
||||
self.module.private_system_bus = lambda: calls.append("start") or "bus"
|
||||
self.module.stop_system_bus = lambda bus: calls.append("stop:%s" % bus)
|
||||
self.module.prepare_rootfs = lambda: None
|
||||
self.module.install = lambda app_id: calls.append("install") or 0
|
||||
self.module.updates = lambda: calls.append("updates") or 0
|
||||
with mock.patch.object(sys, "argv", ["droiddeck-flatpak", "install", "org.example.App"]), \
|
||||
mock.patch.object(self.module.signal, "signal") as handler:
|
||||
self.assertEqual(0, self.module.main())
|
||||
self.assertEqual(["start", "install", "stop:bus"], calls)
|
||||
self.assertEqual(self.module.signal.SIGTERM, handler.call_args[0][0])
|
||||
with self.assertRaises(SystemExit):
|
||||
handler.call_args[0][1](self.module.signal.SIGTERM, None)
|
||||
calls.clear()
|
||||
with mock.patch.object(sys, "argv", ["droiddeck-flatpak", "updates"]):
|
||||
self.assertEqual(0, self.module.main())
|
||||
self.assertNotIn("start", calls)
|
||||
self.assertIn("updates", calls)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,3 @@
|
||||
"""The Quick Access Frame Limit follows the panel when its refresh rate changes."""
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
|
||||
@@ -319,7 +319,7 @@ class FsyncPreloadTest(unittest.TestCase):
|
||||
source = base / "fsync-test.c"
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-fPIC", "-shared", "-pthread", "-o", str(cls.lib),
|
||||
str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), "-ldl"], check=True)
|
||||
str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), str(PRELOAD / "clockpause.c"), "-ldl"], check=True)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-pthread", "-o", str(cls.exe), str(source)], check=True)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -29,6 +29,374 @@ def config_text(entries):
|
||||
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
|
||||
|
||||
|
||||
class RenderPathDefaultsTest(unittest.TestCase):
|
||||
DRIVER = "/drivers/DD-Turnip_v0.4.0/icd.json"
|
||||
COMMAND = ["proton", "waitforexitandrun", "/games/Spintires/SpinTires.exe"]
|
||||
|
||||
def apply(self, env=None, command=None, model="Adreno722", library="libvulkan_freedreno.so"):
|
||||
env = dict({"VK_DRIVER_FILES": self.DRIVER} if env is None else env)
|
||||
manifest = json.dumps({"ICD": {"library_path": library}})
|
||||
with mock.patch.object(Path, "read_text", return_value=model), \
|
||||
mock.patch.object(Path, "is_file", return_value=False), \
|
||||
mock.patch("builtins.open", mock.mock_open(read_data=manifest)):
|
||||
note = MODULE["render_path_defaults"](command or self.COMMAND, env)
|
||||
return env, note
|
||||
|
||||
def test_tested_render_path_keeps_other_options(self):
|
||||
env, note = self.apply({"VK_DRIVER_FILES": self.DRIVER, "DXVK_CONFIG": "d3d9.maxFrameLatency = 2; ", "CUSTOM": "kept"})
|
||||
self.assertEqual(env["DXVK_CONFIG"], "d3d9.maxFrameLatency = 2; dxvk.tilerMode = False")
|
||||
self.assertEqual(env["CUSTOM"], "kept")
|
||||
self.assertIsNotNone(note)
|
||||
self.assertEqual(self.apply()[0]["DXVK_CONFIG"], "dxvk.tilerMode = False")
|
||||
self.assertIsNotNone(self.apply({"VK_ICD_FILENAMES": self.DRIVER})[1])
|
||||
|
||||
def test_other_games_devices_and_drivers_keep_their_environment(self):
|
||||
for changes in (
|
||||
{"command": ["proton", "waitforexitandrun", "/games/MudRunner.exe"]},
|
||||
{"command": ["proton", "run", self.COMMAND[2]]},
|
||||
{"command": ["proton"]},
|
||||
{"model": "Adreno740"},
|
||||
{"model": "Mali-G715"},
|
||||
{"library": "libvulkan.so"},
|
||||
{"env": {}},
|
||||
{"env": {"VK_DRIVER_FILES": "/drivers/new-turnip/icd.json"}},
|
||||
{"env": {"VK_DRIVER_FILES": "", "VK_ICD_FILENAMES": self.DRIVER}},
|
||||
):
|
||||
with self.subTest(changes=changes):
|
||||
env, note = self.apply(**changes)
|
||||
self.assertIsNone(note)
|
||||
self.assertNotIn("DXVK_CONFIG", env)
|
||||
|
||||
def test_explicit_environment_and_config_files_take_precedence(self):
|
||||
for value in ("dxvk.tilerMode = Auto", "d3d9.maxFrameLatency = 1; dxvk.tilerMode=True", "dxvk.tilerMode = False"):
|
||||
env, note = self.apply({"VK_DRIVER_FILES": self.DRIVER, "DXVK_CONFIG": value})
|
||||
self.assertIsNone(note)
|
||||
self.assertEqual(env["DXVK_CONFIG"], value)
|
||||
env, note = self.apply({"VK_DRIVER_FILES": self.DRIVER, "DXVK_CONFIG_FILE": "/games/custom.conf"})
|
||||
self.assertIsNone(note)
|
||||
self.assertNotIn("DXVK_CONFIG", env)
|
||||
with mock.patch.object(Path, "is_file", return_value=True):
|
||||
env = {"VK_DRIVER_FILES": self.DRIVER}
|
||||
self.assertIsNone(MODULE["render_path_defaults"](self.COMMAND, env))
|
||||
self.assertNotIn("DXVK_CONFIG", env)
|
||||
|
||||
def test_unreadable_or_invalid_driver_metadata_leaves_launch_unchanged(self):
|
||||
for data in ("not-json", "{}", '{"ICD":{"library_path":null}}'):
|
||||
with mock.patch.object(Path, "read_text", return_value="Adreno722"), \
|
||||
mock.patch.object(Path, "is_file", return_value=False), \
|
||||
mock.patch("builtins.open", mock.mock_open(read_data=data)):
|
||||
env = {"VK_DRIVER_FILES": self.DRIVER}
|
||||
self.assertIsNone(MODULE["render_path_defaults"](self.COMMAND, env))
|
||||
self.assertNotIn("DXVK_CONFIG", env)
|
||||
with mock.patch.object(Path, "read_text", side_effect=PermissionError), \
|
||||
mock.patch.object(Path, "is_file", return_value=False):
|
||||
self.assertIsNone(MODULE["render_path_defaults"](self.COMMAND, {"VK_DRIVER_FILES": self.DRIVER}))
|
||||
|
||||
|
||||
class DirtTelemetryFixTest(unittest.TestCase):
|
||||
SHOWDOWN_ON = '<x><motion enabled="true" ip="127.0.0.1" port="20777" delay="1" extradata="3" /></x>'
|
||||
SHOWDOWN_DEFAULT = '<x><motion enabled="true" ip="dbox" port="20777" delay="1" extradata="0" /></x>'
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
root = Path(self.tmp.name)
|
||||
self.prefix = root / "compatdata/2848447563"
|
||||
self.proton = root / "Proton/proton"
|
||||
self.own = root / "Proton/files/lib/wine/i386-windows/ws2_32.dll"
|
||||
self.own.parent.mkdir(parents=True)
|
||||
self.own.write_bytes(b"MZ wine ws2_32")
|
||||
self.proton.write_text("")
|
||||
self.target = self.prefix / "pfx/drive_c/windows/syswow64/ws2_32.dll"
|
||||
self.target.parent.mkdir(parents=True)
|
||||
self.target.symlink_to(self.own)
|
||||
self.stand_in = root / "droiddeck-dirt/ws2_32.dll"
|
||||
self.stand_in.parent.mkdir()
|
||||
self.stand_in.write_bytes(b"MZ droiddeck-dirt-ws2_32 stand-in")
|
||||
self.patch = mock.patch.dict(MODULE["dirt_ws2_wanted"].__globals__, {"DIRT_WS2": str(self.stand_in)})
|
||||
self.patch.start()
|
||||
|
||||
def tearDown(self):
|
||||
self.patch.stop()
|
||||
self.tmp.cleanup()
|
||||
|
||||
def config(self, folder, text):
|
||||
path = self.prefix / "pfx/drive_c/users/steamuser/Documents/My Games" / folder / "hardwaresettings/hardware_settings_config.xml"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text)
|
||||
|
||||
def command(self, exe="showdown.exe"):
|
||||
return [str(self.proton), "waitforexitandrun", "/root/Storage/games/DiRT Showdown/" + exe]
|
||||
|
||||
def env(self):
|
||||
return {"STEAM_COMPAT_DATA_PATH": str(self.prefix)}
|
||||
|
||||
def test_telemetry_counts_as_on_when_the_game_sends_somewhere(self):
|
||||
self.config("DiRT Showdown", self.SHOWDOWN_DEFAULT)
|
||||
self.assertFalse(MODULE["dirt_telemetry_on"](self.prefix, "dirtshowdown"))
|
||||
self.config("DiRT Showdown", self.SHOWDOWN_ON)
|
||||
self.assertTrue(MODULE["dirt_telemetry_on"](self.prefix, "dirtshowdown"))
|
||||
self.config("DiRT Showdown", self.SHOWDOWN_ON.replace('enabled="true"', 'enabled="false"'))
|
||||
self.assertFalse(MODULE["dirt_telemetry_on"](self.prefix, "dirtshowdown"))
|
||||
self.config("DiRT3", '<x><motion enabled="true" ip="192.168.1.20" port="20777" /></x>')
|
||||
self.assertTrue(MODULE["dirt_telemetry_on"](self.prefix, "dirt3"))
|
||||
|
||||
def test_stand_in_is_wanted_only_for_the_dirt_games_with_telemetry_on_and_a_proton_without_the_fix(self):
|
||||
wanted = MODULE["dirt_ws2_wanted"]
|
||||
self.config("DiRT Showdown", self.SHOWDOWN_DEFAULT)
|
||||
self.assertIsNone(wanted(self.command(), self.env()))
|
||||
self.config("DiRT Showdown", self.SHOWDOWN_ON)
|
||||
self.assertEqual(wanted(self.command(), self.env()), str(self.prefix))
|
||||
self.assertEqual(wanted(self.command("Showdown_AVX.exe"), self.env()), str(self.prefix))
|
||||
self.assertIsNone(wanted(self.command("DiRTRally2.exe"), self.env()))
|
||||
self.own.write_bytes(b"MZ wine ws2_32 " + "showdown_avx.exe".encode("utf-16-le"))
|
||||
self.assertIsNone(wanted(self.command(), self.env()))
|
||||
|
||||
def test_swap_keeps_the_prefix_link_and_restore_puts_it_back(self):
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
saved = self.target.with_name("ws2_32.dll.droiddeck-original")
|
||||
self.assertFalse(self.target.is_symlink())
|
||||
self.assertEqual(self.target.read_bytes(), self.stand_in.read_bytes())
|
||||
self.assertEqual(os.readlink(saved), str(self.own))
|
||||
self.assertEqual(self.own.read_bytes(), b"MZ wine ws2_32")
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
self.assertEqual(os.readlink(saved), str(self.own))
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, self.proton))
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
self.assertFalse(os.path.lexists(saved))
|
||||
self.assertFalse(MODULE["restore_dirt_ws2"](self.prefix, self.proton))
|
||||
|
||||
def test_restore_keeps_a_file_proton_put_back_meanwhile(self):
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
newer = self.own.with_name("ws2_32-newer.dll")
|
||||
newer.write_bytes(b"MZ newer wine ws2_32")
|
||||
self.target.unlink()
|
||||
self.target.symlink_to(newer)
|
||||
self.assertFalse(MODULE["restore_dirt_ws2"](self.prefix, self.proton))
|
||||
self.assertEqual(os.readlink(self.target), str(newer))
|
||||
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
|
||||
|
||||
def test_after_a_proton_switch_the_running_protons_file_goes_back(self):
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
other = Path(self.tmp.name) / "GE-Proton/proton"
|
||||
other_own = other.parent / "files/lib/wine/i386-windows/ws2_32.dll"
|
||||
other_own.parent.mkdir(parents=True)
|
||||
other_own.write_bytes(b"MZ GE wine ws2_32")
|
||||
other.write_text("")
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, other))
|
||||
self.assertEqual(os.readlink(self.target), str(other_own))
|
||||
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
|
||||
|
||||
def test_restore_follows_a_proton_reached_through_a_linked_folder(self):
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
pack = Path(self.tmp.name) / "pack"
|
||||
(pack / "files/lib/wine").mkdir(parents=True)
|
||||
(pack / "files/lib/wine/i386-windows").symlink_to(self.own.parent)
|
||||
(pack / "proton").write_text("")
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, pack / "proton"))
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
|
||||
def test_a_stand_in_left_without_the_saved_link_is_replaced_by_protons_own_file(self):
|
||||
self.target.unlink()
|
||||
self.target.write_bytes(self.stand_in.read_bytes())
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, self.proton))
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
|
||||
def test_launch_swaps_the_stand_in_in_for_the_game_and_back_afterwards(self):
|
||||
self.config("DiRT Showdown", self.SHOWDOWN_ON)
|
||||
self.proton.write_text("#!" + sys.executable + "\nimport os, sys\n"
|
||||
"target = os.path.join(os.environ['STEAM_COMPAT_DATA_PATH'], 'pfx/drive_c/windows/syswow64/ws2_32.dll')\n"
|
||||
"print(os.environ.get('WINEDLLOVERRIDES', ''))\n"
|
||||
"print(os.path.islink(target), b'droiddeck-dirt-ws2_32' in open(target, 'rb').read())\n")
|
||||
self.proton.chmod(0o755)
|
||||
runner = Path(self.tmp.name) / "run.py"
|
||||
runner.write_text("import runpy, sys\nmain = runpy.run_path(sys.argv[1])['main']\nmain.__globals__['DIRT_WS2'] = sys.argv[2]\n"
|
||||
"sys.argv = [sys.argv[1]] + sys.argv[3:]\nsys.exit(main())\n")
|
||||
home = Path(self.tmp.name) / "home"
|
||||
home.mkdir()
|
||||
result = subprocess.run([sys.executable, str(runner), str(BIN / "droiddeck-game-env"), str(self.stand_in), *self.command()],
|
||||
env={**os.environ, "HOME": str(home), "STEAM_COMPAT_DATA_PATH": str(self.prefix)}, text=True, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
overrides, state = result.stdout.splitlines()[-2:]
|
||||
self.assertIn("ws2_32=n,b", overrides.split(";"))
|
||||
self.assertEqual(state, "False True")
|
||||
self.assertIn("DiRT telemetry fix: ws2_32 stand-in", result.stderr)
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
|
||||
|
||||
def test_a_proton_that_cannot_start_leaves_the_prefix_as_it_was(self):
|
||||
self.config("DiRT Showdown", self.SHOWDOWN_ON)
|
||||
self.proton.write_text("not a program")
|
||||
self.proton.chmod(0o644)
|
||||
runner = Path(self.tmp.name) / "run.py"
|
||||
runner.write_text("import runpy, sys\nmain = runpy.run_path(sys.argv[1])['main']\nmain.__globals__['DIRT_WS2'] = sys.argv[2]\n"
|
||||
"sys.argv = [sys.argv[1]] + sys.argv[3:]\nsys.exit(main())\n")
|
||||
home = Path(self.tmp.name) / "home"
|
||||
home.mkdir()
|
||||
result = subprocess.run([sys.executable, str(runner), str(BIN / "droiddeck-game-env"), str(self.stand_in), *self.command()],
|
||||
env={**os.environ, "HOME": str(home), "STEAM_COMPAT_DATA_PATH": str(self.prefix)}, text=True, capture_output=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("DiRT telemetry fix: ws2_32 stand-in", result.stderr)
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
|
||||
|
||||
def test_launch_with_telemetry_off_leaves_the_prefix_alone(self):
|
||||
self.config("DiRT Showdown", self.SHOWDOWN_DEFAULT)
|
||||
self.proton.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('WINEDLLOVERRIDES', ''))\n")
|
||||
self.proton.chmod(0o755)
|
||||
home = Path(self.tmp.name) / "home"
|
||||
home.mkdir()
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), *self.command()],
|
||||
env={**os.environ, "HOME": str(home), "STEAM_COMPAT_DATA_PATH": str(self.prefix)}, text=True, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertNotIn("ws2_32=n,b", result.stdout)
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
|
||||
def test_a_failed_put_back_does_not_end_the_launch_with_an_error(self):
|
||||
def fail():
|
||||
raise OSError(28, "No space left on device")
|
||||
stderr = io.StringIO()
|
||||
with mock.patch("sys.stderr", stderr):
|
||||
code = MODULE["start"]([sys.executable, "-c", "raise SystemExit(0)"], dict(os.environ), None, fail)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("not put back", stderr.getvalue())
|
||||
|
||||
def test_a_half_done_swap_is_put_back(self):
|
||||
saved = self.target.with_name("ws2_32.dll.droiddeck-original")
|
||||
os.replace(self.target, saved)
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, self.proton))
|
||||
self.assertEqual(os.readlink(self.target), str(self.own))
|
||||
self.assertFalse(os.path.lexists(saved))
|
||||
|
||||
def test_a_native_ws2_32_goes_back_as_it_was_after_a_proton_switch(self):
|
||||
self.target.unlink()
|
||||
self.target.write_bytes(b"MZ a mod's own ws2_32")
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
other = Path(self.tmp.name) / "GE-Proton/proton"
|
||||
(other.parent / "files/lib/wine/i386-windows").mkdir(parents=True)
|
||||
(other.parent / "files/lib/wine/i386-windows/ws2_32.dll").write_bytes(b"MZ GE wine ws2_32")
|
||||
other.write_text("")
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, other))
|
||||
self.assertFalse(self.target.is_symlink())
|
||||
self.assertEqual(self.target.read_bytes(), b"MZ a mod's own ws2_32")
|
||||
|
||||
def test_a_link_to_a_mods_ws2_32_goes_back_as_it_was(self):
|
||||
mod = Path(self.tmp.name) / "mods/ws2_32.dll"
|
||||
mod.parent.mkdir()
|
||||
mod.write_bytes(b"MZ a mod's ws2_32")
|
||||
self.target.unlink()
|
||||
self.target.symlink_to(mod)
|
||||
MODULE["swap_dirt_ws2"](self.prefix)
|
||||
other = Path(self.tmp.name) / "GE-Proton/proton"
|
||||
(other.parent / "files/lib/wine/i386-windows").mkdir(parents=True)
|
||||
(other.parent / "files/lib/wine/i386-windows/ws2_32.dll").write_bytes(b"MZ GE wine ws2_32")
|
||||
other.write_text("")
|
||||
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, other))
|
||||
self.assertEqual(os.readlink(self.target), str(mod))
|
||||
|
||||
def test_start_gives_the_signal_handlers_back(self):
|
||||
import signal
|
||||
before = {s: signal.getsignal(s) for s in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)}
|
||||
MODULE["start"]([sys.executable, "-c", "pass"], dict(os.environ), None, lambda: None)
|
||||
self.assertEqual(before, {s: signal.getsignal(s) for s in before})
|
||||
|
||||
def test_start_puts_the_file_back_after_the_game_exits(self):
|
||||
calls = []
|
||||
code = MODULE["start"]([sys.executable, "-c", "raise SystemExit(3)"], dict(os.environ), None, lambda: calls.append("restored"))
|
||||
self.assertEqual(code, 3)
|
||||
self.assertEqual(calls, ["restored"])
|
||||
with self.assertRaises(OSError):
|
||||
MODULE["start"]([str(Path(self.tmp.name) / "missing")], dict(os.environ), None, lambda: calls.append("again"))
|
||||
self.assertEqual(calls, ["restored"])
|
||||
|
||||
|
||||
class EgoCorePlanTest(unittest.TestCase):
|
||||
|
||||
@staticmethod
|
||||
def rule(op, value, worker_map):
|
||||
return (' <restrict_if name="cores" op="%s" value="%d">\r\n <restrict_add>\r\n'
|
||||
' <threadStrategy parallelUpdateRender="true" workerMapFile="system/%s" updateProcessor="2" />\r\n'
|
||||
' </restrict_add>\r\n </restrict_if>\r\n' % (op, value, worker_map))
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.system = Path(self.tmp.name) / "DiRT 3/system"
|
||||
self.system.mkdir(parents=True)
|
||||
cpu = "".join(self.rule("int_eq", n, "workerMap%dCore.xml" % n) for n in (2, 3, 4, 6)) + self.rule("int_ge", 8, "workerMap8Core.xml")
|
||||
self.shipped = ('<?xml version="1.0" encoding="UTF-8" ?>\r\n<hardware_settings_restrictions>\r\n <cpu>\r\n'
|
||||
' <restrict_info>\r\n' + cpu +
|
||||
' <restrict_else>\r\n <restrict_add>\r\n'
|
||||
' <threadStrategy parallelUpdateRender="false" workerMapFile="system/workerMap.xml" />\r\n'
|
||||
' </restrict_add>\r\n </restrict_else>\r\n </restrict_info>\r\n </cpu>\r\n'
|
||||
' <audio_card>\r\n' + self.rule("int_eq", 5, "audio.xml") + ' </audio_card>\r\n'
|
||||
'</hardware_settings_restrictions>').encode("latin-1")
|
||||
self.path = self.system / "hardware_settings_restrictions.xml"
|
||||
self.path.write_bytes(self.shipped)
|
||||
for name in ("workerMap.xml", "workerMap2Core.xml", "workerMap3Core.xml", "workerMap4Core.xml", "workerMap6Core.xml", "workerMap8Core.xml"):
|
||||
(self.system / name).write_text("<workerMap />")
|
||||
self.command = ["/proton", "waitforexitandrun", str(self.system.parent / "dirt3_game.exe")]
|
||||
self.saved = self.path.with_name(self.path.name + ".droiddeck-original")
|
||||
|
||||
def plan(self, topology, command=None):
|
||||
env = {} if topology is None else {"WINE_CPU_TOPOLOGY": topology}
|
||||
return MODULE["ego_core_plan"](command or self.command, env)
|
||||
|
||||
def test_five_cores_get_a_copy_of_the_four_core_plan(self):
|
||||
note = self.plan("5:7,3,4,5,6")
|
||||
self.assertIn("5 cores", note)
|
||||
self.assertIn("4-core plan", note)
|
||||
text = self.path.read_bytes()
|
||||
four = self.rule("int_eq", 4, "workerMap4Core.xml").encode("latin-1")
|
||||
five = self.rule("int_eq", 5, "workerMap4Core.xml").encode("latin-1")
|
||||
self.assertEqual(text, self.shipped.replace(four, four + five))
|
||||
self.assertNotIn(b"\n", text.replace(b"\r\n", b""))
|
||||
self.assertEqual(self.saved.read_bytes(), self.shipped)
|
||||
self.assertEqual(sorted(p.name for p in self.system.glob("*droiddeck-tmp*")), [])
|
||||
self.assertIsNone(self.plan("5:7,3,4,5,6"))
|
||||
self.assertEqual(self.path.read_bytes(), text)
|
||||
self.assertEqual(self.saved.read_bytes(), self.shipped)
|
||||
|
||||
def test_seven_cores_get_the_six_core_plan(self):
|
||||
self.assertIn("6-core plan", self.plan("7:7,1,2,3,4,5,6"))
|
||||
self.assertIn(b'value="7">\r\n <restrict_add>\r\n <threadStrategy parallelUpdateRender="true" '
|
||||
b'workerMapFile="system/workerMap6Core.xml"', self.path.read_bytes())
|
||||
|
||||
def test_counts_with_a_plan_are_left_alone(self):
|
||||
for topology in ("2:7,6", "4:7,3,4,5", "6:7,3,4,5,6,2", "8:7,2,3,4,5,6,0,1", "12:0,1,2,3,4,5,6,7,8,9,10,11"):
|
||||
self.assertIsNone(self.plan(topology), topology)
|
||||
self.assertEqual(self.path.read_bytes(), self.shipped)
|
||||
self.assertFalse(os.path.lexists(self.saved))
|
||||
|
||||
def test_nothing_changes_without_a_core_count_a_restrictions_file_a_smaller_plan_or_its_worker_map(self):
|
||||
self.assertIsNone(self.plan(None))
|
||||
self.assertIsNone(self.plan(""))
|
||||
self.assertIsNone(self.plan("x:1"))
|
||||
self.assertIsNone(self.plan("\u00b2:7"))
|
||||
self.assertIsNone(self.plan("1:7"))
|
||||
self.assertIsNone(self.plan("5:7,3,4,5,6", ["/proton", "waitforexitandrun"]))
|
||||
self.assertIsNone(self.plan("5:7,3,4,5,6", ["/proton", "waitforexitandrun", "/elsewhere/game.exe"]))
|
||||
(self.system / "workerMap4Core.xml").unlink()
|
||||
self.assertIsNone(self.plan("5:7,3,4,5,6"))
|
||||
self.assertEqual(self.path.read_bytes(), self.shipped)
|
||||
self.assertFalse(os.path.lexists(self.saved))
|
||||
|
||||
def test_an_unknown_comparison_counts_as_a_plan(self):
|
||||
self.path.write_bytes(self.shipped.replace(b'op="int_ge" value="8"', b'op="int_between" value="8"'))
|
||||
self.assertIsNone(self.plan("5:7,3,4,5,6"))
|
||||
|
||||
def test_main_adds_the_plan_before_the_game_starts(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
probe = Path(tmp) / "probe"
|
||||
probe.write_text('#!/bin/sh\ngrep -c \'value="5"\' "%s"\n' % self.path)
|
||||
probe.chmod(0o755)
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith(("WINE", "PROTON", "DROIDDECK", "BL_", "STEAM"))}
|
||||
env.update(HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/3791535942", WINE_CPU_TOPOLOGY="5:7,3,4,5,6")
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun", self.command[2]],
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
self.assertEqual(result.stdout.strip(), "2", result.stderr)
|
||||
self.assertIn("added a copy of its 4-core plan", result.stderr)
|
||||
|
||||
|
||||
class GameDebugLoggingTest(unittest.TestCase):
|
||||
def test_maintenance_precision_survives_run_with_performance_game_settings(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
@@ -155,7 +523,6 @@ class GameDebugLoggingTest(unittest.TestCase):
|
||||
result = launch([str(probe), verb], {**env, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata" / prefix)})
|
||||
self.assertEqual(result["env"]["PROTON_LOG"], "0")
|
||||
self.assertEqual(result["env"]["WINEDEBUG"], "-all")
|
||||
# Non-Steam shortcuts use the same normalized unsigned compatdata identity.
|
||||
result = launch(command, {**env, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/-1")})
|
||||
self.assertEqual(result["env"]["PROTON_LOG"], "1")
|
||||
self.assertFalse((home / "never-created").exists())
|
||||
@@ -194,23 +561,43 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
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.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('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,
|
||||
"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")
|
||||
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_game_profile_directaudio_settings_reach_the_driver(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
probe = home / "probe"
|
||||
probe.write_text("#!" + sys.executable + "\nimport os\nprint(' '.join(sorted(k + '=' + v for k, v in os.environ.items() if k.startswith('BANNER_AUDIO_DIRECT_'))))\n")
|
||||
probe.chmod(0o755)
|
||||
config = home / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(json.dumps({"version": 1, "games": {"42": {"AUDIO_DIRECT_MS": "80"}}}))
|
||||
base = {key: value for key, value in os.environ.items() if "AUDIO_DIRECT_" not in key}
|
||||
base.update(HOME=tmp, BL_MIC_ENABLED="0", STEAM_COMPAT_DATA_PATH="/compatdata/42",
|
||||
AUDIO_DIRECT_MS="60", AUDIO_DIRECT_PERIOD_MS="20", AUDIO_DIRECT_MIC="1",
|
||||
BANNER_AUDIO_DIRECT_MS="60", BANNER_AUDIO_DIRECT_MIC="1")
|
||||
for driver, expected in (("directaudio,pulse", "BANNER_AUDIO_DIRECT_MIC=0 BANNER_AUDIO_DIRECT_MS=80 BANNER_AUDIO_DIRECT_PERIOD_MS=20"),
|
||||
("pulse", "BANNER_AUDIO_DIRECT_MIC=1 BANNER_AUDIO_DIRECT_MS=60")):
|
||||
with self.subTest(driver=driver):
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun"],
|
||||
env=dict(base, WINE_AUDIO_DRIVER=driver), text=True, capture_output=True, check=True)
|
||||
self.assertEqual(result.stdout.strip(), expected)
|
||||
|
||||
def test_desktop_games_restart_on_the_gpu_with_steams_preloads_handed_back(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
@@ -326,6 +713,15 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(evaluate(), (0, 2))
|
||||
self.assertEqual(evaluate("changed"), (0, 3))
|
||||
|
||||
def test_the_mali_bridge_caps_the_vkd3d_feature_level(self):
|
||||
bridge = {"BL_VKBRIDGE": "1", "VKD3D_FEATURE_LEVEL": "12_2"}
|
||||
self.assertIn("capped", MODULE["bridge_feature_level"](bridge))
|
||||
self.assertEqual(bridge["VKD3D_FEATURE_LEVEL"], "12_0")
|
||||
for env in ({"BL_VKBRIDGE": "1", "VKD3D_FEATURE_LEVEL": "11_1"}, {"VKD3D_FEATURE_LEVEL": "12_2"}, {"BL_VKBRIDGE": "1"}):
|
||||
before = dict(env)
|
||||
self.assertIsNone(MODULE["bridge_feature_level"](env))
|
||||
self.assertEqual(env, before)
|
||||
|
||||
def test_profile_precedence_and_unset(self):
|
||||
env = {"KEEP": "inherited", "REMOVE": "inherited", "CUSTOM": "launch option"}
|
||||
config = {"version": 1, "shared": {"CUSTOM": "shared"}, "games": {"42": {"REMOVE": None, "CUSTOM": "game", "EMPTY": ""}}}
|
||||
@@ -432,7 +828,7 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
(game / name).touch()
|
||||
env, extra, notes = MODULE["engine_fixes"](str(game / "Game.exe"), [])
|
||||
self.assertEqual(env["FEX_TSOENABLED"], "1")
|
||||
self.assertEqual(env["FEX_MULTIBLOCK"], "0")
|
||||
self.assertNotIn("FEX_MULTIBLOCK", env)
|
||||
self.assertEqual(env["WINEDLLOVERRIDES"], "libsentry.windows.release.x86_64=d")
|
||||
self.assertEqual(extra, ["--rendering-driver", "vulkan"])
|
||||
self.assertEqual(MODULE["engine_fixes"](str(game / "Game.exe"), ["--rendering-driver", "opengl3"])[1], [])
|
||||
@@ -550,6 +946,38 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
(game / "D3DGear64.DLL").unlink()
|
||||
self.assertEqual(MODULE["engine_fixes"](str(game / "TheCrew2.exe"), []), ({}, [], []))
|
||||
|
||||
def test_doom_2016_keeps_the_swapchain_image_count_it_asks_for(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
game = Path(tmp) / "DOOM (2016)"
|
||||
game.mkdir()
|
||||
for name in ("DOOMx64.exe", "DOOMx64vk.exe", "Galaxy64.dll"):
|
||||
(game / name).touch()
|
||||
images = {
|
||||
"GAMESCOPE_WSI_MIN_IMAGE_COUNT": None,
|
||||
"GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT": None,
|
||||
"vk_x11_strict_image_count": "true",
|
||||
}
|
||||
for exe in ("DOOMx64.exe", "DOOMx64vk.exe"):
|
||||
env, extra, notes = MODULE["engine_fixes"](str(game / exe), [])
|
||||
self.assertEqual((env, extra), (images, []))
|
||||
self.assertTrue(notes)
|
||||
launched = {"GAMESCOPE_WSI_MIN_IMAGE_COUNT": "8", "GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT": "1"}
|
||||
result = MODULE["apply_config"](launched, {"version": 1}, "3566086475", env)
|
||||
self.assertNotIn("GAMESCOPE_WSI_MIN_IMAGE_COUNT", result)
|
||||
self.assertNotIn("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT", result)
|
||||
self.assertEqual(result["vk_x11_strict_image_count"], "true")
|
||||
config = {"version": 1, "games": {"3566086475": {"GAMESCOPE_WSI_MIN_IMAGE_COUNT": "3"}}}
|
||||
self.assertEqual(MODULE["apply_config"](launched, config, "3566086475", env)["GAMESCOPE_WSI_MIN_IMAGE_COUNT"], "3")
|
||||
eternal = Path(tmp) / "DOOMEternal"
|
||||
eternal.mkdir()
|
||||
(eternal / "DOOMEternalx64vk.exe").touch()
|
||||
self.assertEqual(MODULE["engine_fixes"](str(eternal / "DOOMEternalx64vk.exe"), []), ({}, [], []))
|
||||
other = Path(tmp) / "Other"
|
||||
other.mkdir()
|
||||
for name in ("Other.exe", "DOOMx64vk.exe"):
|
||||
(other / name).touch()
|
||||
self.assertEqual(MODULE["engine_fixes"](str(other / "Other.exe"), []), ({}, [], []))
|
||||
|
||||
def test_dll_overrides_from_several_fixes_are_all_kept(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for name in ("Game.exe", "Game.pck", "GodotSharp.dll", "libsentry.windows.release.x86_64.dll", "d3dgear64.dll"):
|
||||
@@ -564,6 +992,12 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertTrue(notes)
|
||||
self.assertEqual(MODULE["engine_fixes"]("/game/Game/DarkSoulsII.exe", []), ({}, [], []))
|
||||
|
||||
def test_little_nightmares_keeps_its_render_thread(self):
|
||||
env, extra, notes = MODULE["engine_fixes"]("/game/Little Nightmares/Atlas/Binaries/Win64/LittleNightmares.exe", [])
|
||||
self.assertEqual((env, extra), ({"PROTONFIXES_DISABLE": "1"}, []))
|
||||
self.assertTrue(notes)
|
||||
self.assertEqual(MODULE["engine_fixes"]("/game/Little Nightmares II/Moonlight/Binaries/Win64/LittleNightmaresII.exe", []), ({}, [], []))
|
||||
|
||||
def test_game_cores_are_parsed_from_lists_and_ranges(self):
|
||||
parse = MODULE["parse_cores"]
|
||||
self.assertEqual(parse("0-3,6"), {0, 1, 2, 3, 6})
|
||||
@@ -1497,11 +1931,11 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
(self.windows / folder).mkdir(parents=True)
|
||||
self.reg = self.compat / "pfx/user.reg"
|
||||
|
||||
def run_setup(self, verb="waitforexitandrun", target="game.exe", cwd=None):
|
||||
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nverb=$2\nbl_directaudio "$1" "$3"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\n'
|
||||
def run_setup(self, verb="waitforexitandrun", target="game.exe", cwd=None, extra=None):
|
||||
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nverb=$2\nbl_directaudio "$1" "$3"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\nenv | grep "^BANNER_AUDIO_DIRECT_" | sort\n'
|
||||
steam = self.compat.parent / "Steam"
|
||||
env = dict(os.environ, BL_DIRECTAUDIO=str(self.sets), STEAM_COMPAT_DATA_PATH=str(self.compat),
|
||||
STEAM_COMPAT_CLIENT_INSTALL_PATH=str(steam))
|
||||
STEAM_COMPAT_CLIENT_INSTALL_PATH=str(steam), **(extra or {}))
|
||||
env.pop("WINEDLLPATH", None)
|
||||
env.pop("WINE_AUDIO_DRIVER", None)
|
||||
return subprocess.run(["bash", "-c", script, "bash", str(self.tool), verb, target], cwd=cwd, env=env,
|
||||
@@ -1549,6 +1983,21 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
self.assertIn("DirectAudio selected", result.stderr)
|
||||
self.assertEqual(self.link("system32"), str(self.audio / "lib/wine/aarch64-windows/winedirectaudio.drv"))
|
||||
self.assertEqual(self.audio_values(), [("[Software\\\\Wine\\\\Drivers]", '"Audio"="directaudio,pulse"')])
|
||||
def test_audio_direct_settings_reach_the_driver_under_its_own_names(self):
|
||||
self.reg.write_text("WINE REGISTRY Version 2\n\n#arch=win64\n")
|
||||
result = self.run_setup(extra={"AUDIO_DIRECT_MS": "60", "AUDIO_DIRECT_PERIOD_MS": "20",
|
||||
"AUDIO_DIRECT_RELAY": "/run/relay.sock", "OTHER_AUDIO_DIRECT_MS": "5"})
|
||||
lines = [line for line in result.stdout.splitlines() if line.startswith("BANNER_")]
|
||||
self.assertEqual(lines, ["BANNER_AUDIO_DIRECT_MS=60", "BANNER_AUDIO_DIRECT_PERIOD_MS=20",
|
||||
"BANNER_AUDIO_DIRECT_RELAY=/run/relay.sock"])
|
||||
|
||||
def test_audio_direct_settings_are_not_handed_on_when_directaudio_stays_off(self):
|
||||
legacycompat = self.compat.parent / "Steam/legacycompat"
|
||||
legacycompat.mkdir(parents=True)
|
||||
(legacycompat / "iscriptevaluator.exe").write_bytes(b"Steam install-script evaluator")
|
||||
result = self.run_setup(target="iscriptevaluator.exe", cwd=legacycompat, extra={"AUDIO_DIRECT_MS": "60"})
|
||||
self.assertNotIn("BANNER_AUDIO_DIRECT_MS", result.stdout)
|
||||
|
||||
def test_non_launch_verbs_preserve_audio_configuration(self):
|
||||
for verb in ("getcompatpath", "getnativepath", "destroyprefix"):
|
||||
with self.subTest(verb=verb):
|
||||
@@ -1650,6 +2099,51 @@ class DirectAudioPrefixTest(unittest.TestCase):
|
||||
self.assertIsNone(self.link("system32"))
|
||||
|
||||
|
||||
class ProjectZomboidJvmTest(unittest.TestCase):
|
||||
ARGS = ["-Djava.awt.headless=true", "-Xmx3072m", "-XX:+UseZGC", "-XX:-CreateCoredumpOnCrash"]
|
||||
|
||||
def launch(self, tmp, args=None, stem="ProjectZomboid64"):
|
||||
settings = Path(tmp) / (stem + ".json")
|
||||
settings.write_text(json.dumps({"mainClass": "zombie/gameStates/MainScreenState", "vmArgs": args or self.ARGS}))
|
||||
command = ["proton", "waitforexitandrun", str(Path(tmp) / (stem + ".exe"))]
|
||||
return settings, command
|
||||
|
||||
def test_zgc_becomes_g1_and_the_c1_jit_flag_is_added_once(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
settings, command = self.launch(tmp)
|
||||
MODULE["project_zomboid_jvm"](command)
|
||||
data = json.loads(settings.read_text())
|
||||
self.assertEqual(data["vmArgs"], ["-Djava.awt.headless=true", "-Xmx3072m", "-XX:-CreateCoredumpOnCrash",
|
||||
"-XX:+UseG1GC", "-XX:TieredStopAtLevel=1"])
|
||||
self.assertEqual(data["mainClass"], "zombie/gameStates/MainScreenState")
|
||||
before = settings.read_text()
|
||||
MODULE["project_zomboid_jvm"](command)
|
||||
self.assertEqual(settings.read_text(), before)
|
||||
|
||||
def test_other_collectors_and_windows_specific_lists_are_rewritten(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
settings, command = self.launch(tmp)
|
||||
settings.write_text(json.dumps({"vmArgs": ["-XX:+UseParallelGC", "-Xmx1g"],
|
||||
"windows": {"10.0.17134": {"vmArgs": ["-XX:+UseZGC", "-XX:+UseG1GC"]}}}))
|
||||
MODULE["project_zomboid_jvm"](command)
|
||||
data = json.loads(settings.read_text())
|
||||
flags = ["-XX:+UseG1GC", "-XX:TieredStopAtLevel=1"]
|
||||
self.assertEqual(data["vmArgs"], ["-Xmx1g"] + flags)
|
||||
self.assertEqual(data["windows"]["10.0.17134"]["vmArgs"], flags)
|
||||
|
||||
def test_other_games_and_unreadable_files_are_left_alone(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
settings, command = self.launch(tmp, stem="Other")
|
||||
before = settings.read_text()
|
||||
MODULE["project_zomboid_jvm"](command)
|
||||
self.assertEqual(settings.read_text(), before)
|
||||
settings.write_text("{")
|
||||
MODULE["project_zomboid_jvm"](command[:2] + [str(Path(tmp) / "Other.exe")])
|
||||
(Path(tmp) / "ProjectZomboid64.json").write_text("{")
|
||||
MODULE["project_zomboid_jvm"](command[:2] + [str(Path(tmp) / "ProjectZomboid64.exe")])
|
||||
self.assertEqual((Path(tmp) / "ProjectZomboid64.json").read_text(), "{")
|
||||
|
||||
|
||||
class UbisoftOverlayTest(unittest.TestCase):
|
||||
SETTINGS = (
|
||||
"language:\n code: en-US\n"
|
||||
|
||||
@@ -106,9 +106,6 @@ def main():
|
||||
surface = alloc()
|
||||
send(comp, 0, U(surface))
|
||||
if not args.unassigned_control:
|
||||
# wlroots 0.20.2 assigns the cursor role before forwarding this serial
|
||||
# to Gamescope, so zero avoids needing pointer focus but still tests the
|
||||
# role guard in xwayland_surface_commit.
|
||||
send(pointer, 0, U(0, surface, 0, 0))
|
||||
roundtrip()
|
||||
before = count()
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PATCH = ROOT / "tools/gamescope/patches/0126-topmost-focus-outranks-other-process-override.patch"
|
||||
|
||||
|
||||
def patched_rule():
|
||||
added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
text = "\n".join(added)
|
||||
start = text.index("static bool is_stacked_below_focus")
|
||||
return text[start:text.index("\n}\n", start) + 3]
|
||||
|
||||
|
||||
PREAMBLE = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
static constexpr uint32_t WS_EX_TOPMOST = 0x00000008u;
|
||||
static constexpr uint32_t WS_EX_TOOLWINDOW = 0x00000080u;
|
||||
static constexpr uint32_t WS_EX_LAYERED = 0x00080000u;
|
||||
|
||||
enum class steamcompmgr_win_type_t { XWAYLAND, XDG };
|
||||
struct xwayland_t { unsigned long id = 0; unsigned long transientFor = 0; };
|
||||
struct steamcompmgr_win_t {
|
||||
int pid = 0;
|
||||
bool hasHwndStyleEx = false;
|
||||
uint32_t hwndStyleEx = 0;
|
||||
steamcompmgr_win_type_t type = steamcompmgr_win_type_t::XWAYLAND;
|
||||
xwayland_t x;
|
||||
xwayland_t &xwayland() { return x; }
|
||||
};
|
||||
|
||||
static steamcompmgr_win_t win(int pid, unsigned long id, uint32_t exstyle) {
|
||||
steamcompmgr_win_t w;
|
||||
w.pid = pid;
|
||||
w.x.id = id;
|
||||
w.hasHwndStyleEx = true;
|
||||
w.hwndStyleEx = exstyle;
|
||||
return w;
|
||||
}
|
||||
'''
|
||||
|
||||
MAIN = r'''
|
||||
int main() {
|
||||
steamcompmgr_win_t signin = win(4407, 0x2c00008, WS_EX_TOPMOST);
|
||||
steamcompmgr_win_t splash = win(4055, 0x1c00005, WS_EX_LAYERED | WS_EX_TOOLWINDOW);
|
||||
assert(is_stacked_below_focus(&splash, &signin));
|
||||
|
||||
steamcompmgr_win_t dropdown = win(4407, 0x2c00010, WS_EX_TOOLWINDOW);
|
||||
assert(!is_stacked_below_focus(&dropdown, &signin));
|
||||
|
||||
steamcompmgr_win_t menu = win(5120, 0x3000004, WS_EX_TOPMOST | WS_EX_TOOLWINDOW);
|
||||
assert(!is_stacked_below_focus(&menu, &signin));
|
||||
|
||||
steamcompmgr_win_t game = win(4407, 0x2c00008, 0);
|
||||
assert(!is_stacked_below_focus(&splash, &game));
|
||||
|
||||
steamcompmgr_win_t owned = win(4055, 0x1c00007, 0);
|
||||
owned.x.transientFor = signin.x.id;
|
||||
assert(!is_stacked_below_focus(&owned, &signin));
|
||||
|
||||
steamcompmgr_win_t unknown = win(4055, 0x1c00009, 0);
|
||||
unknown.hasHwndStyleEx = false;
|
||||
assert(!is_stacked_below_focus(&unknown, &signin));
|
||||
|
||||
steamcompmgr_win_t no_pid = win(-1, 0x1c0000b, WS_EX_LAYERED | WS_EX_TOOLWINDOW);
|
||||
assert(!is_stacked_below_focus(&no_pid, &signin));
|
||||
steamcompmgr_win_t signin_no_pid = win(-1, 0x2c00008, WS_EX_TOPMOST);
|
||||
assert(!is_stacked_below_focus(&splash, &signin_no_pid));
|
||||
|
||||
puts("ok");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("c++"), "needs a C++ compiler")
|
||||
class OverrideStackingTest(unittest.TestCase):
|
||||
def test_a_topmost_focus_keeps_other_process_windows_beneath_it(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
source = Path(tmp) / "stacking.cpp"
|
||||
binary = Path(tmp) / "stacking"
|
||||
source.write_text(PREAMBLE + patched_rule() + MAIN)
|
||||
subprocess.run(["c++", "-std=c++17", "-Wall", "-Werror", str(source), "-o", str(binary)], check=True)
|
||||
self.assertEqual(subprocess.run([str(binary)], capture_output=True, text=True, check=True).stdout.strip(), "ok")
|
||||
|
||||
def test_map_win_reads_the_wine_extended_style(self):
|
||||
hunks = PATCH.read_text().split("\n@@ ")
|
||||
map_win = next(hunk for hunk in hunks if "map_win(" in hunk.split("\n", 1)[0])
|
||||
added = [line[1:].strip() for line in map_win.splitlines() if line.startswith("+")]
|
||||
self.assertIn("w->hwndStyleEx = get_prop(ctx, w->xwayland().id, ctx->atoms.wineHwndStyleEx, 0, &w->hasHwndStyleEx);", added)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -14,7 +14,7 @@ READER = ROOT / "app/src/main/cpp/waylandcomp/src/hudframes.c"
|
||||
def patch_writer():
|
||||
added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")]
|
||||
text = "\n".join(added)
|
||||
start = text.index("// DroidDeck's own HUD reads")
|
||||
start = text.index("static constexpr uint32_t k_uDroidDeckHudFramesMagic")
|
||||
end = text.index("\n}\n", text.index("static void publish_droiddeck_hud_info()", start)) + 3
|
||||
return text[start:end]
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Exercise the HUD's kgsl memstore busy sampling and counter layout (app/src/main/cpp/gpuclock)."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class KgslBusyTest(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')
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-kgsl-busy-')
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
cls.binary = Path(cls.temp.name) / 'kgsl-busy-test'
|
||||
subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror',
|
||||
'-I', str(REPO / 'app/src/main/cpp/gpuclock'),
|
||||
str(REPO / 'tools/tests/kgsl_busy_harness.c'), '-o', str(cls.binary)],
|
||||
check=True, capture_output=True, text=True)
|
||||
|
||||
def test_ringbuffer_slots_and_busy_rule(self):
|
||||
result = subprocess.run([str(self.binary)], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn('PASS: kgsl memstore busy', result.stdout)
|
||||
self.assertIn('PASS: kgsl memstore contexts', result.stdout)
|
||||
self.assertIn('PASS: kgsl counter layout', result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,151 @@
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "../quest/kgsl_compat.h"
|
||||
|
||||
void bl_kgsl_track(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
|
||||
void *arg, int *rc);
|
||||
|
||||
static int read_error, wait_error, waits;
|
||||
static unsigned int retired;
|
||||
|
||||
static int mock(int fd, unsigned long request, void *arg) {
|
||||
assert(fd == 42 || fd == 43);
|
||||
if (request == IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID) {
|
||||
if (read_error) {
|
||||
errno = read_error;
|
||||
return -1;
|
||||
}
|
||||
((struct kgsl_cmdstream_readtimestamp_ctxtid *)arg)->timestamp = retired;
|
||||
return 0;
|
||||
}
|
||||
assert(request == IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID);
|
||||
struct kgsl_device_waittimestamp_ctxtid *wait = arg;
|
||||
assert(wait->context_id == 3 && wait->timeout != 0);
|
||||
waits++;
|
||||
if (wait_error) {
|
||||
errno = wait_error;
|
||||
return -1;
|
||||
}
|
||||
if (wait->timestamp > retired) {
|
||||
errno = ETIMEDOUT;
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int issue(unsigned long request, void *arg) {
|
||||
int rc = mock(42, request, arg);
|
||||
bl_kgsl_track(mock, 42, request, arg, &rc);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static void submit(unsigned int timestamp) {
|
||||
struct kgsl_gpu_command command = {.context_id = 3, .timestamp = timestamp};
|
||||
int rc = 0;
|
||||
bl_kgsl_track(mock, 42, IOCTL_KGSL_GPU_COMMAND, &command, &rc);
|
||||
assert(rc == 0);
|
||||
}
|
||||
|
||||
static int read_timestamp(unsigned int context, unsigned int *timestamp) {
|
||||
struct kgsl_cmdstream_readtimestamp_ctxtid read = {
|
||||
.context_id = context, .type = KGSL_TIMESTAMP_RETIRED};
|
||||
int rc = issue(IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID, &read);
|
||||
*timestamp = read.timestamp;
|
||||
return rc;
|
||||
}
|
||||
|
||||
static void create_context(unsigned int context) {
|
||||
struct kgsl_drawctxt_create create = {.drawctxt_id = context};
|
||||
int rc = 0;
|
||||
bl_kgsl_track(mock, 42, IOCTL_KGSL_DRAWCTXT_CREATE, &create, &rc);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
unsigned int timestamp;
|
||||
|
||||
retired = 5;
|
||||
assert(read_timestamp(3, ×tamp) == 0 && timestamp == 5 && waits == 0);
|
||||
|
||||
read_error = EACCES;
|
||||
retired = 0;
|
||||
errno = EACCES;
|
||||
assert(read_timestamp(3, ×tamp) == -1 && errno == EACCES && waits == 0);
|
||||
|
||||
create_context(3);
|
||||
assert(read_timestamp(3, ×tamp) == 0 && timestamp == 0 && waits == 1);
|
||||
|
||||
wait_error = EINVAL;
|
||||
assert(read_timestamp(3, ×tamp) == -1 && errno == EINVAL);
|
||||
wait_error = 0;
|
||||
|
||||
waits = 0;
|
||||
read_error = EBADF;
|
||||
assert(read_timestamp(3, ×tamp) == -1 && errno == EBADF && waits == 0);
|
||||
read_error = EACCES;
|
||||
|
||||
struct kgsl_cmdstream_readtimestamp_ctxtid other = {.context_id = 3, .type = KGSL_TIMESTAMP_RETIRED};
|
||||
int other_rc = mock(43, IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID, &other);
|
||||
bl_kgsl_track(mock, 43, IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID, &other, &other_rc);
|
||||
assert(other_rc == -1 && errno == EACCES && waits == 0);
|
||||
|
||||
submit(1);
|
||||
submit(2);
|
||||
submit(3);
|
||||
assert(read_timestamp(3, ×tamp) == 0 && timestamp == 0 && waits == 1);
|
||||
|
||||
retired = 2;
|
||||
waits = 0;
|
||||
assert(read_timestamp(3, ×tamp) == 0 && timestamp == 2 && waits == 3);
|
||||
|
||||
waits = 0;
|
||||
assert(read_timestamp(3, ×tamp) == 0 && timestamp == 2 && waits == 1);
|
||||
|
||||
retired = 3;
|
||||
waits = 0;
|
||||
assert(read_timestamp(3, ×tamp) == 0 && timestamp == 3 && waits == 1);
|
||||
|
||||
waits = 0;
|
||||
assert(read_timestamp(3, ×tamp) == 0 && timestamp == 3 && waits == 1);
|
||||
|
||||
wait_error = EINVAL;
|
||||
assert(read_timestamp(3, ×tamp) == -1 && errno == EINVAL);
|
||||
wait_error = 0;
|
||||
|
||||
submit(4);
|
||||
retired = 4;
|
||||
wait_error = EDEADLK;
|
||||
assert(read_timestamp(3, ×tamp) == -1 && errno == EDEADLK);
|
||||
wait_error = 0;
|
||||
|
||||
struct kgsl_gpu_aux_command aux = {.context_id = 3, .timestamp = 6};
|
||||
int rc = 0;
|
||||
bl_kgsl_track(mock, 42, IOCTL_KGSL_GPU_AUX_COMMAND, &aux, &rc);
|
||||
retired = 6;
|
||||
assert(read_timestamp(3, ×tamp) == 0 && timestamp == 6);
|
||||
|
||||
submit(8);
|
||||
submit(7);
|
||||
retired = 8;
|
||||
assert(read_timestamp(3, ×tamp) == 0 && timestamp == 8);
|
||||
|
||||
create_context(3);
|
||||
retired = 0;
|
||||
waits = 0;
|
||||
assert(read_timestamp(3, ×tamp) == 0 && timestamp == 0 && waits == 1);
|
||||
|
||||
struct kgsl_drawctxt_destroy destroy = {.drawctxt_id = 3};
|
||||
bl_kgsl_track(mock, 42, IOCTL_KGSL_DRAWCTXT_DESTROY, &destroy, &rc);
|
||||
assert(read_timestamp(3, ×tamp) == -1 && errno == EACCES);
|
||||
|
||||
struct kgsl_drawctxt_create user = {.flags = KGSL_CONTEXT_USER_GENERATED_TS, .drawctxt_id = 3};
|
||||
bl_kgsl_track(mock, 42, IOCTL_KGSL_DRAWCTXT_CREATE, &user, &rc);
|
||||
waits = 0;
|
||||
assert(read_timestamp(3, ×tamp) == -1 && errno == EACCES && waits == 0);
|
||||
|
||||
errno = EACCES;
|
||||
assert(read_timestamp(5000, ×tamp) == -1 && errno == EACCES);
|
||||
|
||||
puts("PASS: refused timestamp reads answered from retired waits");
|
||||
}
|
||||
@@ -19,7 +19,6 @@ ALL = set(range(8))
|
||||
|
||||
|
||||
class FakeCores:
|
||||
"""Per-thread masks and priorities, with every change recorded."""
|
||||
|
||||
def __init__(self):
|
||||
self.state = {}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Real login1 sleep handshakes; run with dbus-run-session and python3-gi."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
@@ -10,7 +10,6 @@ COMPONENTS = runpy.run_path(str(BIN / "droiddeck-wincomponents"))
|
||||
|
||||
|
||||
class FakePackage:
|
||||
"""A package's tables in memory, as msiinfo would give them."""
|
||||
|
||||
def __init__(self, tables, summary=None):
|
||||
self.path = "fake.msi"
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
"""NetworkManager contract and real D-Bus handovers (requires python3-gi and dbus).
|
||||
|
||||
Run on Linux: dbus-run-session -- python3 -m unittest discover -s tools/tests -p test_netmanager.py
|
||||
"""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
|
||||
@@ -43,7 +43,7 @@ class NoexecPreloadTest(unittest.TestCase):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
cls.lib = cls.tmp / "libnoexec.so"
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-DNOEXEC_TEST", "-o", str(cls.lib),
|
||||
str(PRELOAD / "noexec.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "writewatch.c"), "-ldl"], check=True)
|
||||
str(PRELOAD / "noexec.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), str(PRELOAD / "writewatch.c"), str(PRELOAD / "clockpause.c"), "-ldl"], check=True)
|
||||
source = cls.tmp / "program.c"
|
||||
source.write_text(PROGRAM)
|
||||
for name in ("FEX", "game"):
|
||||
|
||||
@@ -9,8 +9,6 @@ import unittest
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
FASTPATH = Path(__file__).resolve().parents[1] / "proot/fastpath/fastpath.c"
|
||||
|
||||
# Opens each "<dirfd>\t<flags>\t<path>" case with openat2(RESOLVE_IN_ROOT) as FEX does: first through the kernel's own
|
||||
# openat2 on argv[1] when it has one, then, with openat2 failing ENOSYS as under proot, through the preload on argv[2].
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
@@ -225,7 +223,6 @@ int main(int argc, char **argv) {
|
||||
|
||||
O_PATH = getattr(os, "O_PATH", 0o10000000)
|
||||
|
||||
# (dirfd: r = the tree, o = "/"), flags, path, expected: a path in the tree, an errno name, or "proc" for a file outside it.
|
||||
CASES = [
|
||||
("r", os.O_RDONLY, "etc/alternatives/hn", "etc/hostname"),
|
||||
("r", os.O_RDONLY, "/lib64/x86_64-linux-gnu/libfoo.so.1", "usr/lib/x86_64-linux-gnu/libfoo.so.1.2"),
|
||||
@@ -256,7 +253,6 @@ CASES = [
|
||||
("o", os.O_RDONLY, "proc/self/status", "proc"),
|
||||
]
|
||||
|
||||
# Only the preload: an absolute link to a path missing in the tree but present outside it, as droiddeck-fex's rootfs has.
|
||||
HOST_CASES = [
|
||||
("r", os.O_RDONLY, "lib/x86_64-linux-gnu/libbar.so.2", "host:libbar.so.2"),
|
||||
("r", os.O_RDONLY, "hostdir/sub/data", "host:sub/data"),
|
||||
@@ -312,7 +308,7 @@ class Openat2PreloadTest(unittest.TestCase):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
cls.lib = cls.tmp / "libopenat2.so"
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o", str(cls.lib),
|
||||
str(PRELOAD / "robust.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), "-ldl"], check=True)
|
||||
str(PRELOAD / "robust.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "noexec.c"), str(PRELOAD / "writewatch.c"), str(PRELOAD / "clockpause.c"), "-ldl"], check=True)
|
||||
source = cls.tmp / "openat2.c"
|
||||
source.write_text(PROGRAM)
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "openat2"), str(source), "-ldl"], check=True)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Test the renderer's actual map and inverse map without a Vulkan device."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Exercise the compositor's real button dispatcher with a recording Wayland sink."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
@@ -30,7 +30,6 @@ class PreloadSnapshotTest(unittest.TestCase):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.root = Path(directory.name)
|
||||
# Real repository inputs exercise the transitive include walker and build recipe.
|
||||
for group in snapshots.INPUTS:
|
||||
for name in snapshots.source_files(group):
|
||||
if name.startswith('@'):
|
||||
|
||||
@@ -17,6 +17,16 @@ class QuestKgslTest(unittest.TestCase):
|
||||
str(QUEST / 'test_kgsl_compat.c'), str(QUEST / 'kgsl_compat.c')], check=True)
|
||||
result = subprocess.run([binary], capture_output=True, text=True, check=True, timeout=10)
|
||||
self.assertIn('PASS: 12 GPUOBJ', result.stdout)
|
||||
self.assertIn('PASS: denied timestamp reads', result.stdout)
|
||||
|
||||
def test_refused_timestamp_read_is_answered_from_waits(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
binary = str(Path(folder) / 'test-kgsl-read')
|
||||
subprocess.run(['gcc', '-Wall', '-Wextra', '-Werror', '-O2', '-o', binary,
|
||||
str(QUEST.parent / 'tests/test_kgsl_read.c'),
|
||||
str(QUEST.parent / 'linuxfs/preload/kgslpoll.c')], check=True)
|
||||
result = subprocess.run([binary], capture_output=True, text=True, check=True, timeout=10)
|
||||
self.assertIn('PASS: refused timestamp reads', result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -10,8 +10,6 @@ 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)
|
||||
|
||||
@@ -32,6 +32,8 @@ static int64_t g_hold_missed_ns;
|
||||
static int64_t g_refresh_ns = 16666667;
|
||||
volatile int g_render_on_commit = 1;
|
||||
volatile int g_release_unpaced = 1;
|
||||
volatile int g_fps_limit;
|
||||
static int64_t g_scene_due_ns;
|
||||
static atomic_int g_stream_on;
|
||||
static struct { unsigned ticks, ticks_late_2ms, commit_renders; int64_t tick_late_ns, tick_late_max_ns; } g_pace;
|
||||
static struct { unsigned ticks; } g_perf;
|
||||
@@ -204,7 +206,7 @@ class RenderOnCommitTest(unittest.TestCase):
|
||||
render = extract_function(source, 'render_scene')
|
||||
self.assertIn('g_rendered_tick_ns = g_tick_vsync_ns;', render)
|
||||
self.assertIn('g_tick_held = 0;', render)
|
||||
functions = ('commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', 'on_vsync')
|
||||
functions = ('scene_held_for_limit', 'commit_renders_on', 'render_on_commit', 'schedule_render', 'scene_waits_for_game', 'on_commit_idle', 'on_vsync')
|
||||
harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS
|
||||
with tempfile.TemporaryDirectory(prefix='droiddeck-render-on-commit-') as folder:
|
||||
path = Path(folder)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Exercise the Windows launcher without building an APK or contacting a phone."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
@@ -88,6 +88,19 @@ class RuntimeInputsTest(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'sources changed'):
|
||||
runtime.verify(self.root)
|
||||
|
||||
def test_dev_loop_can_reuse_assets_from_other_sources(self):
|
||||
runtime.record(self.root)
|
||||
self.source.write_text('new implementation')
|
||||
with mock.patch('sys.stderr', new_callable=io.StringIO) as stderr:
|
||||
runtime.verify(self.root, stale_sources_ok=True)
|
||||
self.assertIn('tools/linuxfs/preload/test.c', stderr.getvalue())
|
||||
|
||||
def test_dev_loop_still_rejects_changed_outputs(self):
|
||||
runtime.record(self.root)
|
||||
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary')
|
||||
with self.assertRaisesRegex(ValueError, 'changed runtime input'):
|
||||
runtime.verify(self.root, stale_sources_ok=True)
|
||||
|
||||
def test_changed_quest_source_rejects_old_outputs(self):
|
||||
source = self.root / 'tools/quest/kgsl_compat.c'
|
||||
source.parent.mkdir(parents=True)
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SOURCE = ROOT / 'app/src/main/cpp/waylandcomp/src/compositor.c'
|
||||
|
||||
|
||||
def extract_function(source, name):
|
||||
match = re.search(r'^static int(?:64_t)? ' + re.escape(name) + r'\([^;]*?\) \{', source, re.MULTILINE)
|
||||
if match is None:
|
||||
raise AssertionError(f'Missing compositor function: {name}')
|
||||
cursor, depth = match.end(), 1
|
||||
while depth:
|
||||
depth += (source[cursor] == '{') - (source[cursor] == '}')
|
||||
cursor += 1
|
||||
return source[match.start():cursor]
|
||||
|
||||
|
||||
HARNESS = r'''
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
@FUNCTIONS@
|
||||
|
||||
#define MS 1000000LL
|
||||
|
||||
static int run(int64_t refresh, int limit, int64_t jitter, int seconds) {
|
||||
int renders = 0;
|
||||
int64_t due = 0;
|
||||
for (int64_t tick = 0; tick * refresh < seconds * 1000 * MS; tick++) {
|
||||
int64_t now = 1000 * MS + tick * refresh + (tick % 2 ? jitter : -jitter);
|
||||
if (scene_held_for_limit(now, due, limit, 0)) continue;
|
||||
renders++;
|
||||
due = scene_next_due(now, due, limit);
|
||||
}
|
||||
return renders;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
assert(!scene_held_for_limit(100 * MS, 0, 30, 0));
|
||||
assert(!scene_held_for_limit(100 * MS, 130 * MS, 0, 0));
|
||||
assert(!scene_held_for_limit(100 * MS, 130 * MS, 30, 1));
|
||||
assert(scene_held_for_limit(100 * MS, 130 * MS, 30, 0));
|
||||
assert(scene_held_for_limit(100 * MS, 102 * MS, 30, 0));
|
||||
assert(!scene_held_for_limit(100 * MS, 101 * MS, 30, 0));
|
||||
assert(!scene_held_for_limit(100 * MS, 90 * MS, 30, 0));
|
||||
assert(scene_next_due(100 * MS, 0, 0) == 0);
|
||||
assert(scene_next_due(100 * MS, 0, 25) == 140 * MS);
|
||||
assert(scene_next_due(101 * MS, 100 * MS, 25) == 140 * MS);
|
||||
assert(scene_next_due(200 * MS, 100 * MS, 25) == 240 * MS);
|
||||
const struct { int64_t refresh; int limit; int expected; } cases[] = {
|
||||
{8333333, 30, 300}, {8333333, 60, 600}, {16666667, 25, 250}, {16666667, 30, 300},
|
||||
{10000000, 30, 300}, {11111111, 30, 300}, {6944444, 40, 400}, {16666667, 120, 600},
|
||||
};
|
||||
for (unsigned i = 0; i < sizeof cases / sizeof cases[0]; i++) {
|
||||
int got = run(cases[i].refresh, cases[i].limit, 0, 10);
|
||||
if (got > cases[i].expected + 1 || got < cases[i].expected - 2) {
|
||||
fprintf(stderr, "refresh %lld limit %d: %d renders, expected %d\n",
|
||||
(long long)cases[i].refresh, cases[i].limit, got, cases[i].expected);
|
||||
return 1;
|
||||
}
|
||||
got = run(cases[i].refresh, cases[i].limit, 300000, 10);
|
||||
if (got > cases[i].expected + 1 || got < cases[i].expected - 2) {
|
||||
fprintf(stderr, "jittered refresh %lld limit %d: %d renders, expected %d\n",
|
||||
(long long)cases[i].refresh, cases[i].limit, got, cases[i].expected);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
int fallback = run(8 * MS, 30, 0, 10);
|
||||
assert(fallback <= 301 && fallback >= 290);
|
||||
puts("PASS");
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class SceneLimitHoldTest(unittest.TestCase):
|
||||
def test_a_frame_limit_holds_scene_renders_to_its_rate_without_slowing_paced_frames(self):
|
||||
compiler = shutil.which(os.environ.get('CC', 'cc'))
|
||||
if compiler is None:
|
||||
self.skipTest('A host C compiler is required')
|
||||
source = SOURCE.read_text()
|
||||
harness = HARNESS.replace('@FUNCTIONS@', '\n'.join(extract_function(source, name) for name in ('scene_held_for_limit', 'scene_next_due')))
|
||||
with tempfile.TemporaryDirectory(prefix='droiddeck-scene-hold-') as folder:
|
||||
path = Path(folder)
|
||||
(path / 'hold.c').write_text(harness)
|
||||
binary = path / 'hold-test'
|
||||
build = subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror', '-O2',
|
||||
str(path / 'hold.c'), '-o', str(binary)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(0, build.returncode, build.stderr)
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertEqual('PASS', result.stdout.strip())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -64,6 +64,31 @@ UBISOFT_SCRIPT = r'''"installscript"
|
||||
}
|
||||
'''
|
||||
|
||||
EA_SCRIPT = r'''"installscript"
|
||||
{
|
||||
"Run Process"
|
||||
{
|
||||
"EADesktopSetup"
|
||||
{
|
||||
"process 1" "%INSTALLDIR%\\__Installer\\Origin\\redist\\internal\\EAappInstaller.exe"
|
||||
"command 1" "EAX_LAUNCH_CLIENT=0 IGNORE_INSTALLED=1"
|
||||
"HasRunStringKey" "HKEY_LOCAL_MACHINE\\SOFTWARE\\Electronic Arts\\EA Desktop\\InstallSuccessful"
|
||||
"HasRunStringValue" "true"
|
||||
"RunType" "1"
|
||||
}
|
||||
"Windows6.1-KB2670838-x64.msu"
|
||||
{
|
||||
"process 1" "%INSTALLDIR%\\__Installer\\customcomponent\\patch_KB2670838_x64\\Windows6.1-KB2670838-x64.msu"
|
||||
"command 1" "/quiet"
|
||||
"Requirement_OS"
|
||||
{
|
||||
"OSType" "Windows 7"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class SeedRedistsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -373,14 +398,17 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
self.assertEqual(self.reg.read_text().count('"Vulkan111080"'), 2)
|
||||
|
||||
|
||||
def ubisoft(self):
|
||||
script = self.tmp / "legacycompat/evaluatorscript_447040.vdf"
|
||||
def evaluator(self, appid, install_script):
|
||||
script = self.tmp / ("legacycompat/evaluatorscript_%s.vdf" % appid)
|
||||
script.parent.mkdir(parents=True)
|
||||
script.write_text('"evaluatorscript"\n{\n\t"appid"\t\t"447040"\n\t"1"\n'
|
||||
+ "\n".join("\t" + line for line in UBISOFT_SCRIPT.splitlines()) + "\n}\n")
|
||||
script.write_text('"evaluatorscript"\n{\n\t"appid"\t\t"%s"\n\t"1"\n' % appid
|
||||
+ "\n".join("\t" + line for line in install_script.splitlines()) + "\n}\n")
|
||||
env = dict(os.environ, DROIDDECK_LIBRARIES="", DROIDDECK_SEED_SCRIPTS=str(script))
|
||||
return subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
|
||||
|
||||
def ubisoft(self):
|
||||
return self.evaluator("447040", UBISOFT_SCRIPT)
|
||||
|
||||
def test_the_ubisoft_connect_installer_is_left_to_run(self):
|
||||
self.ubisoft()
|
||||
self.assertIn('"easyanticheat"=dword:00000001', self.user.read_text())
|
||||
@@ -399,7 +427,28 @@ class SeedRedistsTest(unittest.TestCase):
|
||||
result = self.ubisoft()
|
||||
self.assertNotIn("Ubisoft Connect PC Client", self.reg.read_text())
|
||||
self.assertNotIn("Ubisoft Connect PC Client", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
self.assertIn("Ubisoft Connect markers out", result.stdout)
|
||||
self.assertIn("Ubisoft Connect and EA app markers out", result.stdout)
|
||||
|
||||
def test_the_ea_app_installer_is_left_to_run(self):
|
||||
self.evaluator("1238080", EA_SCRIPT)
|
||||
reg = self.reg.read_text()
|
||||
self.assertNotIn("EADesktopSetup", reg)
|
||||
self.assertEqual(reg.count('"Windows6.1-KB2670838-x64.msu"=dword:00000001'), 2)
|
||||
self.assertNotIn("EADesktopSetup", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
|
||||
def test_an_ea_app_marker_an_earlier_seeding_wrote_comes_out(self):
|
||||
marker = "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\1238080\tEADesktopSetup"
|
||||
self.reg.write_text(
|
||||
"WINE REGISTRY Version 2\n"
|
||||
"\n[Software\\\\Valve\\\\Steam\\\\Apps\\\\1238080] 1793680524\n"
|
||||
'"EADesktopSetup"=dword:00000001\n'
|
||||
"\n[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\1238080] 1793680524\n"
|
||||
'"EADesktopSetup"=dword:00000001\n')
|
||||
(self.reg.parent / ".droiddeck-redists").write_text(marker + "\n")
|
||||
result = self.evaluator("1238080", EA_SCRIPT)
|
||||
self.assertNotIn("EADesktopSetup", self.reg.read_text())
|
||||
self.assertNotIn("EADesktopSetup", (self.reg.parent / ".droiddeck-redists").read_text())
|
||||
self.assertIn("EA app markers out", result.stdout)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Gamescope composites the cursor only when a Steam session asks for it."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
"""Exercise the literal launch prefix from SessionService without an Android runtime.
|
||||
|
||||
This is a focused source/exec regression check, not a Kotlin or PRoot integration
|
||||
test. PRoot executes the first guest argument directly; KEY=VALUE is meaningful
|
||||
only after /usr/bin/env. Read the production prefix rather than duplicate it.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Steam owns game caps; the nested compositor follows the output refresh rate."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
|
||||
def wait_functions():
|
||||
text = SESSION.read_text()
|
||||
found = []
|
||||
for name in ("bl_now_ms", "vkbridge_wait_socket"):
|
||||
match = re.search(r"^%s\(\) \{\n.*?^\}\n" % name, text, re.M | re.S)
|
||||
if match:
|
||||
found.append(match.group(0))
|
||||
return found
|
||||
|
||||
|
||||
class VkBridgeSocketWaitTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.root = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.root, True)
|
||||
self.sock = self.root / "vkbridge" / "server.sock"
|
||||
self.sock.parent.mkdir()
|
||||
self.listeners = []
|
||||
self.addCleanup(lambda: [s.close() for s in self.listeners])
|
||||
|
||||
def listen(self):
|
||||
listener = socket.socket(socket.AF_UNIX)
|
||||
listener.bind(str(self.sock))
|
||||
listener.listen(1)
|
||||
self.listeners.append(listener)
|
||||
|
||||
def listen_after(self, seconds):
|
||||
timer = threading.Timer(seconds, self.listen)
|
||||
timer.start()
|
||||
self.addCleanup(timer.cancel)
|
||||
|
||||
def run_wait(self, limit_ms, prelude=""):
|
||||
functions = wait_functions()
|
||||
self.assertEqual(2, len(functions), "droiddeck-session lacks bl_now_ms() or vkbridge_wait_socket()")
|
||||
script = "set -u\n" + "".join(functions) + prelude
|
||||
script += 'if vkbridge_wait_socket "$1" "$2"; then echo USABLE; else echo FALLBACK; fi\n'
|
||||
started = time.monotonic()
|
||||
out = subprocess.run(["bash", "-c", script, "session", str(self.sock), str(limit_ms)],
|
||||
capture_output=True, text=True, timeout=30, check=True).stdout
|
||||
return out, time.monotonic() - started
|
||||
|
||||
def waited_ms(self, out):
|
||||
match = re.search(r"waited (\d+) ms|after (\d+) ms", out)
|
||||
self.assertIsNotNone(match, out)
|
||||
return int(match.group(1) or match.group(2))
|
||||
|
||||
def test_a_socket_already_listening_is_used_at_once(self):
|
||||
self.listen()
|
||||
out, elapsed = self.run_wait(10000)
|
||||
self.assertTrue(out.endswith("USABLE\n"), out)
|
||||
self.assertIn("== vkbridge: server socket ready (waited 0 ms)", out)
|
||||
self.assertLess(elapsed, 2)
|
||||
|
||||
def test_a_server_still_probing_is_waited_for(self):
|
||||
self.listen_after(0.4)
|
||||
out, elapsed = self.run_wait(10000)
|
||||
self.assertTrue(out.endswith("USABLE\n"), out)
|
||||
self.assertIn("== vkbridge: server socket ready (waited ", out)
|
||||
waited = self.waited_ms(out)
|
||||
self.assertGreaterEqual(waited, 300, out)
|
||||
self.assertLess(waited, 5000, out)
|
||||
self.assertLess(elapsed, 6)
|
||||
|
||||
def test_no_server_falls_back_after_the_limit(self):
|
||||
out, elapsed = self.run_wait(300)
|
||||
self.assertTrue(out.endswith("FALLBACK\n"), out)
|
||||
self.assertIn("== vkbridge: no server socket after ", out)
|
||||
self.assertIn("(gave up at 300 ms)", out)
|
||||
self.assertGreaterEqual(self.waited_ms(out), 300)
|
||||
self.assertLess(elapsed, 5)
|
||||
|
||||
def test_a_plain_file_is_not_a_socket(self):
|
||||
self.sock.write_text("stale")
|
||||
out, _ = self.run_wait(200)
|
||||
self.assertTrue(out.endswith("FALLBACK\n"), out)
|
||||
|
||||
def test_a_stopping_session_does_not_wait(self):
|
||||
out, elapsed = self.run_wait(10000, prelude="bl_stopping=1\n")
|
||||
self.assertTrue(out.endswith("FALLBACK\n"), out)
|
||||
self.assertIn("the session is stopping", out)
|
||||
self.assertLess(elapsed, 2)
|
||||
|
||||
def test_no_socket_path_is_a_fallback_without_waiting(self):
|
||||
functions = "".join(wait_functions())
|
||||
out = subprocess.run(["bash", "-c", "set -u\n" + functions +
|
||||
'if vkbridge_wait_socket "" 10000; then echo USABLE; else echo FALLBACK; fi\n'],
|
||||
capture_output=True, text=True, timeout=10, check=True).stdout
|
||||
self.assertEqual("FALLBACK\n", out)
|
||||
|
||||
|
||||
class VkBridgeSessionCheckTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.text = SESSION.read_text()
|
||||
match = re.search(r'^if \[ "\$\{BL_VKBRIDGE:-0\}" = 1 \]; then\n.*?^fi\n', self.text, re.M | re.S)
|
||||
self.assertIsNotNone(match)
|
||||
self.block = match.group(0)
|
||||
|
||||
def test_the_first_pass_waits_before_the_usability_check(self):
|
||||
wait = self.block.index("vkbridge_wait_socket")
|
||||
check = self.block.index('[ -S "${VKBRIDGE_SOCKET:-}" ]')
|
||||
self.assertLess(wait, check)
|
||||
self.assertIn('[ -z "${BL_INSIDE:-}" ] && vkbridge_wait_socket', self.block)
|
||||
|
||||
def test_the_fallback_message_names_what_is_missing(self):
|
||||
self.assertIn("Mali bridge requested but NOT usable", self.block)
|
||||
self.assertIn("missing:$bl_vkb_missing", self.block)
|
||||
|
||||
def test_a_stop_ends_the_wait(self):
|
||||
self.assertRegex(self.text, r"trap '[^']*bl_stopping=1[^']*' TERM INT HUP")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,48 @@
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
KEYS = ("BL_VKBRIDGE_WEBHELPER_ARGS", "BL_VKBRIDGE_CEF_ANGLE", "BL_VKBRIDGE_CEF_VULKAN")
|
||||
|
||||
|
||||
def layout_function():
|
||||
match = re.search(r"^bl_webhelper_layout\(\) \{\n.*?^\}\n", SESSION.read_text(), re.M | re.S)
|
||||
return match.group(0) if match else None
|
||||
|
||||
|
||||
class WebhelperLayoutTest(unittest.TestCase):
|
||||
def layout(self, **settings):
|
||||
function = layout_function()
|
||||
self.assertIsNotNone(function, "droiddeck-session lacks bl_webhelper_layout()")
|
||||
env = {k: v for k, v in os.environ.items() if k not in KEYS}
|
||||
env.update(settings)
|
||||
return subprocess.run(["bash", "-c", "set -u\n" + function + "bl_webhelper_layout\n"], env=env,
|
||||
capture_output=True, text=True, check=True).stdout.strip()
|
||||
|
||||
def test_unset_keeps_steams_own_layout(self):
|
||||
self.assertEqual(self.layout(), "stock")
|
||||
|
||||
def test_angle_on_vulkan_brings_chromiums_vulkan_compositing(self):
|
||||
self.assertEqual(self.layout(BL_VKBRIDGE_CEF_ANGLE="vulkan"),
|
||||
"--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
|
||||
|
||||
def test_vulkan_compositing_can_be_left_off(self):
|
||||
self.assertEqual(self.layout(BL_VKBRIDGE_CEF_ANGLE="vulkan", BL_VKBRIDGE_CEF_VULKAN="0"),
|
||||
"--use-gl=angle --use-angle=vulkan")
|
||||
|
||||
def test_other_angle_backends_get_only_the_angle_switches(self):
|
||||
self.assertEqual(self.layout(BL_VKBRIDGE_CEF_ANGLE="gl"), "--use-gl=angle --use-angle=gl")
|
||||
|
||||
def test_explicit_layout_wins(self):
|
||||
self.assertEqual(self.layout(BL_VKBRIDGE_CEF_ANGLE="vulkan", BL_VKBRIDGE_WEBHELPER_ARGS="--x +Y"),
|
||||
"--x +Y")
|
||||
|
||||
def test_the_steam_block_uses_it(self):
|
||||
self.assertIn("BL_WEBHELPER_ARGS=$(bl_webhelper_layout)", SESSION.read_text())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -9,8 +9,6 @@ PACKAGE = 'com.droiddeck.launcher'
|
||||
|
||||
class SignApkRenamesTest(unittest.TestCase):
|
||||
def test_variants_rename_every_authority_and_task_named_after_the_package(self):
|
||||
# sign-apk.sh renames a fixed list of names for the pubg/antutu/ludashi variants and fails the
|
||||
# main build on any authority or task affinity it leaves on the base package; PR builds do not sign.
|
||||
manifest = (ROOT / 'app/src/main/AndroidManifest.xml').read_text()
|
||||
names = set()
|
||||
for attribute in ('authorities', 'taskAffinity'):
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Retry a dropped shortcut without duplicating a launch that is still preparing its first window."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
@@ -29,7 +28,6 @@ class SteamColdLaunchTest(unittest.TestCase):
|
||||
self.agent_count = self.root / "agent-count"
|
||||
self.focus_count = self.root / "focus-count"
|
||||
|
||||
# FOCUS lists the focused app per xprop call; the last value repeats.
|
||||
xprop = self.bin / "xprop"
|
||||
xprop.write_text(
|
||||
"#!/bin/sh\n"
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import random
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
|
||||
|
||||
|
||||
def config_text(entries):
|
||||
return ('"Before" { "9" { "name" "outside" } } '
|
||||
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
|
||||
'"CompatToolMapping" { ' + entries +
|
||||
' } "After" { "9" { "name" "outside" } } } } } }')
|
||||
|
||||
|
||||
class CountedTokens(list):
|
||||
def __init__(self, tokens):
|
||||
super().__init__(tokens)
|
||||
self.visited = 0
|
||||
|
||||
def __getitem__(self, key):
|
||||
self.visited += len(range(*key.indices(len(self)))) if isinstance(key, slice) else 1
|
||||
return super().__getitem__(key)
|
||||
|
||||
|
||||
class MappingBatchTest(unittest.TestCase):
|
||||
def assert_batch(self, entries, changes):
|
||||
original = COMPAT["tokenize"](config_text(entries))
|
||||
mapping = COMPAT["mapping_block"](original)
|
||||
expected, actual = list(original), list(original)
|
||||
for app, tool in changes.items():
|
||||
COMPAT["set_mapping"](expected, mapping, app, tool)
|
||||
COMPAT["set_mappings"](actual, mapping, changes)
|
||||
self.assertEqual(actual, expected)
|
||||
self.assertEqual(COMPAT["serialize"](actual), COMPAT["serialize"](expected))
|
||||
return actual, mapping
|
||||
|
||||
def test_existing_fields_and_default_priority_are_preserved(self):
|
||||
entries = ('"0" { "name" "old" "priority" "123" "config" "custom" } '
|
||||
'"1" { "name" "old" "priority" "17" "extra" { "keep" "yes" } }')
|
||||
actual, _ = self.assert_batch(entries, {"0": "New Default", "1": "New Game"})
|
||||
expected = entries.replace('"old"', '"New Default"', 1).replace('"old"', '"New Game"', 1)
|
||||
self.assertEqual(actual, COMPAT["tokenize"](config_text(expected)))
|
||||
|
||||
def test_missing_names_are_inserted_without_replacing_other_fields(self):
|
||||
entries = '"1" { "config" "custom" "priority" "17" } "2" { "NAME" "kept" }'
|
||||
actual, _ = self.assert_batch(entries, {"1": "new", "2": ""})
|
||||
expected = ('"1" { "name" "new" "config" "custom" "priority" "17" } '
|
||||
'"2" { "name" "" "NAME" "kept" }')
|
||||
self.assertEqual(actual, COMPAT["tokenize"](config_text(expected)))
|
||||
|
||||
def test_new_entries_keep_reverse_insertion_order_and_priorities(self):
|
||||
actual, mapping = self.assert_batch('"1" { "name" "old" }',
|
||||
{"4": "four", "0": "default", "9": "nine", "8": None, "1": "one"})
|
||||
expected = COMPAT["tokenize"](
|
||||
'"9" { "name" "nine" "config" "" "priority" "250" } '
|
||||
'"0" { "name" "default" "config" "" "priority" "75" } '
|
||||
'"4" { "name" "four" "config" "" "priority" "250" }')
|
||||
self.assertEqual(actual[mapping + 1:mapping + 1 + len(expected)], expected)
|
||||
|
||||
def test_deletion_and_absent_deletion_preserve_neighbor_sections(self):
|
||||
entries = '"layout" "keep" "1" { "name" "old" } "2" { "name" "kept" }'
|
||||
actual, _ = self.assert_batch(entries, {"1": None, "9": None})
|
||||
self.assertEqual(actual, COMPAT["tokenize"](config_text('"layout" "keep" "2" { "name" "kept" }')))
|
||||
|
||||
def test_duplicate_app_entries_change_only_the_first_match(self):
|
||||
entries = '"1" { "name" "first" } "1" { "name" "second" } "2" { "name" "other" }'
|
||||
for tool in (None, "new"):
|
||||
with self.subTest(tool=tool):
|
||||
actual, _ = self.assert_batch(entries, {"1": tool, "2": "updated"})
|
||||
first = '' if tool is None else '"1" { "name" "new" } '
|
||||
expected = first + '"1" { "name" "second" } "2" { "name" "updated" }'
|
||||
self.assertEqual(actual, COMPAT["tokenize"](config_text(expected)))
|
||||
|
||||
def test_nested_and_duplicate_name_fields_keep_first_match_semantics(self):
|
||||
entries = ('"1" { "extra" { "name" "nested" } "name" "outer" } '
|
||||
'"2" { "name" "first" "name" "second" }')
|
||||
actual, _ = self.assert_batch(entries, {"1": "new", "2": "new"})
|
||||
expected = entries.replace('"nested"', '"new"').replace('"first"', '"new"')
|
||||
self.assertEqual(actual, COMPAT["tokenize"](config_text(expected)))
|
||||
|
||||
def test_case_aliases_and_quoted_aliases_keep_sequential_semantics(self):
|
||||
for entries, changes in (
|
||||
('"App" { "name" "first" } "app" { "name" "second" }', {"App": None, "app": "new"}),
|
||||
('', {"App": "first", "app": "second"}),
|
||||
('', {0: "first", "0": "second"})):
|
||||
with self.subTest(entries=entries, changes=changes):
|
||||
self.assert_batch(entries, changes)
|
||||
|
||||
def test_an_empty_batch_does_not_read_or_mutate_tokens(self):
|
||||
tokens = CountedTokens(COMPAT["tokenize"](config_text('"1" { "name" "old" }')))
|
||||
mapping = COMPAT["mapping_block"](tokens)
|
||||
tokens.visited = 0
|
||||
before = list(tokens)
|
||||
COMPAT["set_mappings"](tokens, mapping, {})
|
||||
self.assertEqual(tokens, before)
|
||||
self.assertEqual(tokens.visited, 0)
|
||||
|
||||
def test_non_string_keys_keep_the_single_writers_error_behavior(self):
|
||||
for changes in ({1: "new", "2": "new"}, {"2": "new", 1: "new"}):
|
||||
with self.subTest(changes=changes):
|
||||
tokens = COMPAT["tokenize"](config_text('"1" { "name" "old" } "2" { "name" "old" }'))
|
||||
mapping = COMPAT["mapping_block"](tokens)
|
||||
expected, actual = list(tokens), list(tokens)
|
||||
with self.assertRaises(AttributeError):
|
||||
for app, tool in changes.items():
|
||||
COMPAT["set_mapping"](expected, mapping, app, tool)
|
||||
with self.assertRaises(AttributeError):
|
||||
COMPAT["set_mappings"](actual, mapping, changes)
|
||||
self.assertEqual(actual, expected)
|
||||
|
||||
def test_single_changes_use_the_existing_writer(self):
|
||||
globals_ = COMPAT["set_mappings"].__globals__
|
||||
for changes in ({"1": "new"}, {"1": None}, {"2": "new"}):
|
||||
with self.subTest(changes=changes):
|
||||
tokens = COMPAT["tokenize"](config_text('"1" { "name" "old" }'))
|
||||
mapping = COMPAT["mapping_block"](tokens)
|
||||
with mock.patch.dict(globals_, set_mapping=mock.Mock(wraps=COMPAT["set_mapping"])):
|
||||
COMPAT["set_mappings"](tokens, mapping, changes)
|
||||
globals_["set_mapping"].assert_called_once_with(tokens, mapping, *next(iter(changes.items())))
|
||||
|
||||
def test_bulk_work_is_linear_for_updates_insertions_and_deletions(self):
|
||||
for count in (128, 512):
|
||||
for kind in ("update", "insert", "delete", "missing-name"):
|
||||
with self.subTest(count=count, kind=kind):
|
||||
field = '"config" "kept"' if kind == "missing-name" else '"name" "old"'
|
||||
entries = "".join('"%s" { %s }' % (app, field) for app in range(count))
|
||||
tokens = CountedTokens(COMPAT["tokenize"](config_text(entries)))
|
||||
mapping = COMPAT["mapping_block"](tokens)
|
||||
start = count if kind == "insert" else 0
|
||||
changes = {str(app): None if kind == "delete" else "new" for app in range(start, start + count)}
|
||||
tokens.visited = 0
|
||||
size = len(tokens)
|
||||
COMPAT["set_mappings"](tokens, mapping, changes)
|
||||
self.assertLessEqual(tokens.visited, 8 * size + 8 * count)
|
||||
|
||||
def test_a_batch_stops_after_its_last_matching_entry(self):
|
||||
entries = "".join('"%s" { "name" "old" }' % app for app in range(512))
|
||||
tokens = CountedTokens(COMPAT["tokenize"](config_text(entries)))
|
||||
mapping = COMPAT["mapping_block"](tokens)
|
||||
tokens.visited = 0
|
||||
COMPAT["set_mappings"](tokens, mapping, {"0": "new", "1": "new"})
|
||||
self.assertLess(tokens.visited, 100)
|
||||
|
||||
def test_mixed_batches_match_the_single_writer(self):
|
||||
random_ = random.Random(1748)
|
||||
fields = (
|
||||
'"name" "old" "config" "" "priority" "250"',
|
||||
'"priority" "17"',
|
||||
'"name" "" "name" "second"',
|
||||
'"extra" { "name" "nested" } "name" "outer"',
|
||||
'"NAME" "keep" "extra" { "1" { "name" "nested" } }',
|
||||
'',
|
||||
r'"name" "old" "config" "quoted \"value\" and \\path"',
|
||||
)
|
||||
for case in range(512):
|
||||
entries = '"layout" "keep" ' + "".join(
|
||||
'"%s" { %s }' % (random_.randrange(8), random_.choice(fields))
|
||||
for _ in range(random_.randrange(12)))
|
||||
apps = random_.sample(range(12), random_.randrange(13))
|
||||
changes = {str(app): random_.choice((None, "", "New Tool", r"new\\tool")) for app in apps}
|
||||
with self.subTest(case=case):
|
||||
self.assert_batch(entries, changes)
|
||||
|
||||
|
||||
class MappingBatchIntegrationTest(unittest.TestCase):
|
||||
def register(self, replace):
|
||||
old = {"name": "DroidDeck-Proton-11-11.2", "dir": "DroidDeck-Proton 11-11.2", "valve": False}
|
||||
new = {"name": "DroidDeck-Proton-11-11.4", "dir": "DroidDeck-Proton 11-11.4", "valve": False}
|
||||
valve = {"name": COMPAT["TOOL"], "dir": "Proton - Experimental (ARM64)", "valve": True}
|
||||
before = old if replace else valve
|
||||
apps = [str(app) for app in range(1, 65)]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
state = Path(tmp) / "state"
|
||||
state.mkdir()
|
||||
(state / "state.json").write_text(json.dumps({
|
||||
"default": before["name"], "own_proton": True, "tools": [valve, before],
|
||||
"auto": {app: before["name"] for app in apps},
|
||||
}))
|
||||
config = Path(tmp) / "Steam/config/config.vdf"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(config_text("".join(
|
||||
'"%s" { "name" "%s" "priority" "%s" }' %
|
||||
(app, before["name"], "75" if app == "0" else "250") for app in ["0", *apps])))
|
||||
globals_ = COMPAT["register_default"].__globals__
|
||||
single = mock.Mock(wraps=COMPAT["set_mapping"])
|
||||
with mock.patch.dict(globals_, set_mapping=single, steam_running=lambda: False):
|
||||
result = COMPAT["register_default"](
|
||||
str(config), apps, catalog=[valve, new], directory=str(state), settle=True,
|
||||
default=None if replace else new["name"])
|
||||
self.assertEqual(result, new["name"])
|
||||
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {app: new["name"] for app in ["0", *apps]})
|
||||
self.assertLessEqual(single.call_count, 1 if replace else 0)
|
||||
|
||||
def test_retired_proton_replacements_are_batched(self):
|
||||
self.register(replace=True)
|
||||
|
||||
def test_planned_default_changes_are_batched(self):
|
||||
self.register(replace=False)
|
||||
|
||||
def test_x64_repoint_batches_default_and_games_and_keeps_pending_order(self):
|
||||
apps = [str(app) for app in range(1, 65)]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
steam = Path(tmp) / "Steam"
|
||||
config = steam / "config/config.vdf"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(config_text("".join('"%s" { "name" "proton_experimental" }' % app for app in apps)))
|
||||
pending = Path(tmp) / ".bl-compat-pending"
|
||||
pending.write_text("before\n")
|
||||
globals_ = COMPAT["x64_repoint"].__globals__
|
||||
single = mock.Mock(wraps=COMPAT["set_mapping"])
|
||||
with mock.patch.dict(globals_, set_mapping=single), mock.patch.dict("os.environ", HOME=tmp):
|
||||
moved = COMPAT["x64_repoint"](str(steam), "new-a64", live=True)
|
||||
self.assertEqual(moved, apps)
|
||||
self.assertEqual(COMPAT["read_config_mapping"](str(config)), {app: "new-a64" for app in ["0", *apps]})
|
||||
self.assertEqual(pending.read_text(), "before\n" + "".join(app + "\n" for app in apps))
|
||||
single.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -50,14 +50,12 @@ CONFIG = '''"InstallConfigStore"
|
||||
|
||||
|
||||
class X64RepointTest(unittest.TestCase):
|
||||
"""steam-compatibility --x64: the x86-64 client's Proton entries go to its arm64 wrapper."""
|
||||
|
||||
def setUp(self):
|
||||
self.home = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.home.name) / "Steam"
|
||||
(self.root / "config").mkdir(parents=True)
|
||||
(self.root / "config" / "config.vdf").write_text(CONFIG)
|
||||
# A wrapper of its own whose name starts with "proton": kept, never repointed.
|
||||
own = self.root / "compatibilitytools.d" / "proton-cachyos-a64"
|
||||
own.mkdir(parents=True)
|
||||
(own / "compatibilitytool.vdf").write_text('"compatibilitytools"\n{\n\t"compat_tools"\n\t{\n\t\t"proton-cachyos-a64"\n\t\t{\n\t\t}\n\t}\n}\n')
|
||||
@@ -82,12 +80,10 @@ class X64RepointTest(unittest.TestCase):
|
||||
self.assertEqual(m["550"], "GE-Proton11-7-a64")
|
||||
self.assertEqual(m["620"], "proton-cachyos-a64")
|
||||
self.assertEqual(m["730"], "steamlinuxruntime")
|
||||
# The arm64 client's own Proton name, which this client ignores.
|
||||
self.assertEqual(m["880"], "GE-Proton11-7-a64")
|
||||
self.assertEqual(m["0"], "GE-Proton11-7-a64")
|
||||
|
||||
def test_repoints_arm64_name_even_with_its_stray_tool(self):
|
||||
# An arm64 compat pass that ran against this client also left its tool folder here.
|
||||
stray = self.root / "compatibilitytools.d" / "droiddeck-proton-arm64"
|
||||
stray.mkdir(parents=True)
|
||||
(stray / "compatibilitytool.vdf").write_text('"compatibilitytools"\n{\n\t"compat_tools"\n\t{\n\t\t"droiddeck-proton-arm64"\n\t\t{\n\t\t}\n\t}\n}\n')
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Desktop Steam stays on KDE; explicit Big Picture still switches sessions."""
|
||||
import fcntl
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -92,6 +91,30 @@ class DesktopSteamLaunchTest(unittest.TestCase):
|
||||
'-cef-disable-gpu', 'steam://open/settings'])
|
||||
self.assertFalse((self.session / 'steam-launch').exists())
|
||||
|
||||
def _running_client(self):
|
||||
steam = self.root / 'data/Steam/steamrtarm64/steam'
|
||||
steam.parent.mkdir(parents=True)
|
||||
steam.write_text('#!/bin/bash\nprintf "%s\\n" "$@"\n')
|
||||
steam.chmod(0o755)
|
||||
(self.root / '.steam').mkdir()
|
||||
os.mkfifo(self.root / '.steam/steam.pipe')
|
||||
(self.root / '.steam/steam.pid').write_text(str(os.getpid()))
|
||||
|
||||
def test_bottom_screen_desktop_hands_games_to_the_running_client(self):
|
||||
self._running_client()
|
||||
self.env['BL_BOTTOM_DESKTOP'] = '1'
|
||||
result = self.launch('desktop', '501590')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.splitlines(), ['-nobigpicture', '-no-cef-sandbox', '-cef-ozone-platform=x11',
|
||||
'-cef-disable-gpu', 'steam://rungameid/501590'])
|
||||
self.assertFalse((self.root / 'cache/droiddeck/steam-desktop.lock').exists())
|
||||
|
||||
def test_bottom_screen_desktop_starts_its_own_client_when_none_runs(self):
|
||||
self.env.update(BL_BOTTOM_DESKTOP='1', DISPLAY=':7')
|
||||
result = self.launch('desktop')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.splitlines(), ['1', 'desktop', ':7', 'steam', 'steam://open/library'])
|
||||
|
||||
def test_second_click_forwards_to_the_x86_64_client_in_its_own_home(self):
|
||||
lock = self.root / 'cache/droiddeck/steam-desktop.lock'
|
||||
lock.parent.mkdir(parents=True)
|
||||
|
||||
@@ -6,6 +6,7 @@ from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
import zlib
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
|
||||
@@ -247,6 +248,36 @@ class ImportsTest(unittest.TestCase):
|
||||
config.write_text(json.dumps({'installedManifestIDs': {'43': 0x7FFFFFFFFFFFFFFF}}))
|
||||
self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42'))
|
||||
|
||||
def test_compressed_protobuf_depot_config_records_installed_depots(self):
|
||||
config = self.folder / '.DepotDownloader/depot.config'
|
||||
config.parent.mkdir()
|
||||
(self.folder / '.download_complete').touch()
|
||||
entry = bytes([0x08, 43, 0x10, 99])
|
||||
packed = zlib.compressobj(wbits=-15)
|
||||
config.write_bytes(packed.compress(bytes([0x0A, len(entry)]) + entry) + packed.flush())
|
||||
self.assertIn('"43"\n {\n "manifest" "99"', imports.installed_build(self.folder, 42, 'DroidDeck-42'))
|
||||
config.write_bytes(b'not a config')
|
||||
self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42'))
|
||||
(config.parent / 'completed').mkdir()
|
||||
(config.parent / 'completed/43_98.manifest').write_bytes(b'x')
|
||||
self.assertIn('"manifest" "98"', imports.installed_build(self.folder, 42, 'DroidDeck-42'))
|
||||
config.write_text(json.dumps({'installedManifestIDs': {}}))
|
||||
self.assertIn('"manifest" "98"', imports.installed_build(self.folder, 42, 'DroidDeck-42'))
|
||||
|
||||
def test_completed_manifests_record_installed_depots(self):
|
||||
completed = self.folder / '.DepotDownloader/completed'
|
||||
completed.mkdir(parents=True)
|
||||
(self.folder / '.download_complete').touch()
|
||||
self.assertIsNone(imports.installed_build(self.folder, 42, 'DroidDeck-42'))
|
||||
(completed / '43_98.manifest').write_bytes(b'old')
|
||||
(completed / '43_99.manifest').write_bytes(b'new')
|
||||
(completed / '44_7.manifest').write_bytes(b'x')
|
||||
os.utime(completed / '43_98.manifest', (1, 1))
|
||||
text = imports.installed_build(self.folder, 42, 'DroidDeck-42')
|
||||
self.assertIn('"43"\n {\n "manifest" "99"', text)
|
||||
self.assertIn('"44"\n {\n "manifest" "7"', text)
|
||||
self.assertNotIn('"98"', text)
|
||||
|
||||
def test_bare_import_manifest_gains_installed_build(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
@@ -391,6 +422,61 @@ class ImportsTest(unittest.TestCase):
|
||||
with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError):
|
||||
self.assertEqual(42, imports.identify(self.game))
|
||||
|
||||
def test_spacewar_appid_names_no_game(self):
|
||||
(self.folder / 'steam_appid.txt').write_text('480\n')
|
||||
with patch.object(imports.urllib.request, 'urlopen', side_effect=OSError):
|
||||
self.assertIsNone(imports.identify(self.game))
|
||||
|
||||
def import_as(self, appid):
|
||||
self.assertTrue(imports.seed_install(self.steam, self.game, appid))
|
||||
self.assertTrue((self.steam / f'steamapps/appmanifest_{appid}.acf').is_file())
|
||||
|
||||
def snapshot_names(self, appid, owned):
|
||||
imports.save_json(self.acct / 'config' / imports.STATE,
|
||||
dict(account='123', owned={str(appid): owned},
|
||||
candidates={str(self.folder): appid},
|
||||
sources={str(self.folder): imports.source_stamp(self.game)}))
|
||||
|
||||
def assert_not_imported_as(self, appid):
|
||||
self.assertFalse((self.steam / f'steamapps/appmanifest_{appid}.acf').exists())
|
||||
self.assertFalse(os.path.lexists(self.steam / f'steamapps/common/DroidDeck-{appid}'))
|
||||
|
||||
def test_spacewar_import_is_released_and_never_made_again(self):
|
||||
self.import_as(480)
|
||||
self.snapshot_names(480, owned=True)
|
||||
with patch('builtins.print'):
|
||||
self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game]))
|
||||
self.assert_not_imported_as(480)
|
||||
self.assertEqual(b'game', self.exe.read_bytes())
|
||||
|
||||
def test_import_follows_the_app_the_files_name_now(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
self.snapshot_names(43, owned=True)
|
||||
with patch('builtins.print'):
|
||||
self.assertEqual(([], {str(self.game['appid']): 43}), imports.route(self.steam, self.acct, [self.game]))
|
||||
self.assert_not_imported_as(42)
|
||||
self.assertEqual(self.folder, (self.steam / 'steamapps/common/DroidDeck-43').resolve())
|
||||
|
||||
def test_unowned_new_appid_leaves_a_shortcut(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
self.snapshot_names(43, owned=False)
|
||||
with patch('builtins.print'):
|
||||
self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game]))
|
||||
self.assert_not_imported_as(42)
|
||||
self.assert_not_imported_as(43)
|
||||
|
||||
def test_import_stays_while_the_new_identity_is_unknown(self):
|
||||
self.snapshot()
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
for candidates in ({}, {str(self.folder): 43}):
|
||||
imports.save_json(self.acct / 'config' / imports.STATE,
|
||||
dict(account='123', owned={'43': True}, candidates=candidates,
|
||||
sources={str(self.folder): ['stale']}))
|
||||
imports.route(self.steam, self.acct, [self.game])
|
||||
self.assertTrue((self.steam / 'steamapps/appmanifest_42.acf').is_file())
|
||||
|
||||
def test_manifest_identity_uses_install_directory(self):
|
||||
folder = self.root / 'second/steamapps/common/Custom Name'
|
||||
folder.mkdir(parents=True)
|
||||
@@ -399,6 +485,21 @@ class ImportsTest(unittest.TestCase):
|
||||
with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError):
|
||||
self.assertEqual(42, imports.identify(game))
|
||||
|
||||
def test_a_spacewar_manifest_names_no_game(self):
|
||||
folder = self.root / 'second/steamapps/common/PEAK'
|
||||
folder.mkdir(parents=True)
|
||||
(folder.parent.parent / 'appmanifest_480.acf').write_text('"AppState" { "installdir" "PEAK" }')
|
||||
(folder / 'steam_appid.txt').write_text('3527290\n')
|
||||
game = dict(self.game, folder=str(folder), exe=str(folder / 'PEAK.exe'))
|
||||
with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError):
|
||||
self.assertEqual(3527290, imports.identify(game))
|
||||
|
||||
def test_a_store_search_answering_spacewar_names_no_game(self):
|
||||
with patch.object(imports.urllib.request, 'urlopen') as request:
|
||||
request.return_value.__enter__.return_value.read.return_value = json.dumps(
|
||||
{'items': [{'id': 480, 'name': 'Spacewar'}]}).encode()
|
||||
self.assertIsNone(imports.identify(dict(self.game, name='Spacewar')))
|
||||
|
||||
def test_store_requires_unique_exact_title(self):
|
||||
cases = [([{'id': 42, 'name': 'Example Deluxe'}], None),
|
||||
([{'id': 42, 'name': 'Example'}, {'id': 43, 'name': 'Example'}], None),
|
||||
|
||||
@@ -280,8 +280,6 @@ done(28 if end < len(data) else 0)
|
||||
self.assertFalse(self.requests.exists())
|
||||
|
||||
def publish(self, **parts):
|
||||
"""The CDN's client as these parts (block name -> byte count of incompressible content),
|
||||
listed with sizes as Valve's manifest lists them."""
|
||||
files = {}
|
||||
blocks = ''
|
||||
for block, length in parts.items():
|
||||
|
||||
@@ -90,6 +90,20 @@ class LibraryListTest(unittest.TestCase):
|
||||
self.assertIn(self.pc, self.paths(self.run_main()))
|
||||
self.assertIn(self.card, self.paths(self.vdf.read_text()))
|
||||
|
||||
def test_added_library_is_registered_while_listed_and_forgotten_once_removed(self):
|
||||
added = self.root / "lib" / "1"
|
||||
manifest(added / "steamapps", 20)
|
||||
with patch.object(library, "ADDED_DIR", str(self.root / "lib") + "/"):
|
||||
self.listing.write_text(json.dumps([{"path": str(added), "label": "Documents"}]))
|
||||
text = self.run_main()
|
||||
self.assertIn(added, self.paths(text))
|
||||
self.assertIn('"20"\t\t"0"', text)
|
||||
self.listing.write_text(json.dumps([]))
|
||||
text = self.run_main()
|
||||
self.assertNotIn(added, self.paths(text))
|
||||
self.assertIn(self.user, self.paths(text))
|
||||
self.assertTrue((added / "steamapps/appmanifest_20.acf").is_file())
|
||||
|
||||
def test_without_a_list_only_the_card_is_managed(self):
|
||||
text = self.run_main(listing=False)
|
||||
self.assertEqual([self.steam, self.old, self.user, self.card], self.paths(text))
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
|
||||
|
||||
HARNESS = """
|
||||
const reports = [];
|
||||
global.appStore = {
|
||||
BHasCachedLibraryAsset(appid, version, type) {
|
||||
if ((version ?? 0) & (1 << type)) return true;
|
||||
reports.push([appid, type]);
|
||||
return false;
|
||||
},
|
||||
};
|
||||
const first = eval(process.argv[2]);
|
||||
const second = eval(process.argv[2]);
|
||||
const check = (name, actual, expected) => { if (actual !== expected) throw new Error(name + ": " + actual); };
|
||||
check("install", first, "installed");
|
||||
check("reinstall", second, "present");
|
||||
check("no logon", appStore.BHasCachedLibraryAsset(10, undefined, 3), true);
|
||||
check("zero version", appStore.BHasCachedLibraryAsset(10, 0, 3), true);
|
||||
check("reported", reports.length, 2);
|
||||
check("bit set", appStore.BHasCachedLibraryAsset(10, 1 << 3, 3), true);
|
||||
check("bit missing", appStore.BHasCachedLibraryAsset(10, 1 << 2, 3), false);
|
||||
check("reported again", reports.length, 3);
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("node"), "node is not installed")
|
||||
class LibraryArtTest(unittest.TestCase):
|
||||
def run_node(self, harness):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
script = Path(directory, "harness.js")
|
||||
script.write_text("global.window = {};\n" + harness)
|
||||
return subprocess.run(["node", str(script), LIVE["LIBRARY_ART_JS"]], capture_output=True, text=True, timeout=20)
|
||||
|
||||
def test_apps_without_a_client_cache_report_read_from_the_local_library_cache(self):
|
||||
result = self.run_node(HARNESS)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_a_page_without_the_app_store_is_left_alone(self):
|
||||
result = self.run_node("""
|
||||
if (eval(process.argv[2]) !== "unavailable") throw new Error("installed without an app store");
|
||||
""")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,6 +1,3 @@
|
||||
"""droiddeck-store-launch: a launch from anywhere - the Steam client's own Play button included -
|
||||
asks the app for an Epic game's sign-in code before Proton starts. These pin how it recognises a
|
||||
store game, how it asks, and that both Proton launchers call it."""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
@@ -441,6 +438,120 @@ class GogRegistry(unittest.TestCase):
|
||||
], entries)
|
||||
self.assertEqual(3, skipped)
|
||||
|
||||
def test_a_game_whose_support_installer_cannot_run_gets_the_install_registry(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1207658924')
|
||||
(folder / 'goggame-1207658924.info').write_text(json.dumps({'language': 'English', 'languages': ['en-US']}))
|
||||
gog_script(folder, '1207658924', [
|
||||
{'install': {'action': 'Execute', 'arguments': {'executable': 'galaxy_the_witcher_enhanced_edition_2.1.0.15.exe'}}},
|
||||
])
|
||||
entries, skipped = store.gog_registry(folder)
|
||||
app = store.windows_path(str(folder)).replace('\\', '\\\\')
|
||||
self.assertEqual([
|
||||
'[HKEY_LOCAL_MACHINE\\Software\\CD Projekt Red\\The Witcher]\r\n"InstallFolder"="%s\\\\"' % app,
|
||||
'[HKEY_LOCAL_MACHINE\\Software\\CD Projekt Red\\The Witcher]\r\n"RegionVersion"="US"',
|
||||
'[HKEY_LOCAL_MACHINE\\Software\\CD Projekt Red\\The Witcher]\r\n"IsDjinniInstalled"=dword:00000001',
|
||||
'[HKEY_LOCAL_MACHINE\\Software\\CD Projekt Red\\The Witcher]\r\n"Language"="3"',
|
||||
'[HKEY_CURRENT_USER\\Software\\CD Projekt RED\\Witcher\\Settings]\r\n"TextLanguage"="3"',
|
||||
'[HKEY_CURRENT_USER\\Software\\CD Projekt RED\\Witcher\\Settings]\r\n"VoiceLanguage"="3"',
|
||||
], entries)
|
||||
self.assertEqual(0, skipped)
|
||||
|
||||
def test_a_players_language_choice_is_not_overwritten(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1207658924')
|
||||
(folder / 'goggame-1207658924.info').write_text(json.dumps({'languages': ['en-US']}))
|
||||
proton = Path(root) / 'proton'
|
||||
proton.write_text('selected Proton')
|
||||
data = Path(root) / 'compat'
|
||||
(data / 'pfx').mkdir(parents=True)
|
||||
(data / 'pfx/user.reg').write_text(
|
||||
'[Software\\\\OtherApp] 1\n"InstallFolder"="C:\\\\Other"\n\n'
|
||||
'[Software\\\\CD Projekt RED\\\\Witcher\\\\Settings] 1\n"TextLanguage"="5"\n')
|
||||
imported = []
|
||||
def run(argv, **kwargs):
|
||||
imported.append(Path(argv[4][2:].replace('\\', '/')).read_bytes()[2:].decode('utf-16-le'))
|
||||
(data / 'pfx/system.reg').write_text('Wine registry')
|
||||
return __import__('subprocess').CompletedProcess(argv, 0)
|
||||
with patch.object(store.subprocess, 'run', side_effect=run):
|
||||
store.apply_gog_registry(folder, str(data), str(proton))
|
||||
text = imported[0]
|
||||
self.assertNotIn('"TextLanguage"', text)
|
||||
self.assertIn('"VoiceLanguage"', text)
|
||||
self.assertIn('"InstallFolder"', text)
|
||||
|
||||
def test_malformed_language_metadata_falls_back_to_english(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1207658924')
|
||||
(folder / 'goggame-1207658924.info').write_text(json.dumps({'languages': 3}))
|
||||
entries, _ = store.gog_registry(folder)
|
||||
self.assertIn('"Language"="3"', entries[3])
|
||||
|
||||
def test_a_native_hklm_value_does_not_replace_the_32_bit_fallback(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1207658924')
|
||||
(folder / 'goggame-1207658924.info').write_text(json.dumps({'languages': ['en-US']}))
|
||||
pfx = Path(root) / 'pfx'
|
||||
pfx.mkdir()
|
||||
(pfx / 'system.reg').write_text(
|
||||
'[Software\\\\CD Projekt Red\\\\The Witcher] 1\n"InstallFolder"="C:\\\\Native"\n')
|
||||
entries, _ = store.gog_registry(folder, store.gog_registry_values(pfx))
|
||||
self.assertTrue(any('"InstallFolder"' in entry for entry in entries))
|
||||
(pfx / 'system.reg').write_text(
|
||||
'[Software\\\\Wow6432Node\\\\CD Projekt Red\\\\The Witcher] 1\n"InstallFolder"="C:\\\\32bit"\n')
|
||||
entries, _ = store.gog_registry(folder, store.gog_registry_values(pfx))
|
||||
self.assertFalse(any('"InstallFolder"' in entry for entry in entries))
|
||||
|
||||
def test_a_deleted_fallback_value_is_imported_again(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1207658924')
|
||||
(folder / 'goggame-1207658924.info').write_text(json.dumps({'languages': ['en-US']}))
|
||||
proton = Path(root) / 'proton'
|
||||
proton.write_text('selected Proton')
|
||||
data = Path(root) / 'compat'
|
||||
pfx = data / 'pfx'
|
||||
pfx.mkdir(parents=True)
|
||||
imported = []
|
||||
def run(argv, **kwargs):
|
||||
imported.append(argv)
|
||||
(pfx / 'system.reg').write_text(
|
||||
'[Software\\\\Wow6432Node\\\\CD Projekt Red\\\\The Witcher] 1\n'
|
||||
'"InstallFolder"="C:\\\\Game"\n"RegionVersion"="US"\n'
|
||||
'"IsDjinniInstalled"=dword:00000001\n"Language"="3"\n')
|
||||
(pfx / 'user.reg').write_text(
|
||||
'[Software\\\\CD Projekt RED\\\\Witcher\\\\Settings] 1\n'
|
||||
'"TextLanguage"="3"\n"VoiceLanguage"="3"\n')
|
||||
return __import__('subprocess').CompletedProcess(argv, 0)
|
||||
with patch.object(store.subprocess, 'run', side_effect=run):
|
||||
self.assertEqual('written=6', store.apply_gog_registry(folder, str(data), str(proton)))
|
||||
self.assertEqual('none', store.apply_gog_registry(folder, str(data), str(proton)))
|
||||
(pfx / 'system.reg').write_text(
|
||||
'[Software\\\\Wow6432Node\\\\CD Projekt Red\\\\The Witcher] 1\n'
|
||||
'"RegionVersion"="US"\n"IsDjinniInstalled"=dword:00000001\n"Language"="3"\n')
|
||||
self.assertEqual('written=1', store.apply_gog_registry(folder, str(data), str(proton)))
|
||||
self.assertEqual(2, len(imported))
|
||||
|
||||
def test_the_install_language_selects_the_titles_language_id(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1207658924')
|
||||
(folder / 'goggame-1207658924.info').write_text(json.dumps({'languages': ['pl-PL']}))
|
||||
entries, _ = store.gog_registry(folder)
|
||||
self.assertIn('"Language"="5"', entries[3])
|
||||
|
||||
def test_a_script_that_sets_registry_keeps_its_own_values(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog', ident='1207658924')
|
||||
(folder / 'goggame-1207658924.info').write_text(json.dumps({'languages': ['en-US']}))
|
||||
gog_script(folder, '1207658924', [
|
||||
set_registry(root='HKLM', subkey='Software\\CD Projekt Red\\The Witcher',
|
||||
valueName='InstallFolder', valueData='{app}\\', valueType='string'),
|
||||
])
|
||||
entries, _ = store.gog_registry(folder)
|
||||
app = store.windows_path(str(folder)).replace('\\', '\\\\')
|
||||
self.assertEqual([
|
||||
'[HKEY_LOCAL_MACHINE\\Software\\CD Projekt Red\\The Witcher]\r\n"InstallFolder"="%s\\\\"' % app,
|
||||
], entries)
|
||||
|
||||
def test_a_game_without_a_script_starts_without_proton(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = game(root, store_id='gog')
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
"""The shortcuts writer and a store install: the app registers a game GOG, Epic or Amazon
|
||||
installed through the same listing as an added folder, pointing the shortcut at the game's
|
||||
launcher .bat when it has one. These pin the parts of the writer that contract relies on."""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
@@ -28,8 +25,6 @@ LAUNCHER = FOLDER + '/.droiddeck-launch.bat'
|
||||
|
||||
|
||||
def app_id(exe, name):
|
||||
"""The appid the app computes for a shortcut (AddedGames.scanGame): CRC32 of the quoted exe
|
||||
and the name, high bit set - what Steam itself derives for a shortcut it is given."""
|
||||
return (zlib.crc32(('"%s"' % exe + name).encode()) | 0x80000000) & 0xFFFFFFFF
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ TERMUX_DIR = TESTS.parents[1] / "app/src/main/cpp/termux"
|
||||
|
||||
|
||||
def jni_include_dir():
|
||||
"""A directory holding jni.h: JNI_INCLUDE, then the JDK, then the Android NDK."""
|
||||
candidates = [os.environ.get("JNI_INCLUDE")]
|
||||
java_home = os.environ.get("JAVA_HOME")
|
||||
if java_home:
|
||||
@@ -29,7 +28,6 @@ def jni_include_dir():
|
||||
|
||||
|
||||
def include_flags():
|
||||
"""-I flags for jni.h, plus the JDK's per-platform directory that holds jni_md.h."""
|
||||
base = jni_include_dir()
|
||||
flags = ["-I", base]
|
||||
for sub in glob.glob(os.path.join(base, "*")):
|
||||
|
||||
@@ -33,6 +33,7 @@ int probe(void) {
|
||||
#include <dlfcn.h>
|
||||
int bl_fsync_syscall(long n, const long *a, long *r) { (void)n; (void)a; (void)r; return 0; }
|
||||
int bl_writewatch_syscall(long n, const long *a, long (*real)(long, ...), long *r) { (void)n; (void)a; (void)real; (void)r; return 0; }
|
||||
int bl_clock_syscall(long n, const long *a, long (*real)(long, ...), long *r) { (void)n; (void)a; (void)real; (void)r; return 0; }
|
||||
#include """ + '"' + robust.as_posix() + '"' + r"""
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 3);
|
||||
|
||||
@@ -61,6 +61,19 @@ class WebhelperPreloadTest(unittest.TestCase):
|
||||
args = [WEBHELPER, "--enable-features=A"]
|
||||
self.assertEqual(self.argv(*args, spec="stock"), args)
|
||||
|
||||
def test_angle_switches_are_appended_with_the_gpu_process_kept_out_of_process(self):
|
||||
out = self.argv(WEBHELPER, "-lang=en_US", "--enable-features=A", spec="--use-gl=angle --use-angle=vulkan")
|
||||
self.assertEqual(out, [WEBHELPER, "-lang=en_US", "--use-gl=angle", "--use-angle=vulkan",
|
||||
"--enable-features=A"])
|
||||
self.assertNotIn("--in-process-gpu", out)
|
||||
|
||||
def test_vulkan_compositing_features_join_steams_feature_list(self):
|
||||
out = self.argv(WEBHELPER, "--enable-features=PlatformHEVCDecoderSupport,V4L2VideoDecode",
|
||||
spec="--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
|
||||
self.assertEqual(out, [WEBHELPER, "--use-gl=angle", "--use-angle=vulkan",
|
||||
"--enable-features=PlatformHEVCDecoderSupport,V4L2VideoDecode,"
|
||||
"Vulkan,VulkanFromANGLE,DefaultANGLEVulkan"])
|
||||
|
||||
def test_an_empty_setting_means_the_default(self):
|
||||
self.assertIn("--no-zygote", self.argv(WEBHELPER, spec=""))
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
# Stands in for libfakeinput.so, which ld.so.preload lists after libblsession.so.
|
||||
SHIM = r"""
|
||||
#include <linux/input.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
@@ -136,7 +136,7 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
self.assertNotIn('DROIDDECK_XBOX_COMMAND_FILE', child_env)
|
||||
self.assertEqual(child_env['XODUS_BRIDGE_KEY'], 'runtime-key')
|
||||
|
||||
def test_launch_view_runs_from_a_short_drive_letter(self):
|
||||
def test_launch_view_runs_from_its_own_folder_on_a_short_drive_letter(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
root = Path(root)
|
||||
prefix = root / 'compat/pfx'
|
||||
@@ -156,7 +156,7 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
with patch.dict(os.environ, env), patch.dict(xbox['wine'].__globals__, RUNTIME=runtime.parent), patch('subprocess.run') as initialize, patch('subprocess.call', side_effect=call):
|
||||
initialize.return_value.returncode = 0
|
||||
self.assertEqual(xbox['wine']([str(view / 'Bin/Game.exe')]), 0)
|
||||
self.assertEqual(seen, [(['/selected/proton', 'waitforexitandrun', 'X:\\Bin\\Game.exe'], str(view))])
|
||||
self.assertEqual(seen, [(['/selected/proton', 'waitforexitandrun', 'X:\\droiddeck-xbox-1ZpM3D\\Bin\\Game.exe'], str(view.parent))])
|
||||
self.assertFalse(os.path.lexists(prefix / 'dosdevices/x:'))
|
||||
|
||||
def test_view_drive_keeps_drives_in_use_and_reuses_a_stale_view(self):
|
||||
@@ -170,8 +170,8 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
(devices / 'w:').symlink_to(root / 'games')
|
||||
(devices / 'v:').symlink_to(views / 'launch-0/droiddeck-xbox-gone')
|
||||
exe, link = xbox['view_drive'](root / 'pfx', str(view / 'Game.exe'))
|
||||
self.assertEqual((exe, link), ('V:\\Game.exe', devices / 'v:'))
|
||||
self.assertEqual(os.readlink(devices / 'v:'), str(view))
|
||||
self.assertEqual((exe, link), ('V:\\droiddeck-xbox-new\\Game.exe', devices / 'v:'))
|
||||
self.assertEqual(os.readlink(devices / 'v:'), str(view.parent))
|
||||
self.assertEqual(os.readlink(devices / 'x:'), str(live))
|
||||
self.assertEqual(sorted(p.name for p in devices.iterdir()), ['v:', 'w:', 'x:'])
|
||||
self.assertEqual(xbox['view_drive'](root / 'pfx', '/games/Game.exe'), ('/games/Game.exe', None))
|
||||
|
||||
Reference in new issue
Block a user