Merge origin/main into feat/malibridge-v25

This commit is contained in:
DroidDeck Merge committed 2026-11-01 19:59:31 +08:00
commit a2a5f84711
132 files changed
+7212 -156

No files matched your search

+15
View File
@@ -237,5 +237,20 @@
"packages": [
"gcc-aarch64-linux-gnu"
]
},
"dirt-ws2": {
"script": "tools/components/recipes/dirt-ws2.sh",
"inputs": [
"tools/dirt-ws2",
"tools/components/recipes/dirt-ws2.sh"
],
"outputs": [
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-dirt/ws2_32.dll"
],
"packages": [
"clang",
"lld",
"llvm"
]
}
}
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
set -euo pipefail
bash tools/dirt-ws2/build.sh app/src/main/assets/linuxfs/usr/local/lib/droiddeck-dirt
+19
View File
@@ -0,0 +1,19 @@
# DiRT 3 / DiRT Showdown ws2_32 stand-in
DiRT 3 (`dirt3_game.exe`) and DiRT Showdown (`showdown.exe`, `showdown_avx.exe`) close their motion telemetry UDP
socket at the end of a race, and when leaving Joyride, but keep calling `sendto()` on it. `sendto()` fails with
WSAENOTSOCK and the game stops with "sendto failed with error 10038". The same happens on Windows.
`ws2_32.dll` here is a 32-bit stand-in: every export jumps to the same-ordinal export of Wine's own `ws2_32.dll`;
only a `sendto()` that fails with 10038 reports 0 bytes sent instead. Same behaviour as
[DiRTTelemetryErrorFix](https://github.com/RoccoC/DiRTTelemetryErrorFix) by RoccoC (MIT), based on the original fix
by Carsten Gottschling.
Wine loads `ws2_32` as a KnownDLL, so a copy beside the game is ignored. `droiddeck-game-env` puts the stand-in in
place of the prefix's `syswow64/ws2_32.dll` for these games while their telemetry output is on, adds
`WINEDLLOVERRIDES=ws2_32=n,b`, and puts Wine's file back when the game exits. It skips the swap when the game's
Proton already has the fix in its own `ws2_32.dll` (DroidDeck-Proton patch
`dirt-telemetry-sendto-closed-socket.patch`).
`build.sh OUT` builds it with clang, lld and llvm-dlltool and checks its exports against `ws2_32-exports.txt`
(taken from Wine 11's `ws2_32.dll`).
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
# Builds the 32-bit ws2_32.dll stand-in for DiRT 3 and DiRT Showdown into the given folder.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
mkdir -p "$1"
out=$(cd "$1" && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
tool() {
local found
found=$(command -v "$1" || ls /usr/lib/llvm-*/bin/"$1" 2>/dev/null | sort -V | tail -n1 || true)
[ -n "$found" ] || { echo "dirt-ws2: $1 not found" >&2; exit 1; }
echo "$found"
}
clang=$(tool clang)
dlltool=$(tool llvm-dlltool)
tool ld.lld > /dev/null
python3 "$here/gen.py" generate "$here" "$work"
"$dlltool" -m i386 -k -d "$here/kernel32.def" -l "$work/libkernel32.a"
"$clang" --target=i686-w64-mingw32 -O2 -Wall -Wextra -Werror -ffreestanding -fno-stack-protector -fno-builtin \
-nostdlib -shared -fuse-ld=lld -o "$work/ws2_32.dll" "$here/ws2_32.c" "$work/thunks.c" "$work/ws2_32.def" \
-L"$work" -lkernel32 -Wl,--entry,DllMain@12 -Wl,--no-insert-timestamp
python3 "$here/gen.py" verify "$here" "$work/ws2_32.dll"
install -m 644 "$work/ws2_32.dll" "$out/ws2_32.dll"
+74
View File
@@ -0,0 +1,74 @@
"""ws2_32 stand-in helpers.
gen.py generate SRC OUT writes OUT/thunks.c (one jump per export) and OUT/ws2_32.def from SRC/ws2_32-exports.txt.
gen.py verify SRC DLL checks that DLL exports exactly the ordinals and names in SRC/ws2_32-exports.txt.
"""
import struct
import sys
from pathlib import Path
def exports_list(src):
rows = []
for line in (Path(src) / 'ws2_32-exports.txt').read_text().splitlines():
ordinal, name = line.split()
rows.append((int(ordinal), name))
return rows
def generate(src, out):
rows = exports_list(src)
passed = [(o, n) for o, n in rows if n != 'sendto']
c = ['/* Generated by tools/dirt-ws2/gen.py. */',
'const unsigned short dirtfix_ordinals[%d] = {%s};' % (len(passed), ', '.join(str(o) for o, _ in passed)),
'const unsigned int dirtfix_count = %d;' % len(passed),
'void *dirtfix_real[%d];' % len(passed),
'__asm__(".text\\n"']
for i, (o, _) in enumerate(passed):
c.append(' ".globl _dirtfix_t%d\\n_dirtfix_t%d:\\n\\tjmp *_dirtfix_real+%d\\n"' % (o, o, 4 * i))
c.append(');')
(Path(out) / 'thunks.c').write_text('\n'.join(c) + '\n')
d = ['LIBRARY ws2_32.dll', 'EXPORTS']
d += [' %s=%s @%d' % (n, 'dirtfix_sendto@24' if n == 'sendto' else 'dirtfix_t%d' % o, o) for o, n in rows]
(Path(out) / 'ws2_32.def').write_text('\n'.join(d) + '\n')
def pe_exports(path):
data = Path(path).read_bytes()
pe = struct.unpack_from('<I', data, 0x3c)[0]
machine, sections = struct.unpack_from('<HH', data, pe + 4)
optional_size = struct.unpack_from('<H', data, pe + 20)[0]
optional = pe + 24
export_rva = struct.unpack_from('<I', data, optional + 96)[0]
table = [struct.unpack_from('<IIII', data, optional + optional_size + 40 * i + 8) for i in range(sections)]
def offset(rva):
for size, address, raw_size, raw in table:
if address <= rva < address + max(size, raw_size):
return rva - address + raw
raise ValueError('RVA %#x outside the sections' % rva)
base, functions, names, function_rva, name_rva, ordinal_rva = struct.unpack_from('<IIIIII', data, offset(export_rva) + 16)
named = {}
for i in range(names):
text = struct.unpack_from('<I', data, offset(name_rva) + 4 * i)[0]
index = struct.unpack_from('<H', data, offset(ordinal_rva) + 2 * i)[0]
named[index] = data[offset(text):].split(b'\0')[0].decode()
result = [(base + i, named.get(i)) for i in range(functions) if struct.unpack_from('<I', data, offset(function_rva) + 4 * i)[0]]
return machine, result
def verify(src, dll):
machine, found = pe_exports(dll)
if machine != 0x14c:
sys.exit('%s is not a 32-bit x86 DLL (machine %#x)' % (dll, machine))
expected = exports_list(src)
if found != expected:
sys.exit('%s exports differ from ws2_32-exports.txt: %d found, %d expected' % (dll, len(found), len(expected)))
if b'droiddeck-dirt-ws2_32' not in Path(dll).read_bytes():
sys.exit('%s lacks the stand-in marker' % dll)
print('%s: %d exports match, marker present' % (dll, len(found)))
if __name__ == '__main__':
{'generate': generate, 'verify': verify}[sys.argv[1]](sys.argv[2], sys.argv[3])
+7
View File
@@ -0,0 +1,7 @@
LIBRARY kernel32.dll
EXPORTS
LoadLibraryW@4
GetProcAddress@8
GetSystemDirectoryW@8
GetEnvironmentVariableW@12
GetFileAttributesW@4
+135
View File
@@ -0,0 +1,135 @@
1 accept
2 bind
3 closesocket
4 connect
5 getpeername
6 getsockname
7 getsockopt
8 htonl
9 htons
10 ioctlsocket
11 inet_addr
12 inet_ntoa
13 listen
14 ntohl
15 ntohs
16 recv
17 recvfrom
18 select
19 send
20 sendto
21 setsockopt
22 shutdown
23 socket
24 FreeAddrInfoEx
25 FreeAddrInfoExW
26 FreeAddrInfoW
27 GetAddrInfoExCancel
28 GetAddrInfoExOverlappedResult
29 GetAddrInfoExW
30 GetAddrInfoW
31 GetHostNameW
32 GetNameInfoW
33 InetNtopW
34 InetPtonW
35 WSApSetPostRoutine
36 WPUCompleteOverlappedRequest
37 WSAAccept
38 WSAAddressToStringA
39 WSAAddressToStringW
40 WSACloseEvent
41 WSAConnect
42 WSAConnectByNameA
43 WSAConnectByNameW
44 WSACreateEvent
45 WSADuplicateSocketA
46 WSADuplicateSocketW
47 WSAEnumNameSpaceProvidersA
48 WSAEnumNameSpaceProvidersW
49 WSAEnumNetworkEvents
50 WSAEnumProtocolsA
51 gethostbyaddr
52 gethostbyname
53 getprotobyname
54 getprotobynumber
55 getservbyname
56 getservbyport
57 gethostname
58 WSAEnumProtocolsW
59 WSAEventSelect
60 WSAGetOverlappedResult
61 WSAGetQOSByName
62 WSAGetServiceClassInfoA
63 WSAGetServiceClassInfoW
64 WSAGetServiceClassNameByClassIdA
65 WSAGetServiceClassNameByClassIdW
66 WSAHtonl
67 WSAHtons
68 WSAInstallServiceClassA
69 WSAInstallServiceClassW
70 WSAIoctl
71 WSAJoinLeaf
72 WSALookupServiceBeginA
73 WSALookupServiceBeginW
74 WSALookupServiceEnd
75 WSALookupServiceNextA
76 WSALookupServiceNextW
77 WSANSPIoctl
78 WSANtohl
79 WSANtohs
80 WSAPoll
81 WSAProviderConfigChange
82 WSARecv
83 WSARecvDisconnect
84 WSARecvFrom
85 WSARemoveServiceClass
86 WSAResetEvent
87 WSASend
88 WSASendDisconnect
89 WSASendMsg
90 WSASendTo
91 WSASetEvent
92 WSASetServiceA
93 WSASetServiceW
94 WSASocketA
95 WSASocketW
96 WSAStringToAddressA
97 WSAStringToAddressW
98 WSAWaitForMultipleEvents
99 WSCDeinstallProvider
100 WSCEnableNSProvider
101 WSAAsyncSelect
102 WSAAsyncGetHostByAddr
103 WSAAsyncGetHostByName
104 WSAAsyncGetProtoByNumber
105 WSAAsyncGetProtoByName
106 WSAAsyncGetServByPort
107 WSAAsyncGetServByName
108 WSACancelAsyncRequest
109 WSASetBlockingHook
110 WSAUnhookBlockingHook
111 WSAGetLastError
112 WSASetLastError
113 WSACancelBlockingCall
114 WSAIsBlocking
115 WSAStartup
116 WSACleanup
117 WSCEnumProtocols
118 WSCEnumProtocols32
119 WSCGetApplicationCategory
120 WSCGetProviderInfo
121 WSCGetProviderPath
122 WSCInstallNameSpace
123 WSCInstallProvider
124 WSCSetApplicationCategory
125 WSCUnInstallNameSpace
126 WSCUpdateProvider
127 WSCWriteNameSpaceOrder
128 WSCWriteProviderOrder
129 freeaddrinfo
130 getaddrinfo
131 getnameinfo
132 inet_ntop
133 inet_pton
151 __WSAFDIsSet
500 WEP
+103
View File
@@ -0,0 +1,103 @@
/* ws2_32.dll stand-in for DiRT 3 and DiRT Showdown (32-bit).
*
* Both games close their motion telemetry UDP socket at the end of a race (and when leaving Joyride) and keep
* calling sendto() on it; the WSAENOTSOCK (10038) failure stops the game. Every export here jumps to the
* same-ordinal export of Wine's own ws2_32.dll, except that a sendto() failing with 10038 reports 0 bytes sent.
* Same behaviour as DiRTTelemetryErrorFix by RoccoC (MIT), based on the fix by Carsten Gottschling. */
typedef unsigned short WCHAR;
typedef unsigned long DWORD;
typedef unsigned int UINT;
typedef unsigned int UINT_PTR;
typedef int BOOL;
typedef void *HMODULE;
#define WINAPI __attribute__((stdcall))
#define WSAENOTSOCK 10038
#define ORDINAL(n) ((const char *)(UINT_PTR)(n))
__attribute__((dllimport)) HMODULE WINAPI LoadLibraryW(const WCHAR *name);
__attribute__((dllimport)) void *WINAPI GetProcAddress(HMODULE module, const char *name);
__attribute__((dllimport)) UINT WINAPI GetSystemDirectoryW(WCHAR *buffer, UINT size);
__attribute__((dllimport)) DWORD WINAPI GetEnvironmentVariableW(const WCHAR *name, WCHAR *buffer, DWORD size);
__attribute__((dllimport)) DWORD WINAPI GetFileAttributesW(const WCHAR *name);
/* droiddeck-game-env recognises a swapped-in copy by this text. */
__attribute__((used)) const char dirtfix_marker[] = "droiddeck-dirt-ws2_32";
extern const unsigned short dirtfix_ordinals[];
extern const unsigned int dirtfix_count;
extern void *dirtfix_real[];
static int (WINAPI *real_sendto)(UINT_PTR, const char *, int, int, const void *, int);
static int (WINAPI *real_WSAGetLastError)(void);
static void (WINAPI *real_WSASetLastError)(int);
int WINAPI dirtfix_sendto(UINT_PTR s, const char *buf, int len, int flags, const void *to, int tolen)
{
int ret = real_sendto(s, buf, len, flags, to, tolen);
if (ret == -1 && real_WSAGetLastError() == WSAENOTSOCK)
{
real_WSASetLastError(0);
return 0;
}
return ret;
}
static void append(WCHAR *dst, const char *src)
{
while (*dst) dst++;
while ((*dst++ = (WCHAR)(unsigned char)*src++));
}
static void append_number(WCHAR *dst, UINT n)
{
char digits[12];
int i = 11;
digits[i] = 0;
do digits[--i] = (char)('0' + n % 10); while (n /= 10);
append(dst, digits + i);
}
/* When this file replaces the prefix's syswow64\ws2_32.dll, Wine's own copy is the i386-windows\ws2_32.dll in one
* of the builtin DLL folders Wine lists in WINEDLLDIR0, WINEDLLDIR1, ... as NT paths (\??\Z:\...). */
static HMODULE load_wine_ws2_32(HMODULE self)
{
WCHAR name[24], path[600];
HMODULE real;
UINT n, d;
for (d = 0; d < 16; d++)
{
name[0] = 0;
append(name, "WINEDLLDIR");
append_number(name, d);
n = GetEnvironmentVariableW(name, path, 500);
if (!n || n >= 500) continue;
if (path[0] == '\\' && path[1] == '?' && path[2] == '?' && path[3] == '\\') path[1] = '\\';
append(path, "\\i386-windows\\ws2_32.dll");
if (GetFileAttributesW(path) == (DWORD)-1) continue;
if ((real = LoadLibraryW(path)) && real != self) return real;
}
n = GetSystemDirectoryW(path, 280);
if (!n || n >= 280) return 0;
path[n] = 0;
append(path, "\\ws2_32.dll");
real = LoadLibraryW(path);
return real != self ? real : 0;
}
BOOL WINAPI DllMain(HMODULE self, DWORD reason, void *reserved)
{
HMODULE real;
UINT i;
(void)reserved;
if (reason != 1) return 1;
if (!(real = load_wine_ws2_32(self))) return 0;
for (i = 0; i < dirtfix_count; i++) dirtfix_real[i] = GetProcAddress(real, ORDINAL(dirtfix_ordinals[i]));
real_sendto = GetProcAddress(real, ORDINAL(20));
real_WSAGetLastError = GetProcAddress(real, ORDINAL(111));
real_WSASetLastError = GetProcAddress(real, ORDINAL(112));
return real_sendto && real_WSAGetLastError && real_WSASetLastError;
}
@@ -1,7 +1,15 @@
#!/usr/bin/python3
import json
import os
import re
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
import urllib.parse
os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/droiddeck-bwrap")
@@ -11,6 +19,22 @@ gi.require_version("Flatpak", "1.0")
from gi.repository import Flatpak, Gio, GLib
REMOTE = "flathub"
SYSTEM_BUS = "/run/dbus/system_bus_socket"
BUS_COMMANDS = ("install", "install-bundle", "uninstall", "update", "prune")
BUS_CONFIG = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>system</type>
<listen>unix:path=%s</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow user="*"/>
<allow own="*"/>
<allow send_destination="*"/>
<allow receive_sender="*"/>
</policy>
</busconfig>
"""
def prepare_rootfs():
@@ -33,6 +57,116 @@ def prepare_rootfs():
emit(e="warning", message="could not prepare %s: %s" % (target, err))
def bus_reachable(path):
if isinstance(path, tuple):
try:
socket.create_connection(path, timeout=1).close()
return True
except (OSError, ValueError):
return False
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.connect(path)
return True
except OSError:
return False
finally:
sock.close()
def system_bus_paths():
address = os.environ.get("DBUS_SYSTEM_BUS_ADDRESS", "")
if not address:
return [SYSTEM_BUS]
paths = []
for entry in filter(None, address.split(";")):
found = None
kind, _, params = entry.partition(":")
values = dict(part.partition("=")[::2] for part in params.split(","))
if kind == "unix":
if values.get("path"):
found = urllib.parse.unquote_to_bytes(values["path"])
elif values.get("abstract"):
found = b"\0" + urllib.parse.unquote_to_bytes(values["abstract"])
elif kind == "tcp":
port = urllib.parse.unquote(values.get("port", ""))
digits = port.lstrip("0")
if not re.fullmatch(r"[0-9]+", port, re.ASCII) or not 0 < len(digits) <= 5 or int(digits) > 65535:
continue
found = (urllib.parse.unquote(values.get("host", "localhost")), int(digits))
if found is None:
return None
paths.append(found)
return paths
def system_bus_reachable():
paths = system_bus_paths()
return paths is None or any(bus_reachable(path) for path in paths)
def stop_system_bus(bus):
if not bus:
return
proc, work, conf, path = bus
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
remove_bus_files(work, conf, path)
def remove_bus_files(work, conf, path):
for name in (path, conf):
try:
os.unlink(name)
except OSError:
pass
try:
os.rmdir(work)
except OSError:
pass
def private_system_bus():
if system_bus_reachable():
return None
daemon = shutil.which("dbus-daemon")
if not daemon:
emit(e="warning", message="no system bus and no dbus-daemon to start one")
return None
try:
work = tempfile.mkdtemp(prefix="droiddeck-flatpak-bus-")
except OSError as err:
emit(e="warning", message="could not start a private system bus: %s" % err)
return None
conf = os.path.join(work, "bus.conf")
path = os.path.join(work, "bus")
try:
with open(conf, "w") as f:
f.write(BUS_CONFIG % path)
proc = subprocess.Popen([daemon, "--config-file=" + conf, "--nofork", "--nopidfile"],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError as err:
remove_bus_files(work, conf, path)
emit(e="warning", message="could not start a private system bus: %s" % err)
return None
bus = (proc, work, conf, path)
for _ in range(50):
if bus_reachable(path) or proc.poll() is not None:
break
time.sleep(0.1)
if not bus_reachable(path):
stop_system_bus(bus)
emit(e="warning", message="the private system bus did not start")
return None
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "unix:path=" + path
return bus
def emit(**kw):
sys.stdout.write(json.dumps(kw) + "\n")
sys.stdout.flush()
@@ -257,6 +391,16 @@ def main():
cmd, args = sys.argv[1], sys.argv[2:]
if cmd in ("install", "install-bundle", "update"):
prepare_rootfs()
bus = private_system_bus() if cmd in BUS_COMMANDS else None
if bus:
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(128 + signum))
try:
return command(cmd, args)
finally:
stop_system_bus(bus)
def command(cmd, args):
if cmd == "install" and args:
return install(args[0])
if cmd == "install-bundle" and args:
@@ -4,6 +4,7 @@ import json
import os
import re
import runpy
import signal
import subprocess
import sys
import tempfile
@@ -142,6 +143,12 @@ def protonfixes_off(game):
return {"PROTONFIXES_DISABLE": "1"}, [], "umu-protonfixes off (its ALSA audio and VC++ installer steps fail here)"
@fix
def little_nightmares_threads(game):
if game.stem == "littlenightmares":
return {"PROTONFIXES_DISABLE": "1"}, [], "Little Nightmares: umu-protonfixes off (its -onethread puts the game and renderer on one thread)"
@fix
def caravan_sandwitch_feature_level(game):
if "caravansandwitch.exe" in game.files or game.stem == "caravansandwitch-win64-shipping":
@@ -743,7 +750,202 @@ def directaudio_settings(env):
return env
def start(launch, launch_env, digest):
DIRT_GAMES = {"dirt3_game": "dirt3", "showdown": "dirtshowdown", "showdown_avx": "dirtshowdown"}
DIRT_WS2 = "/usr/local/lib/droiddeck-dirt/ws2_32.dll"
DIRT_MARKER = b"droiddeck-dirt-ws2_32"
DIRT_FIXED = "showdown_avx.exe".encode("utf-16-le")
DIRT_SAVED = ".droiddeck-original"
def dirt_telemetry_on(prefix, game):
"""Whether the game's UDP/motion output is on, as In-game stats or another listener sets it ("dbox" is its default)."""
try:
folders = [f for f in (Path(prefix) / "pfx/drive_c/users/steamuser/Documents/My Games").iterdir()
if f.name.lower().replace(" ", "") == game]
except OSError:
return False
for folder in folders:
try:
text = (folder / "hardwaresettings/hardware_settings_config.xml").read_text(encoding="latin-1")
except OSError:
continue
for tag in ("udp", "motion"):
element = re.search(r"<%s\s[^>]*>" % tag, text)
if element:
attrs = dict(re.findall(r'\s(\w+)="([^"]*)"', element.group(0)))
return attrs.get("enabled") == "true" and attrs.get("ip", "").lower() not in ("", "dbox")
return False
def proton_ws2(proton):
return Path(proton).parent / "files/lib/wine/i386-windows/ws2_32.dll"
def proton_has_dirt_fix(proton):
try:
return DIRT_FIXED in proton_ws2(proton).read_bytes()
except OSError:
return False
WINE_DLL_DIRS = ("/lib/wine/i386-windows", "/lib/wine/x86_64-windows", "/lib/wine/aarch64-windows", "/lib/wine",
"/lib/wine/fakedlls", "/lib64/wine", "/lib64/wine/fakedlls", "/lib64/wine/x86_64-windows")
def is_wine_dll_link(path):
"""A link into a Wine DLL folder: the rule Proton uses to tell its own DLLs in a prefix (file_is_wine_builtin_dll)."""
try:
return os.path.islink(path) and os.path.dirname(os.readlink(path)).endswith(WINE_DLL_DIRS)
except OSError:
return False
def prefix_ws2(prefix):
return Path(prefix) / "pfx/drive_c/windows/syswow64/ws2_32.dll"
def is_dirt_stand_in(path):
try:
return not path.is_symlink() and DIRT_MARKER in path.read_bytes()
except OSError:
return False
def dirt_ws2_wanted(command, env):
"""The prefix to give the ws2_32 stand-in: a DiRT 3 / Showdown launch with telemetry on and a Proton without the fix."""
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if len(command) < 3 or not prefix or not os.path.isfile(DIRT_WS2):
return None
game = DIRT_GAMES.get(os.path.splitext(os.path.basename(command[2]))[0].lower())
if not game or not dirt_telemetry_on(prefix, game) or proton_has_dirt_fix(command[0]):
return None
return prefix if os.path.lexists(prefix_ws2(prefix)) else None
def swap_dirt_ws2(prefix):
"""Puts the stand-in where the prefix's syswow64/ws2_32.dll is; that file is kept beside it."""
target = prefix_ws2(prefix)
saved = target.with_name(target.name + DIRT_SAVED)
data = Path(DIRT_WS2).read_bytes()
if not is_dirt_stand_in(target):
if os.path.lexists(saved):
os.unlink(saved)
os.replace(target, saved)
staged = target.with_name(target.name + ".droiddeck-tmp")
staged.write_bytes(data)
os.replace(staged, target)
def restore_dirt_ws2(prefix, proton):
"""Puts a Wine syswow64/ws2_32.dll back if the stand-in is still there; true when it changed something.
That is the prefix's own one, unless it was a link to a Wine DLL folder and the game ran on another Proton since
the swap: Proton then relinked the prefix's other DLLs to itself but left the stand-in, so a link to the running
Proton's ws2_32.dll goes back instead. Anything else (a native file, a link to a mod's DLL) goes back as it was."""
target = prefix_ws2(prefix)
saved = target.with_name(target.name + DIRT_SAVED)
own = proton_ws2(proton)
had_saved = os.path.lexists(saved)
if had_saved:
if os.path.lexists(target) and not is_dirt_stand_in(target):
os.unlink(saved)
return False
if not own.is_file() or not is_wine_dll_link(saved) or os.path.realpath(saved) == os.path.realpath(own):
os.replace(saved, target)
return True
os.unlink(saved)
if own.is_file() and (is_dirt_stand_in(target) or (had_saved and not os.path.lexists(target))):
link = target.with_name(target.name + ".droiddeck-tmp")
if os.path.lexists(link):
os.unlink(link)
os.symlink(own, link)
os.replace(link, target)
return True
return False
EGO_RESTRICTIONS = "system/hardware_settings_restrictions.xml"
EGO_CORE_RULE = re.compile(r'[ \t]*<restrict_if name="cores" op="(int_[a-z]+)" value="(\d+)">.*?</restrict_if>[ \t]*\r?\n', re.S)
EGO_OPS = {"int_eq": int.__eq__, "int_ne": int.__ne__, "int_ge": int.__ge__, "int_gt": int.__gt__,
"int_le": int.__le__, "int_lt": int.__lt__}
def windows_core_count(env):
count = (env.get("WINE_CPU_TOPOLOGY") or "").split(":", 1)[0]
return int(count) if count.isascii() and count.isdigit() and int(count) > 0 else None
def ego_core_plan(command, env):
"""Codemasters EGO games (DiRT 3, DiRT Showdown, GRID, F1 ...) pick their thread plan by core count from
system/hardware_settings_restrictions.xml. A count with no plan (5 when a phone's slow cores are left out) puts
every worker on one core, and DiRT 3 then stops on a loading screen. Adds a plan for the count Windows sees,
copied from the nearest smaller one; the file as it was is kept beside it. Returns a note, or None."""
count = windows_core_count(env)
if not count or len(command) < 3:
return None
folder = Path(command[2]).parent
path = folder / EGO_RESTRICTIONS
try:
raw = path.read_bytes()
except OSError:
return None
text = raw.decode("latin-1")
start, end = text.find("<cpu>"), text.find("</cpu>")
if start < 0 or end < start:
return None
rules = list(EGO_CORE_RULE.finditer(text, start, end))
if not rules or any(EGO_OPS.get(rule.group(1), lambda a, b: True)(count, int(rule.group(2))) for rule in rules):
return None
smaller = [rule for rule in rules if rule.group(1) == "int_eq" and int(rule.group(2)) < count]
if not smaller:
return None
source = max(smaller, key=lambda rule: int(rule.group(2)))
worker_map = re.search(r'workerMapFile="([^"]+)"', source.group(0))
if worker_map and not (folder / worker_map.group(1)).is_file():
return None
plan = source.group(0).replace('value="%s"' % source.group(2), 'value="%d"' % count, 1)
saved = path.with_name(path.name + DIRT_SAVED)
if not os.path.lexists(saved):
saved.write_bytes(raw)
handle, staged = tempfile.mkstemp(prefix=path.name + ".", suffix=".droiddeck-tmp", dir=str(path.parent))
try:
with os.fdopen(handle, "wb") as out:
out.write((text[:source.end()] + plan + text[source.end():]).encode("latin-1"))
os.replace(staged, path)
except BaseException:
if os.path.lexists(staged):
os.unlink(staged)
raise
return "%s had no thread plan for %d cores; added a copy of its %s-core plan" % (EGO_RESTRICTIONS, count, source.group(2))
def wait_forwarding_signals(process):
def forward(signum, frame):
try:
process.send_signal(signum)
except OSError:
pass
previous = {signum: signal.signal(signum, forward) for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)}
try:
code = process.wait()
finally:
for signum, handler in previous.items():
signal.signal(signum, handler)
return 128 - code if code < 0 else code
def start(launch, launch_env, digest, after=None):
if after:
process = subprocess.Popen(launch, env=launch_env)
try:
return wait_forwarding_signals(process)
finally:
try:
after()
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); the next launch does it" % error,
file=sys.stderr)
if digest:
code = subprocess.run(launch, env=launch_env, check=False).returncode
if code == 0:
@@ -768,6 +970,7 @@ def main():
except OSError:
digest = None
app_id = game_id(env)
dirt_prefix = None
if app_id:
gl_default = gl_vsync(env)
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
@@ -787,6 +990,10 @@ def main():
if components:
own = fixes.get("WINEDLLOVERRIDES")
fixes["WINEDLLOVERRIDES"] = components + ";" + own if own else components
dirt_prefix = dirt_ws2_wanted(command, env)
if dirt_prefix:
own = fixes.get("WINEDLLOVERRIDES")
fixes["WINEDLLOVERRIDES"] = own + ";ws2_32=n,b" if own else "ws2_32=n,b"
path = Path.home() / ".config/droiddeck/game-environment.json"
config = {}
try:
@@ -822,6 +1029,13 @@ def main():
env = force_ssbs(command, env)
game_cores(env)
cpu_topology(env, command)
if app_id and len(command) > 2 and command[1] == "waitforexitandrun":
try:
note = ego_core_plan(command, env)
except OSError as error:
note = "no thread plan added for this core count (%s)" % error
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
try:
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
except Exception as error:
@@ -834,16 +1048,45 @@ def main():
return 1
if xbox_result is not None:
return xbox_result
after = None
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if app_id and prefix and len(command) > 1 and command[1] == "waitforexitandrun":
try:
if dirt_prefix:
after = lambda: restore_dirt_ws2(dirt_prefix, command[0])
swap_dirt_ws2(dirt_prefix)
print("droiddeck-game-env: DiRT telemetry fix: ws2_32 stand-in in the prefix until the game exits",
file=sys.stderr)
elif restore_dirt_ws2(prefix, command[0]):
print("droiddeck-game-env: DiRT telemetry fix: put the prefix's own ws2_32 back", file=sys.stderr)
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix not applied (%s)" % error, file=sys.stderr)
if after:
after = None
try:
restore_dirt_ws2(dirt_prefix, command[0])
except OSError as undo:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); Wine uses its own copy "
"and the next launch puts the file back" % undo, file=sys.stderr)
sync = load_sync()
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
try:
return start(launch, launch_env, digest)
return start(launch, launch_env, digest, after)
except OSError as error:
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
launch, launch_env = command, without_pack(launch_env, env)
record_stock(sync, launch, launch_env)
return start(launch, launch_env, digest)
try:
return start(launch, launch_env, digest, after)
except OSError:
if after:
try:
after()
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); the next launch does it" % error,
file=sys.stderr)
raise
if __name__ == "__main__":
@@ -623,7 +623,7 @@ case $mode in
fi
if [ "${BL_ZRAM:-0}" = 1 ]; then
step "zRAM compression: on"
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam and the hidden Epic Games Launcher are not compressed while games run (turned off in Performance)"
[ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam, the hidden Epic Games Launcher and Battle.net are not compressed while games run (turned off in Performance)"
_bl_ram_cap=0
case ${BL_RAM_CAP_MB:-} in
''|0) ;;
@@ -633,7 +633,7 @@ case $mode in
(
bl_zram_scan() {
_bl_game=0 _bl_pids=() _bl_others=() _bl_apps=
local _d _c _args _name _a _id _fex
local _d _c _args _name _a _id _fex _lower _bnet=() _bnet_game=0
for _d in /proc/[0-9]*; do
[ "${_d##*/}" != "$BASHPID" ] || continue
_args=()
@@ -658,14 +658,34 @@ case $mode in
;;
steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;;
*)
_lower=${_name,,}
if [ "$_fex" = 1 ] && grep -qz '^DROIDDECK_EPIC_HIDDEN=1$' "$_d/environ" 2>/dev/null; then
_bl_pids+=("${_d##*/}")
elif [[ $_lower == [a-z]:[\\/]'program files (x86)'[\\/]battle.net[\\/]* ||
$_lower == [a-z]:[\\/]programdata[\\/]battle.net[\\/]* ]]; then
_bnet+=("${_d##*/}")
else
_bl_others+=("${_d##*/}")
if [[ $_lower == [a-z]:[\\/]* ]]; then
case ${_lower##*[\\/]} in
agent.exe|conhost.exe|explorer.exe|lsass.exe|plugplay.exe|rpcss.exe|services.exe|start.exe|\
steam.exe|svchost.exe|tabtip.exe|winedevice.exe|rundll32.exe|wineboot.exe|winemenubuilder.exe) ;;
*)
for _a in "${_args[@]:1}"; do
[ "${_a,,}" = -uid ] && _bnet_game=1
done
;;
esac
fi
fi
;;
esac
done
if [ "$_bnet_game" = 1 ]; then
_bl_pids+=("${_bnet[@]}")
else
_bl_others+=("${_bnet[@]}")
fi
}
bl_zram_usage() {
local _p _k _v _u _rss=0 _swap=0
@@ -20,6 +20,7 @@ LIBRARY = "/mnt/droiddeck-sd"
LEGACY_LIBRARY = "/mnt/bannerlator-sd"
PARKED = ".droiddeck-parked"
BASE_ID = 76561197960265728
SPACEWAR = 480
def read_json(path, default):
@@ -86,14 +87,14 @@ def identify(game):
folder = Path(game["folder"])
steamapps = folder.parent.parent
for library in ([steamapps] if folder.parent.name == "common" and steamapps.name == "steamapps" else []) + [folder.parent / WINNATIVE]:
matches = manifest_ids(library, folder.name)
matches = [appid for appid in manifest_ids(library, folder.name) if appid != SPACEWAR]
if matches:
return matches[0] if len(matches) == 1 else None
ids = set()
for parent in {folder, Path(game["exe"]).parent}:
try:
appid = int((parent / "steam_appid.txt").read_text().strip())
if 0 < appid < 0x80000000:
if 0 < appid < 0x80000000 and appid != SPACEWAR:
ids.add(appid)
except (OSError, ValueError):
pass
@@ -107,7 +108,7 @@ def identify(game):
ids = {int(item["id"]) for item in items
if key(item.get("name", "")) == key(game["name"]) and key(game["name"])}
if ids:
return next(iter(ids)) if len(ids) == 1 else None
return next(iter(ids)) if len(ids) == 1 and SPACEWAR not in ids else None
return None
except (OSError, ValueError, KeyError):
return None
@@ -423,20 +424,20 @@ def seed_install(steam_root, game, appid):
return True
def release(steam_root, game):
"""Undoes an import made before store games were skipped. Only our symlink and manifest go;
the store's folder stays where it is."""
def release(steam_root, game, stale, reason):
"""Undoes the imports of the game's folder as the Steam apps [stale] picks. Only our symlink and
manifest go; the folder stays where it is."""
steamapps = Path(steam_root) / "steamapps"
sources = {game.get("folder", ""), legacy_path(game.get("folder", ""))}
for target in sorted((steamapps / "common").glob("DroidDeck-*")):
appid = target.name.removeprefix("DroidDeck-")
if not (appid.isdigit() and target.is_symlink() and os.readlink(target) in sources):
if not (appid.isdigit() and target.is_symlink() and os.readlink(target) in sources and stale(int(appid))):
continue
for manifest in (steamapps / f"appmanifest_{appid}.acf", steamapps / PARKED / f"appmanifest_{appid}.acf"):
if manifest.is_file() and ours(manifest, appid):
manifest.unlink()
target.unlink()
print(f"droiddeck-steam-games: {game.get('name', appid)} came from {game['store']}; it is a shortcut again, not Steam app {appid}")
print(f"droiddeck-steam-games: {game.get('name', appid)} {reason}; it is no longer Steam app {appid}")
def route(steam_root, acct, games):
@@ -457,7 +458,7 @@ def route(steam_root, acct, games):
for game in games:
if store_game(game):
try:
release(steam_root, game)
release(steam_root, game, lambda old: True, f"came from {game['store']}")
except OSError as error:
print(f"droiddeck-steam-games: store import not undone ({error})")
shortcuts.append(game)
@@ -469,9 +470,14 @@ def route(steam_root, acct, games):
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
stamp = source_stamp(game)
recorded = sources.get(folder, sources.get(legacy_path(folder)))
confirmed = (isinstance(appid, int) and 0 < appid < 0x80000000
and owned.get(str(appid)) is True and stamp is not None
and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:]))
current = stamp is not None and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:])
named = isinstance(appid, int) and 0 < appid < 0x80000000 and appid != SPACEWAR
try:
release(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid),
"names another Steam app now")
except OSError as error:
print(f"droiddeck-steam-games: earlier import not undone ({error})")
confirmed = named and current and owned.get(str(appid)) is True
if confirmed:
try:
if seed_install(steam_root, game, appid):
@@ -480,7 +486,7 @@ def route(steam_root, acct, games):
print(f"droiddeck-steam-games: {game.get('name', appid)} stays a shortcut this session: it could not be linked as Steam app {appid}")
except OSError as error:
print(f"droiddeck-steam-games: import unavailable ({error})")
elif isinstance(appid, int) and 0 < appid < 0x80000000 and seeded(steamapps, game, appid):
elif named and seeded(steamapps, game, appid):
routes[str(game["appid"])] = appid
continue
shortcuts.append(game)
+2 -1
View File
@@ -23,7 +23,8 @@ while IFS= read -r dir; do
done < <(ls -d "${sdk_dir}"/build-tools/* 2>/dev/null | sort -rV)
[[ -n "${build_tools}" ]] || { echo "No build-tools with aapt, zipalign and apksigner under ${sdk_dir}." >&2; exit 1; }
./gradlew -q :app:assembleRelease
# Runtime assets from another branch are fine for a Kotlin/UI loop; CI and releases stay strict.
./gradlew -q -PallowStaleRuntime=true :app:assembleRelease
(
cd "$(dirname "${signing_env}")"
set -a; . "${signing_env}"; set +a
+12 -4
View File
@@ -23,7 +23,7 @@ PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler']
SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst',
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
'app/src/main/cpp/waylandcomp/src/headpose_shm.h',
@@ -149,13 +149,21 @@ def record(root=ROOT):
(root / MANIFEST).write_text(json.dumps(data, sort_keys=True, indent=2) + '\n')
def verify(root=ROOT):
def verify(root=ROOT, stale_sources_ok=False):
try:
data = json.loads((root / MANIFEST).read_text())
except (OSError, ValueError):
raise ValueError('Runtime inputs have not been prepared. Run tools/build_local.sh.')
if data.get('version') != 1 or data.get('sources') != sources(root):
if data.get('version') != 1:
raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.')
current = sources(root)
if data.get('sources') != current:
if not stale_sources_ok:
raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.')
recorded = data.get('sources') or {}
changed = sorted(name for name in recorded.keys() | current.keys() if recorded.get(name) != current.get(name))
print('Warning: reusing runtime assets prepared from other sources (run tools/build_local.sh if these matter):\n '
+ '\n '.join(changed[:20]) + ('\n ...' if len(changed) > 20 else ''), file=sys.stderr)
for name in required():
if name not in data['outputs']:
raise ValueError('Runtime manifest missing ' + name)
@@ -224,7 +232,7 @@ if __name__ == '__main__':
if sys.argv[1] == 'record':
record()
elif sys.argv[1] == 'verify':
verify()
verify(stale_sources_ok='--allow-stale-sources' in sys.argv[2:])
elif sys.argv[1] == 'apk':
check_apk(sys.argv[2])
else:
+64
View File
@@ -0,0 +1,64 @@
#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);
/* A hotspot that pushes the image across the seam must not move the mirror to the
* other eye: the pointer decides the eye, the hotspot only shifts the image. */
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);
/* Each copy is cropped to its own eye, so nothing bleeds into the other eye's half. */
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;
}
+35
View File
@@ -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')
+54
View File
@@ -0,0 +1,54 @@
"""Exercise the compositor's real cursor placement rule for glasses output."""
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()
+199
View File
@@ -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()
+311
View File
@@ -29,6 +29,311 @@ def config_text(entries):
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
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):
"""DiRT 3's restrictions as shipped: plans for 2, 3, 4, 6 and 8+ cores, one core for anything else."""
@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:
@@ -593,6 +898,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})
+13
View File
@@ -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)
+70
View File
@@ -391,6 +391,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 +454,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),