mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 12:56:06 +00:00
Merge remote-tracking branch 'droiddeck/main' into HEAD
# Conflicts: # tools/linuxfs/overlay/usr/local/bin/droiddeck-fex # tools/tests/test_droiddeck_fex.py
This commit is contained in:
commit
b36e5425d7
227 files changed
+12088
-1987
No files matched your search
@@ -113,11 +113,10 @@ if [ ! -d "$ANDROID_HOME/platforms/android-34" ]; then
|
||||
"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" "platforms;android-34" "build-tools;35.0.0" >/dev/null
|
||||
fi
|
||||
|
||||
# A full Kotlin compile of the app needs about 2.5 GB of heap and Gradle about 1 GB; smaller devices get
|
||||
# what they can spare. Both daemons end with this script's process when the build is done.
|
||||
total_mb=$(awk '/^MemTotal:/ {print int($2 / 1024)}' /proc/meminfo)
|
||||
heap=$(( total_mb / 2 )); [ $heap -gt 4096 ] && heap=4096; [ $heap -lt 2048 ] && heap=2048
|
||||
heap=${DD_LAB_HEAP_MB:-$heap}
|
||||
# A full Kotlin compile of the app runs out of memory with 2.4 GB of heap, and Gradle needs about 1 GB,
|
||||
# so devices with less memory to spare swap rather than fail. Both daemons end with this script's
|
||||
# process when the build is done.
|
||||
heap=${DD_LAB_HEAP_MB:-4096}
|
||||
kotlin_heap=$(( heap * 2 / 3 )); gradle_heap=$(( heap - kotlin_heap ))
|
||||
|
||||
# Only the Kotlin daemon compiles incrementally; in-process compiles always redo the whole app, and the
|
||||
|
||||
@@ -65,6 +65,7 @@ PA_MODULE_USAGE(
|
||||
#define DA_RING_CAP_MS_LOCAL 250
|
||||
#define DA_FREEZE_GAP_NS 500000000ull
|
||||
#define DA_CB_STALL_NS 1000000000ull
|
||||
#define DA_HOST_RESTART_STALLS 3
|
||||
#define DA_DECAY_QUIET_NS 10000000000ull
|
||||
#define DA_DECAY_PUNISH_NS 5000000000ull
|
||||
#define DA_DECAY_MAX_BACKOFF 32
|
||||
@@ -106,6 +107,7 @@ struct userdata {
|
||||
uint64_t last_cb_ns, last_xrun_ns, last_decay_ns, wd_last_tick_ns;
|
||||
int32_t base_buf_frames, decay_floor;
|
||||
unsigned int decay_backoff, cb_count, wd_last_cb;
|
||||
uint64_t stall_state;
|
||||
int reopen_running, reopen_redo;
|
||||
int consuming, primed, starved;
|
||||
int suspended;
|
||||
@@ -154,6 +156,13 @@ static void limit(float *p, uint32_t samples) {
|
||||
}
|
||||
}
|
||||
|
||||
static void record_callback(struct userdata *u) {
|
||||
uint64_t state = __atomic_load_n(&u->stall_state, __ATOMIC_SEQ_CST);
|
||||
|
||||
while (!__atomic_compare_exchange_n(&u->stall_state, &state,
|
||||
((state >> 32) + 1) << 32, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {}
|
||||
}
|
||||
|
||||
static aaudio_data_callback_result_t out_cb(AAudioStream *aq, void *user, void *audioData, int32_t numFrames) {
|
||||
struct userdata *u = user;
|
||||
struct da_ring *r = u->ring;
|
||||
@@ -170,6 +179,8 @@ static aaudio_data_callback_result_t out_cb(AAudioStream *aq, void *user, void *
|
||||
return AAUDIO_CALLBACK_RESULT_CONTINUE;
|
||||
}
|
||||
|
||||
record_callback(u);
|
||||
|
||||
ridx = __atomic_load_n(&r->ridx, __ATOMIC_ACQUIRE);
|
||||
avail = __atomic_load_n(&r->widx, __ATOMIC_ACQUIRE) - ridx;
|
||||
if (!u->primed) {
|
||||
@@ -412,10 +423,12 @@ static void request_reopen(struct userdata *u, const char *why) {
|
||||
static void watchdog(struct userdata *u) {
|
||||
uint64_t now = now_ns(), last_cb, prev_tick;
|
||||
unsigned int cb;
|
||||
uint64_t stalled;
|
||||
|
||||
if (!u->watchdog_on) return;
|
||||
if (!__atomic_load_n(&u->aq, __ATOMIC_SEQ_CST)) return;
|
||||
|
||||
stalled = __atomic_load_n(&u->stall_state, __ATOMIC_SEQ_CST);
|
||||
prev_tick = u->wd_last_tick_ns;
|
||||
u->wd_last_tick_ns = now;
|
||||
cb = __atomic_load_n(&u->cb_count, __ATOMIC_SEQ_CST);
|
||||
@@ -431,6 +444,13 @@ static void watchdog(struct userdata *u) {
|
||||
if (!last_cb || now - last_cb < DA_CB_STALL_NS) return;
|
||||
|
||||
__atomic_store_n(&u->last_cb_ns, now, __ATOMIC_SEQ_CST);
|
||||
if (__atomic_load_n(&u->cb_count, __ATOMIC_SEQ_CST) != cb) return;
|
||||
if (!__atomic_compare_exchange_n(&u->stall_state, &stalled, stalled + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) return;
|
||||
if ((uint32_t) (stalled + 1) >= DA_HOST_RESTART_STALLS) {
|
||||
pa_log("directaudio-native-sink: no data callback after %u stream recoveries; restarting the audio host", (unsigned int) (stalled + 1));
|
||||
_exit(EXIT_FAILURE);
|
||||
return;
|
||||
}
|
||||
request_reopen(u, "data callback stalled");
|
||||
}
|
||||
|
||||
|
||||
+232
-4
@@ -67,10 +67,11 @@ def adb_path(configured: str | None) -> str:
|
||||
raise ControlError("adb not found; set ADB, ANDROID_HOME, or ANDROID_SDK_ROOT", "ADB_NOT_FOUND")
|
||||
|
||||
|
||||
def run_adb(adb: str, serial: str, *args: str, timeout: float = 30) -> subprocess.CompletedProcess[bytes]:
|
||||
def run_adb(adb: str, serial: str, *args: str, timeout: float = 30,
|
||||
stdin: bytes | None = None) -> subprocess.CompletedProcess[bytes]:
|
||||
try:
|
||||
return subprocess.run(
|
||||
[adb, "-s", serial, *args], capture_output=True, check=False, timeout=timeout
|
||||
[adb, "-s", serial, *args], input=stdin, capture_output=True, check=False, timeout=timeout
|
||||
)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
raise ControlError(str(exc), "ADB_FAILED") from exc
|
||||
@@ -287,7 +288,9 @@ def displays(adb: str, serial: str) -> list[dict]:
|
||||
|
||||
def physical_display(adb: str, serial: str, logical: int | None) -> str | None:
|
||||
if logical is None:
|
||||
return None
|
||||
found = displays(adb, serial)
|
||||
main = next((d["physicalId"] for d in found if d["display"] == 0), None)
|
||||
return main if len(found) > 1 else None
|
||||
for d in displays(adb, serial):
|
||||
if d["display"] == logical:
|
||||
if not d["physicalId"]:
|
||||
@@ -596,6 +599,199 @@ def input_request(args: argparse.Namespace) -> dict:
|
||||
raise ControlError(f"Unknown input type {kind}", "INVALID_INPUT")
|
||||
|
||||
|
||||
PEN_MAX_MS = 30_000
|
||||
UINPUT_SCALE = 16
|
||||
UINPUT_PRESSURE = 4095
|
||||
UINPUT_DISTANCE = 255
|
||||
UINPUT_REGISTER_MS = 1000
|
||||
UINPUT_TAIL_MS = 300
|
||||
UINPUT_SYNC = "droiddeckctl-pen-done"
|
||||
|
||||
|
||||
def pen_span(value: str) -> tuple[float, float]:
|
||||
try:
|
||||
low, high = map(float, value.split(":")) if ":" in value else (float(value),) * 2
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError(f"{value!r} is not a number or FROM:TO") from None
|
||||
return low, high
|
||||
|
||||
|
||||
def pen_times(start: float, duration: float, rate: float) -> list[float]:
|
||||
steps = max(1, round(duration * rate / 1000))
|
||||
return [start + duration * i / steps for i in range(steps + 1)]
|
||||
|
||||
|
||||
def pen_lerp(span: tuple[float, float], fraction: float) -> float:
|
||||
return span[0] + (span[1] - span[0]) * fraction
|
||||
|
||||
|
||||
def pen_samples(args: argparse.Namespace) -> list[dict]:
|
||||
op = args.pen_op
|
||||
contact = op in ("tap", "stroke")
|
||||
side = args.button if op == "button" else None
|
||||
lead = 0 if op == "hover" else args.hover_ms
|
||||
length = args.duration if op in ("hover", "stroke") else args.hold
|
||||
total = 2 * lead + length
|
||||
start = end = (args.x, args.y)
|
||||
if op == "stroke":
|
||||
end = (args.x2, args.y2)
|
||||
elif op == "hover" and args.to:
|
||||
end = tuple(args.to)
|
||||
for name in ("duration", "hold", "hover_ms"):
|
||||
if getattr(args, name, 0) < 0:
|
||||
raise ControlError(f"--{name.replace('_', '-')} must not be negative", "INVALID_INPUT")
|
||||
if not 1 <= args.rate <= 1000:
|
||||
raise ControlError("--rate must be 1..1000 Hz", "INVALID_INPUT")
|
||||
if total > PEN_MAX_MS:
|
||||
raise ControlError(f"The gesture lasts {total} ms, more than {PEN_MAX_MS}", "INVALID_INPUT")
|
||||
if not all(0 <= v <= 1 for v in start + end):
|
||||
raise ControlError("Positions are fractions of the screen, 0..1", "INVALID_INPUT")
|
||||
if contact and not all(0 <= p <= 1 for p in args.pressure):
|
||||
raise ControlError("--pressure must be 0..1", "INVALID_INPUT")
|
||||
if not all(-90 <= a <= 90 for a in args.tilt_x + args.tilt_y):
|
||||
raise ControlError("--tilt-x and --tilt-y must be -90..90", "INVALID_INPUT")
|
||||
if not 0 <= args.distance <= UINPUT_DISTANCE:
|
||||
raise ControlError(f"--distance must be 0..{UINPUT_DISTANCE}", "INVALID_INPUT")
|
||||
samples = []
|
||||
|
||||
def add(t: float, phase: str, x: float, y: float, pressure: float = 0.0, button: str | None = None) -> None:
|
||||
progress = t / (total or 1)
|
||||
samples.append({"t": round(t), "phase": phase, "x": x, "y": y, "pressure": pressure, "button": button,
|
||||
"distance": args.distance, "tilt_x": pen_lerp(args.tilt_x, progress),
|
||||
"tilt_y": pen_lerp(args.tilt_y, progress)})
|
||||
|
||||
if lead:
|
||||
for t in pen_times(0, lead, args.rate)[:-1]:
|
||||
add(t, "hover", *start)
|
||||
middle = pen_times(lead, length, args.rate)
|
||||
steps = len(middle) - 1
|
||||
for i, t in enumerate(middle):
|
||||
f = i / steps
|
||||
x, y = pen_lerp((start[0], end[0]), f), pen_lerp((start[1], end[1]), f)
|
||||
if contact:
|
||||
add(t, "down" if i == 0 else "up" if i == steps else "move", x, y, pen_lerp(args.pressure, f))
|
||||
else:
|
||||
add(t, "hover", x, y, button=None if i == steps else side)
|
||||
if lead:
|
||||
for t in pen_times(lead + length, lead, args.rate)[1:]:
|
||||
add(t, "hover", *end)
|
||||
add(total, "out", *end)
|
||||
return samples
|
||||
|
||||
|
||||
def input_viewport(dump: str) -> dict:
|
||||
blocks = re.findall(r"^[ \t]*Viewports:\n((?:[ \t]+Viewport .*\n?)+)", dump, re.M)
|
||||
viewports = []
|
||||
for line in re.findall(r"Viewport INTERNAL: (.*)", blocks[-1] if blocks else dump):
|
||||
fields = dict(re.findall(r"(\w+)=(\[[^\]]*\]|[^,\s]+)", line))
|
||||
size = re.fullmatch(r"\[(\d+), (\d+)\]", fields.get("deviceSize", ""))
|
||||
frame = re.fullmatch(r"\[(-?\d+), (-?\d+), (-?\d+), (-?\d+)\]", fields.get("physicalFrame", ""))
|
||||
if size and frame and re.fullmatch(r"-?\d+", fields.get("displayId", "")) and fields.get("orientation") in ("0", "1", "2", "3"):
|
||||
viewports.append({"display": int(fields["displayId"]), "rotation": int(fields["orientation"]),
|
||||
"size": [int(size.group(1)), int(size.group(2))],
|
||||
"frame": [int(edge) for edge in frame.groups()], "active": fields.get("isActive") != "[0]"})
|
||||
if not viewports:
|
||||
raise ControlError("`dumpsys input` shows no internal display viewport to map the pen to", "NO_VIEWPORT")
|
||||
viewport = next((v for v in viewports if v["display"] == 0), viewports[0])
|
||||
if not viewport["active"]:
|
||||
raise ControlError(f"Display {viewport['display']} is off, and Android ignores touchscreens on it; "
|
||||
"wake the device first", "NO_VIEWPORT")
|
||||
return viewport
|
||||
|
||||
|
||||
def uinput_point(x: float, y: float, tilt_x: float, tilt_y: float, rotation: int, width: int,
|
||||
height: int, frame: list[int]) -> tuple[int, int, int, int]:
|
||||
left, top, right, bottom = frame
|
||||
x = min(right - 1, round(left + x * (right - left)))
|
||||
y = min(bottom - 1, round(top + y * (bottom - top)))
|
||||
if rotation == 1:
|
||||
return width - 1 - y, x, round(-tilt_y), round(tilt_x)
|
||||
if rotation == 2:
|
||||
return width - 1 - x, height - 1 - y, round(-tilt_x), round(-tilt_y)
|
||||
if rotation == 3:
|
||||
return y, height - 1 - x, round(tilt_y), round(-tilt_x)
|
||||
return x, y, round(tilt_x), round(tilt_y)
|
||||
|
||||
|
||||
def uinput_commands(samples: list[dict], tool: str, viewport: dict) -> list[dict]:
|
||||
rotation = viewport["rotation"]
|
||||
natural = viewport["size"][::-1] if rotation % 2 else viewport["size"]
|
||||
width, height = (n * UINPUT_SCALE for n in natural)
|
||||
bounds = [edge * UINPUT_SCALE for edge in viewport["frame"]]
|
||||
last_x = max(uinput_point(f, f, 0, 0, rotation, width, height, bounds)[0] for f in (0, 1))
|
||||
tool_key = "BTN_TOOL_RUBBER" if tool == "eraser" else "BTN_TOOL_PEN"
|
||||
|
||||
def axis(code: str, low: int, high: int) -> dict:
|
||||
return {"code": code, "info": {"value": 0, "minimum": low, "maximum": high, "fuzz": 0, "flat": 0, "resolution": 0}}
|
||||
|
||||
commands = [
|
||||
{"id": 1, "command": "register", "name": "DroidDeck agent pen", "bus": "virtual", "configuration": [
|
||||
{"type": "UI_SET_EVBIT", "data": ["EV_KEY", "EV_ABS"]},
|
||||
{"type": "UI_SET_KEYBIT", "data": ["BTN_TOOL_PEN", "BTN_TOOL_RUBBER", "BTN_TOUCH", "BTN_STYLUS", "BTN_STYLUS2"]},
|
||||
{"type": "UI_SET_ABSBIT", "data": ["ABS_X", "ABS_Y", "ABS_PRESSURE", "ABS_DISTANCE", "ABS_TILT_X", "ABS_TILT_Y"]},
|
||||
{"type": "UI_SET_PROPBIT", "data": ["INPUT_PROP_DIRECT"]},
|
||||
], "abs_info": [axis("ABS_X", 0, width - 1), axis("ABS_Y", 0, height - 1), axis("ABS_PRESSURE", 0, UINPUT_PRESSURE),
|
||||
axis("ABS_DISTANCE", 0, UINPUT_DISTANCE), axis("ABS_TILT_X", -90, 90), axis("ABS_TILT_Y", -90, 90)]},
|
||||
{"id": 1, "command": "delay", "duration": UINPUT_REGISTER_MS},
|
||||
]
|
||||
sent = {tool_key: 0, "BTN_TOUCH": 0, "BTN_STYLUS": 0, "BTN_STYLUS2": 0}
|
||||
|
||||
def frame(sample: dict, phase: str) -> list:
|
||||
near, contact = phase != "out", phase in ("down", "move")
|
||||
values = {tool_key: int(near), "BTN_TOUCH": int(contact), "BTN_STYLUS": int(sample["button"] == "primary"),
|
||||
"BTN_STYLUS2": int(sample["button"] == "secondary")}
|
||||
if near:
|
||||
x, y, tilt_x, tilt_y = uinput_point(sample["x"], sample["y"], sample["tilt_x"], sample["tilt_y"],
|
||||
rotation, width, height, bounds)
|
||||
values.update(ABS_X=x, ABS_Y=y, ABS_PRESSURE=max(1, round(sample["pressure"] * UINPUT_PRESSURE)) if contact else 0,
|
||||
ABS_DISTANCE=0 if contact else sample["distance"], ABS_TILT_X=tilt_x, ABS_TILT_Y=tilt_y)
|
||||
events = []
|
||||
for code, value in values.items():
|
||||
if sent.get(code) != value:
|
||||
events += ["EV_KEY" if code.startswith("BTN_") else "EV_ABS", code, value]
|
||||
sent[code] = value
|
||||
return events + ["EV_SYN", "SYN_REPORT", 0] if events else []
|
||||
|
||||
now = 0
|
||||
for sample in samples:
|
||||
events = frame(sample, "move") if sample["phase"] == "up" else []
|
||||
events += frame(sample, sample["phase"])
|
||||
if not events:
|
||||
sent["ABS_X"] += 1 if sent["ABS_X"] < last_x else -1
|
||||
events = ["EV_ABS", "ABS_X", sent["ABS_X"], "EV_SYN", "SYN_REPORT", 0]
|
||||
if sample["t"] > now:
|
||||
commands.append({"id": 1, "command": "delay", "duration": sample["t"] - now})
|
||||
now = sample["t"]
|
||||
commands.append({"id": 1, "command": "inject", "events": events})
|
||||
return commands + [{"id": 1, "command": "delay", "duration": UINPUT_TAIL_MS},
|
||||
{"id": 1, "command": "sync", "syncToken": UINPUT_SYNC}]
|
||||
|
||||
|
||||
def pen_uinput(adb: str, serial: str, samples: list[dict], tool: str) -> dict:
|
||||
probe = run_adb(adb, serial, "shell",
|
||||
"command -v uinput >/dev/null 2>&1 || echo no-uinput; [ -w /dev/uinput ] || echo no-dev-uinput")
|
||||
if probe.returncode != 0:
|
||||
raise ControlError((probe.stdout + probe.stderr).decode(errors="replace").strip() or "adb shell failed", "ADB_FAILED")
|
||||
missing = probe.stdout.decode(errors="replace").split()
|
||||
if "no-uinput" in missing:
|
||||
raise ControlError("This device's shell has no `uinput` command", "UINPUT_UNAVAILABLE")
|
||||
if "no-dev-uinput" in missing:
|
||||
raise ControlError("The ADB shell cannot write /dev/uinput on this device", "UINPUT_UNAVAILABLE")
|
||||
viewport = input_viewport(run_adb(adb, serial, "shell", "dumpsys", "input").stdout.decode(errors="replace"))
|
||||
script = "".join(json.dumps(command) + "\n" for command in uinput_commands(samples, tool, viewport))
|
||||
started = time.monotonic()
|
||||
result = run_adb(adb, serial, "shell", "uinput", "-", stdin=script.encode(),
|
||||
timeout=(UINPUT_REGISTER_MS + samples[-1]["t"] + UINPUT_TAIL_MS) / 1000 + 30)
|
||||
elapsed = round((time.monotonic() - started) * 1000)
|
||||
if UINPUT_SYNC not in result.stdout.decode(errors="replace"):
|
||||
detail = (result.stderr or result.stdout).decode(errors="replace").strip()[-400:]
|
||||
raise ControlError(f"uinput stopped before the end of the gesture (exit {result.returncode})"
|
||||
+ (f": {detail}" if detail else "") + "; `adb logcat -s UINPUT UinputDevice` tells why",
|
||||
"UINPUT_FAILED")
|
||||
return {"ok": True, "command": "input", "type": "pen", "samples": len(samples), "ms": elapsed,
|
||||
"viewport": {key: viewport[key] for key in ("display", "rotation", "size")}}
|
||||
|
||||
|
||||
def xr_ppm_to_png(data: bytes, linear: bool = False) -> bytes:
|
||||
header = re.match(rb"P6\n([0-9]+) ([0-9]+)\n255\n", data)
|
||||
if not header:
|
||||
@@ -824,6 +1020,8 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
|
||||
"CDP_FAILED"), serial)
|
||||
|
||||
if command == "input":
|
||||
if args.input_type == "pen":
|
||||
return add_serial(pen_uinput(adb, serial, pen_samples(args), args.tool), serial)
|
||||
return add_serial(checked(provider_call(adb, serial, "input", request=input_request(args), timeout=60),
|
||||
"INPUT_FAILED"), serial)
|
||||
|
||||
@@ -1095,6 +1293,36 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
trigger.add_argument("trigger", choices=["left", "right"])
|
||||
trigger.add_argument("value", type=float, nargs="?", default=1.0)
|
||||
trigger.add_argument("--hold", type=int, default=200)
|
||||
pen = kinds.add_parser("pen", help="a virtual pen at fractions of the screen as shown")
|
||||
pen_ops = pen.add_subparsers(dest="pen_op", required=True)
|
||||
pen_hover = pen_ops.add_parser("hover", help="come near at X Y, glide to --to X2 Y2 and leave")
|
||||
pen_hover.add_argument("x", type=float)
|
||||
pen_hover.add_argument("y", type=float)
|
||||
pen_hover.add_argument("--to", type=float, nargs=2, metavar=("X2", "Y2"))
|
||||
pen_hover.add_argument("--duration", type=int, default=300)
|
||||
pen_tap = pen_ops.add_parser("tap", help="hover, touch down at X Y, lift and leave")
|
||||
pen_tap.add_argument("x", type=float)
|
||||
pen_tap.add_argument("y", type=float)
|
||||
pen_tap.add_argument("--hold", type=int, default=60, help="ms in contact")
|
||||
pen_stroke = pen_ops.add_parser("stroke", help="hover, draw a line from X Y to X2 Y2 and leave")
|
||||
for name in ("x", "y", "x2", "y2"):
|
||||
pen_stroke.add_argument(name, type=float)
|
||||
pen_stroke.add_argument("--duration", type=int, default=300, help="ms in contact")
|
||||
pen_button = pen_ops.add_parser("button", help="press and release a side button while hovering at X Y")
|
||||
pen_button.add_argument("button", choices=["primary", "secondary"])
|
||||
pen_button.add_argument("x", type=float)
|
||||
pen_button.add_argument("y", type=float)
|
||||
pen_button.add_argument("--hold", type=int, default=120, help="ms the button is down")
|
||||
for op in (pen_tap, pen_stroke):
|
||||
op.add_argument("--pressure", type=pen_span, default=(0.5, 0.5), metavar="P[:P]")
|
||||
for op in (pen_tap, pen_stroke, pen_button):
|
||||
op.add_argument("--hover-ms", type=int, default=80, help="ms of hover before and after")
|
||||
for op in (pen_hover, pen_tap, pen_stroke, pen_button):
|
||||
op.add_argument("--tool", choices=["pen", "eraser"], default="pen")
|
||||
op.add_argument("--tilt-x", type=pen_span, default=(0.0, 0.0), metavar="DEG[:DEG]")
|
||||
op.add_argument("--tilt-y", type=pen_span, default=(0.0, 0.0), metavar="DEG[:DEG]")
|
||||
op.add_argument("--distance", type=int, default=0, help="while hovering, in device units 0..255")
|
||||
op.add_argument("--rate", type=float, default=120, help="samples per second")
|
||||
|
||||
ui = commands.add_parser("ui", help="the app's own UI: dump nodes, click or type by test tag")
|
||||
ui_ops = ui.add_subparsers(dest="ui_op", required=True)
|
||||
@@ -1197,7 +1425,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
return parser
|
||||
|
||||
|
||||
EXIT_ADB = {"ADB_NOT_FOUND", "ADB_FAILED", "INVALID_PROVIDER_RESPONSE"}
|
||||
EXIT_ADB = {"ADB_NOT_FOUND", "ADB_FAILED", "INVALID_PROVIDER_RESPONSE", "UINPUT_UNAVAILABLE", "NO_VIEWPORT", "UINPUT_FAILED"}
|
||||
EXIT_SESSION = {
|
||||
"SESSION_ACTIVE", "NO_ACTIVE_SESSION", "SESSION_NOT_SUSPENDED", "SESSION_FAILED", "GUEST_EXIT",
|
||||
"GUEST_START_FAILED", "RUNTIME_INSTALL_FAILED", "DESKTOP_INSTALL_FAILED", "ACTIVITY_START_FAILED",
|
||||
|
||||
@@ -350,3 +350,11 @@ motion while the seat is locked) with how the X pointer moves. A hinted constrai
|
||||
after 30 moving frames on which the X pointer follows. Any constraint goes relative once the X pointer moves less than a quarter
|
||||
of that motion on three frames within half a second, as it does when the game recentres it or clips it to a small rectangle
|
||||
(PEAK). `tools/tests/test_gamescope_pointer_hold.py` compiles the rule from this patch.
|
||||
|
||||
## 0134 wlserver: a touch presses the emulated click button only once
|
||||
|
||||
In the Left, Right and Middle touch click modes every finger pressed the button, but a finger lifting releases it once
|
||||
and clears the held flag. wlroots counts repeated presses of one button and sends the release only when the count
|
||||
reaches zero, so a second finger touching before the first lifted left the button pressed in the seat for good: the
|
||||
game saw a held click, and later taps only raised and lowered the count. A finger now presses the button only when no
|
||||
earlier finger holds it. `tools/tests/test_gamescope_touch_click.py` compiles the rule from this patch.
|
||||
@@ -0,0 +1,33 @@
|
||||
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
|
||||
index d932df4..df352b0 100644
|
||||
--- a/src/wlserver.cpp
|
||||
+++ b/src/wlserver.cpp
|
||||
@@ -3343,6 +3343,14 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
|
||||
bump_input_counter();
|
||||
}
|
||||
|
||||
+static bool touch_click_press( bool *pHeld, int nMode, uint32_t uButton )
|
||||
+{
|
||||
+ if ( uButton == 0 || nMode < 0 || nMode >= WLSERVER_BUTTON_COUNT || pHeld[ nMode ] )
|
||||
+ return false;
|
||||
+ pHeld[ nMode ] = true;
|
||||
+ return true;
|
||||
+}
|
||||
+
|
||||
void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamescope::IBackendConnector* connector )
|
||||
{
|
||||
assert( wlserver_is_lock_held() );
|
||||
@@ -3389,12 +3397,10 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
|
||||
|
||||
uint32_t button = TouchClickModeToLinuxButton( eMode );
|
||||
|
||||
- if ( button != 0 && eMode < WLSERVER_BUTTON_COUNT )
|
||||
+ if ( touch_click_press( wlserver.button_held, eMode, button ) )
|
||||
{
|
||||
wlr_seat_pointer_notify_button( wlserver.wlr.seat, time, button, WL_POINTER_BUTTON_STATE_PRESSED );
|
||||
wlr_seat_pointer_notify_frame( wlserver.wlr.seat );
|
||||
-
|
||||
- wlserver.button_held[ eMode ] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import runpy
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
@@ -16,6 +17,7 @@ import urllib.request
|
||||
HOME = os.environ.get("HOME") or "/root"
|
||||
BIN = "/usr/local/bin"
|
||||
PROTON_RUN = os.path.join(BIN, "droiddeck-proton-run")
|
||||
GAME_DEBUG = runpy.run_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), "droiddeck-game-debug"))
|
||||
APP_ID = "2596113170"
|
||||
INSTALLER_URL = "https://downloader.battle.net/download/getInstallerForGame?os=win&gameProgram=BATTLENET_APP&version=Live"
|
||||
CLIENT_DIR = ("Program Files (x86)", "Battle.net")
|
||||
@@ -685,6 +687,7 @@ def steam_running(proc="/proc"):
|
||||
|
||||
def proton_env():
|
||||
env = dict(os.environ)
|
||||
env = GAME_DEBUG["apply_game_debug_logs"](env)
|
||||
if not steam_running():
|
||||
env.setdefault("PROTON_SPOOF_STEAMINPUT_VIDPID", "1")
|
||||
return env
|
||||
|
||||
@@ -24,6 +24,7 @@ import urllib.request
|
||||
HOME = os.environ.get("HOME") or "/root"
|
||||
SELF = os.path.abspath(__file__)
|
||||
BIN_DIR = os.path.dirname(SELF)
|
||||
GAME_DEBUG = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-debug"))
|
||||
STATE = os.path.join(HOME, ".local", "share", "droiddeck-epic")
|
||||
CURRENT = os.path.join(STATE, "current.json")
|
||||
APPS = os.path.join(STATE, "app")
|
||||
@@ -1196,6 +1197,7 @@ def run_game(request, session_env, running=None):
|
||||
exe = native_path(request.get("exe") or "")
|
||||
args = request.get("args") or []
|
||||
env = {k: v for k, v in session_env.items() if not k.startswith(("FEX_", "DROIDDECK_EPIC", "EGL_", "WEBKIT_"))}
|
||||
env = GAME_DEBUG["apply_game_debug_logs"](env)
|
||||
preload = env.pop(STEAM_PRELOAD, "")
|
||||
if preload:
|
||||
env["LD_PRELOAD"] = preload
|
||||
|
||||
@@ -8,6 +8,7 @@ import os
|
||||
import re
|
||||
import runpy
|
||||
import shutil
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -37,7 +38,9 @@ RUNTIMES = {SNIPER_APPID: ("sniper_platform_", "Steam Linux Runtime 3.0 (sniper"
|
||||
SLR4_APPID: ("steamrt4_platform_", "Steam Linux Runtime 4.0 (steamrt4")}
|
||||
MARKER = ".droiddeck-fex"
|
||||
LAYOUT = 1
|
||||
ROOTFS_LAYOUT = 9
|
||||
ROOTFS_LAYOUT = 10
|
||||
BLOB_DIRS = re.compile(r"^(?:\.ref|[0-9a-f]{2})$")
|
||||
ROOTFS_LIBRARY_DIRS = ("lib", "lib64")
|
||||
ARCH_DIRS = ("x86_64-linux-gnu", "i386-linux-gnu")
|
||||
INTERPRETERS = ("ld-linux-x86-64.so.2", "ld-linux.so.2")
|
||||
PROVIDED = frozenset((
|
||||
@@ -318,11 +321,40 @@ def provides_newer(base, provider):
|
||||
return True
|
||||
|
||||
|
||||
def mirror(source, provider, name, target):
|
||||
def clone(source, target, parents=()):
|
||||
real = os.path.realpath(source)
|
||||
if real in parents or not os.path.lexists(real):
|
||||
return
|
||||
if os.path.isdir(real):
|
||||
os.makedirs(target, exist_ok=True)
|
||||
for entry in os.listdir(real):
|
||||
clone(os.path.join(real, entry), os.path.join(target, entry), parents + (real,))
|
||||
shutil.copystat(real, target)
|
||||
return
|
||||
shutil.copy2(real, target)
|
||||
|
||||
|
||||
def remove_tree(path):
|
||||
if os.path.islink(path) or not os.path.isdir(path):
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
os.unlink(path)
|
||||
return
|
||||
os.chmod(path, os.lstat(path).st_mode | stat.S_IRWXU)
|
||||
for entry in os.listdir(path):
|
||||
remove_tree(os.path.join(path, entry))
|
||||
os.rmdir(path)
|
||||
|
||||
|
||||
def stays_in_libraries(root, target, link):
|
||||
resolved = os.path.normpath(os.path.join(os.path.relpath(target, root), link))
|
||||
return resolved.split(os.sep)[0] in ROOTFS_LIBRARY_DIRS
|
||||
|
||||
|
||||
def mirror(source, provider, name, target, root):
|
||||
usable_provider = provider and all(os.path.exists(os.path.join(provider, needed))
|
||||
for needed in (name,) + PROVIDED_NEEDS.get(name, ()))
|
||||
if name in PROVIDED and usable_provider:
|
||||
os.symlink(os.path.realpath(os.path.join(provider, name)), os.path.join(target, name))
|
||||
clone(os.path.join(provider, name), os.path.join(target, name))
|
||||
return
|
||||
path = os.path.join(source, name)
|
||||
if not os.path.lexists(path):
|
||||
@@ -334,10 +366,10 @@ def mirror(source, provider, name, target):
|
||||
link = os.path.join(os.path.dirname(link), name)
|
||||
if provider and GLIBC_BUILD.match(name):
|
||||
return
|
||||
if link and not link.startswith("/"):
|
||||
if link and not link.startswith("/") and stays_in_libraries(root, target, link):
|
||||
os.symlink(link, os.path.join(target, name))
|
||||
else:
|
||||
os.symlink(os.path.realpath(path), os.path.join(target, name))
|
||||
clone(path, os.path.join(target, name))
|
||||
|
||||
|
||||
def build_rootfs(base, provider):
|
||||
@@ -359,12 +391,12 @@ def build_rootfs(base, provider):
|
||||
return False
|
||||
for entry in os.listdir(STATE):
|
||||
if entry.startswith("rootfs."):
|
||||
shutil.rmtree(os.path.join(STATE, entry), ignore_errors=True)
|
||||
remove_tree(os.path.join(STATE, entry))
|
||||
tmp = "%s.%d.tmp" % (rootfs, os.getpid())
|
||||
os.makedirs(tmp)
|
||||
for entry in os.listdir(base_files):
|
||||
if entry not in ("lib", "lib64", "usr", MARKER):
|
||||
os.symlink(os.path.realpath(os.path.join(base_files, entry)), os.path.join(tmp, entry))
|
||||
if entry not in ("lib", "lib64", "usr", MARKER) and not BLOB_DIRS.match(entry):
|
||||
clone(os.path.join(base_files, entry), os.path.join(tmp, entry))
|
||||
os.symlink(".", os.path.join(tmp, "usr"))
|
||||
for top in ("lib", "lib64"):
|
||||
source = os.path.join(base_files, top)
|
||||
@@ -375,15 +407,15 @@ def build_rootfs(base, provider):
|
||||
provided = os.path.join(provider_files, top, entry)
|
||||
os.makedirs(os.path.join(tmp, top, entry))
|
||||
for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.exists(os.path.join(provided, name))}:
|
||||
mirror(path, provided, name, os.path.join(tmp, top, entry))
|
||||
mirror(path, provided, name, os.path.join(tmp, top, entry), tmp)
|
||||
else:
|
||||
mirror(source, None, entry, os.path.join(tmp, top))
|
||||
mirror(source, None, entry, os.path.join(tmp, top), tmp)
|
||||
write_if_changed(os.path.join(tmp, MARKER), stamp)
|
||||
old = "%s.%d.old" % (rootfs, os.getpid())
|
||||
if os.path.lexists(rootfs):
|
||||
os.rename(rootfs, old)
|
||||
os.rename(tmp, rootfs)
|
||||
shutil.rmtree(old, ignore_errors=True)
|
||||
remove_tree(old)
|
||||
return True
|
||||
|
||||
|
||||
@@ -463,7 +495,7 @@ def link_guest_sdk(root):
|
||||
continue
|
||||
os.makedirs(os.path.dirname(link), exist_ok=True)
|
||||
if os.path.lexists(link):
|
||||
os.unlink(link)
|
||||
remove_tree(link)
|
||||
os.symlink(directory, link)
|
||||
|
||||
|
||||
@@ -535,8 +567,6 @@ def prepare(app=SNIPER_APPID):
|
||||
root = os.path.join(platform, "files")
|
||||
if materialize(platform):
|
||||
say("prepared %s as the x86 runtime" % os.path.basename(platform))
|
||||
install_preloads(root)
|
||||
install_fonts(root)
|
||||
provider = None
|
||||
if app == SNIPER_APPID:
|
||||
provider = graphics_platform()
|
||||
@@ -553,6 +583,8 @@ def prepare(app=SNIPER_APPID):
|
||||
say("built the x86 runtime from %s with the C and C++ libraries of %s"
|
||||
% (os.path.basename(platform), os.path.basename(provider)))
|
||||
root = os.path.join(STATE, "rootfs")
|
||||
install_preloads(root)
|
||||
install_fonts(root)
|
||||
with contextlib.suppress(OSError):
|
||||
link_guest_sdk(root)
|
||||
write_config(fex, root)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/python3
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
GAME_DEBUG_CHANNELS = (
|
||||
"timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree",
|
||||
)
|
||||
WINE_DEBUG_SELECTOR = re.compile(r"(?:(trace|warn|err|fixme))?([+-])([A-Za-z_][A-Za-z0-9_]*)")
|
||||
|
||||
|
||||
def game_debug_channels(*values):
|
||||
selectors = {}
|
||||
for value in values:
|
||||
if not isinstance(value, str) or "\0" in value or len(value) > 8192:
|
||||
continue
|
||||
for part in value.split(","):
|
||||
part = part.strip()
|
||||
match = WINE_DEBUG_SELECTOR.fullmatch(part)
|
||||
if match is None:
|
||||
continue
|
||||
key = (match[1] or "", match[3])
|
||||
selectors.pop(key, None)
|
||||
selectors[key] = part
|
||||
for channel in GAME_DEBUG_CHANNELS:
|
||||
key = ("", channel)
|
||||
selectors.pop(key, None)
|
||||
selectors[key] = "+" + channel
|
||||
formatted = ",".join(selectors.values())
|
||||
if len(formatted) > 8192:
|
||||
formatted = ",".join("+" + channel for channel in GAME_DEBUG_CHANNELS)
|
||||
return formatted
|
||||
|
||||
|
||||
def load_config():
|
||||
try:
|
||||
path = Path(os.environ.get("HOME") or "/root") / ".config/droiddeck/game-environment.json"
|
||||
with path.open(encoding="utf-8") as source:
|
||||
return json.load(source)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def session_debug_dir(env):
|
||||
return env.get("BL_DEBUG_DIR", "")
|
||||
|
||||
|
||||
def apply_game_debug_logs(env, config=None, debug_dir=None):
|
||||
if config is None:
|
||||
config = load_config()
|
||||
if not isinstance(config, dict) or config.get("version") != 1 or config.get("gameDebugLogs") is not True:
|
||||
return env
|
||||
if debug_dir is None:
|
||||
debug_dir = session_debug_dir(env)
|
||||
if (not isinstance(debug_dir, str) or "\0" in debug_dir or len(debug_dir) > 8192
|
||||
or not os.path.isabs(debug_dir) or not os.path.isdir(debug_dir)):
|
||||
print("droiddeck-game-env: game debug logs skipped; session log directory unavailable", file=sys.stderr)
|
||||
return env
|
||||
result = dict(env)
|
||||
result.update({
|
||||
"PROTON_LOG": "1",
|
||||
"PROTON_LOG_DIR": debug_dir,
|
||||
"PROTON_CRASH_REPORT_DIR": debug_dir,
|
||||
"DXVK_LOG_PATH": debug_dir,
|
||||
"DXVK_LOG_LEVEL": "debug",
|
||||
"VKD3D_DEBUG": "info",
|
||||
"WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
|
||||
})
|
||||
return result
|
||||
@@ -17,6 +17,10 @@ D3D9_DEFAULT_MEMORY_MB = 4096
|
||||
SYNC_KEYS = ("BL_SYNC", "BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
|
||||
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
|
||||
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
|
||||
GAME_DEBUG = runpy.run_path(str(Path(__file__).with_name("droiddeck-game-debug")))
|
||||
game_debug_channels = GAME_DEBUG["game_debug_channels"]
|
||||
apply_game_debug_logs = GAME_DEBUG["apply_game_debug_logs"]
|
||||
session_debug_dir = GAME_DEBUG["session_debug_dir"]
|
||||
|
||||
|
||||
# Prefixes several games share; the game itself is the Steam app being launched.
|
||||
@@ -124,7 +128,8 @@ def godot_vulkan(game):
|
||||
@fix
|
||||
def godot_sentry(game):
|
||||
sentry = sorted(n[:-4] for n in game.files if n.startswith("libsentry.windows.") and n.endswith(".dll"))
|
||||
if is_godot(game) and sentry and ("coreclr.dll" in game.files or "godotsharp.dll" in game.files):
|
||||
# Sentry.Godot.dll's module initializer P/Invokes the native DLL; without it GodotPlugins fails to start.
|
||||
if is_godot(game) and sentry and ("coreclr.dll" in game.files or "godotsharp.dll" in game.files) and "sentry.godot.dll" not in game.files:
|
||||
return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off"
|
||||
|
||||
|
||||
@@ -188,6 +193,21 @@ def little_nightmares_threads(game):
|
||||
return {"PROTONFIXES_DISABLE": "1"}, [], "Little Nightmares: umu-protonfixes off (its -onethread puts the game and renderer on one thread)"
|
||||
|
||||
|
||||
def names_module(overrides, names):
|
||||
for entry in (overrides or "").split(";"):
|
||||
if "=" in entry and names & {re.sub(r"^\*|\.dll$", "", name.lower()) for name in re.split(r"[, \t]", entry.split("=", 1)[0])}:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def keyboard_helper_off(env):
|
||||
if env.get("SteamDeck") == "1" or names_module(env.get("WINEDLLOVERRIDES"), {"tabtip.exe"}):
|
||||
return None
|
||||
own = env.get("WINEDLLOVERRIDES")
|
||||
env["WINEDLLOVERRIDES"] = own + ";tabtip.exe=d" if own else "tabtip.exe=d"
|
||||
return "tabtip.exe off (it only opens Steam's keyboard with SteamDeck=1, and its UI Automation calls crash games)"
|
||||
|
||||
|
||||
def skip_red_launcher(command):
|
||||
if len(command) > 2 and os.path.basename(command[2]).lower() == "redprelauncher.exe":
|
||||
game = os.path.join(os.path.dirname(command[2]), "bin", "x64", "Cyberpunk2077.exe")
|
||||
@@ -361,6 +381,36 @@ def engine_fixes(exe, args):
|
||||
return env, extra, notes
|
||||
|
||||
|
||||
DS_APP_IDS = {"1190460", "1850570"}
|
||||
DS_SIZE = 86479872
|
||||
DS_WINDOW_OFFSET = 0x38FE190
|
||||
DS_WINDOW = bytes.fromhex("48895c240848896c2410488974241848897c242041564883ec70458bf1498bf0488bfa488be94885c9")
|
||||
DS_ORIGINAL = bytes.fromhex("0f85a5000000")
|
||||
DS_FIXED = bytes.fromhex("e9a600000090")
|
||||
|
||||
|
||||
def death_stranding_allocator(app_id, exe):
|
||||
# The game's bundled mimalloc tries one random address between 4 and 8 TiB and never falls back,
|
||||
# but a 39-bit kernel cannot map anything above 512 GiB. Jumping straight to its aligned path avoids it.
|
||||
if app_id not in DS_APP_IDS or os.path.basename(exe).lower() != "ds.exe":
|
||||
return False
|
||||
try:
|
||||
with open(exe, "r+b") as game:
|
||||
if os.fstat(game.fileno()).st_size != DS_SIZE:
|
||||
return False
|
||||
game.seek(DS_WINDOW_OFFSET)
|
||||
seen = game.read(len(DS_WINDOW) + len(DS_ORIGINAL))
|
||||
if seen[:len(DS_WINDOW)] != DS_WINDOW or seen[len(DS_WINDOW):] != DS_ORIGINAL:
|
||||
return False
|
||||
game.seek(DS_WINDOW_OFFSET + len(DS_WINDOW))
|
||||
game.write(DS_FIXED)
|
||||
except OSError as error:
|
||||
print("droiddeck-game-env: Death Stranding allocator fix not applied (%s)" % error, file=sys.stderr)
|
||||
return False
|
||||
print("droiddeck-game-env: Death Stranding: memory allocator no longer needs a high address (39-bit kernels)", file=sys.stderr)
|
||||
return True
|
||||
|
||||
|
||||
def win_components(compat, app_id, proton=None, env=None):
|
||||
if not compat:
|
||||
return ""
|
||||
@@ -550,7 +600,16 @@ def apply_config(env, config, app_id, fixes=None):
|
||||
if name == "WINEDLLOVERRIDES" and entries.get(name, env.get(name)):
|
||||
value = entries.get(name, env.get(name)) + ";" + value
|
||||
entries[name] = value
|
||||
entries.update(config.get("games", {}).get(app_id, {}))
|
||||
game = config.get("games", {}).get(app_id, {})
|
||||
fix = (fixes or {}).get("WINEDLLOVERRIDES")
|
||||
if fix and isinstance(game.get("WINEDLLOVERRIDES"), str):
|
||||
own = game["WINEDLLOVERRIDES"]
|
||||
combined = fix + ";" + own if own else fix
|
||||
if len(combined) > 8192:
|
||||
print("droiddeck-game-env: game WINEDLLOVERRIDES too long to add DroidDeck's overrides; using the game value only", file=sys.stderr)
|
||||
combined = own
|
||||
game = dict(game, WINEDLLOVERRIDES=combined)
|
||||
entries.update(game)
|
||||
for name, value in entries.items():
|
||||
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
|
||||
raise ValueError("invalid environment name")
|
||||
@@ -615,55 +674,6 @@ def bridge_feature_level(env):
|
||||
return "Mali bridge: VKD3D_FEATURE_LEVEL %s capped at 12_0 (no ray tracing or mesh shaders)" % was
|
||||
|
||||
|
||||
GAME_DEBUG_CHANNELS = (
|
||||
"timestamp", "pid", "tid", "seh", "unwind", "threadname", "debugstr", "loaddll", "mscoree",
|
||||
)
|
||||
WINE_DEBUG_SELECTOR = re.compile(r"(?:(trace|warn|err|fixme))?([+-])([A-Za-z_][A-Za-z0-9_]*)")
|
||||
|
||||
|
||||
def game_debug_channels(*values):
|
||||
selectors = {}
|
||||
for value in values:
|
||||
if not isinstance(value, str) or "\0" in value or len(value) > 8192:
|
||||
continue
|
||||
for part in value.split(","):
|
||||
part = part.strip()
|
||||
match = WINE_DEBUG_SELECTOR.fullmatch(part)
|
||||
if match is None:
|
||||
continue
|
||||
key = (match[1] or "", match[3])
|
||||
selectors.pop(key, None)
|
||||
selectors[key] = part
|
||||
for channel in GAME_DEBUG_CHANNELS:
|
||||
key = ("", channel)
|
||||
selectors.pop(key, None)
|
||||
selectors[key] = "+" + channel
|
||||
formatted = ",".join(selectors.values())
|
||||
if len(formatted) > 8192:
|
||||
formatted = ",".join("+" + channel for channel in GAME_DEBUG_CHANNELS)
|
||||
return formatted
|
||||
|
||||
|
||||
def apply_game_debug_logs(env, config, debug_dir):
|
||||
if not isinstance(config, dict) or config.get("version") != 1 or config.get("gameDebugLogs") is not True:
|
||||
return env
|
||||
if (not isinstance(debug_dir, str) or "\0" in debug_dir or len(debug_dir) > 8192
|
||||
or not os.path.isabs(debug_dir) or not os.path.isdir(debug_dir)):
|
||||
print("droiddeck-game-env: game debug logs skipped; session log directory unavailable", file=sys.stderr)
|
||||
return env
|
||||
result = dict(env)
|
||||
result.update({
|
||||
"PROTON_LOG": "1",
|
||||
"PROTON_LOG_DIR": debug_dir,
|
||||
"PROTON_CRASH_REPORT_DIR": debug_dir,
|
||||
"DXVK_LOG_PATH": debug_dir,
|
||||
"DXVK_LOG_LEVEL": "debug",
|
||||
"VKD3D_DEBUG": "info",
|
||||
"WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def sync_config(config, app_id):
|
||||
games = config.get("games", {})
|
||||
return {
|
||||
@@ -897,14 +907,11 @@ PE = runpy.run_path(str(Path(__file__).resolve().parent / "droiddeck-wine-pe"))
|
||||
pe_machine = PE["pe_machine"]
|
||||
|
||||
|
||||
def repair_foreign_system_dlls(prefix, proton, env=None):
|
||||
def prefix_system_dlls(prefix, proton, env=None):
|
||||
dist = Path(proton).parent / "files/lib/wine"
|
||||
windows = Path(prefix) / "pfx/drive_c/windows"
|
||||
machines_by_folder = PE["proton_pe_machines"](proton, env or {})
|
||||
if machines_by_folder is None:
|
||||
return []
|
||||
repaired = []
|
||||
for folder, (libdir, machines) in machines_by_folder.items():
|
||||
for folder, (libdir, machines) in (machines_by_folder or {}).items():
|
||||
builtins = dist / libdir
|
||||
try:
|
||||
builtin_names = {name.lower(): name for name in os.listdir(builtins)}
|
||||
@@ -914,35 +921,83 @@ def repair_foreign_system_dlls(prefix, proton, env=None):
|
||||
names = sorted(os.listdir(windows / folder))
|
||||
except OSError:
|
||||
continue
|
||||
# Both restoration and repair may examine many DLLs. Index the backup
|
||||
# names from this directory listing instead of listing it for each DLL.
|
||||
backups = {}
|
||||
for entry in names:
|
||||
stem, marker, suffix = entry.partition(FOREIGN_SUFFIX)
|
||||
if not marker or not stem.lower().endswith(".dll"):
|
||||
continue
|
||||
if not suffix:
|
||||
serial = 0
|
||||
elif suffix.startswith(".") and suffix[1:].isdigit():
|
||||
serial = int(suffix[1:])
|
||||
else:
|
||||
continue
|
||||
backups.setdefault(stem, []).append((serial, windows / folder / entry))
|
||||
for copies in backups.values():
|
||||
copies.sort()
|
||||
for name in names:
|
||||
path = windows / folder / name
|
||||
builtin_name = builtin_names.get(name.lower())
|
||||
source = builtins / builtin_name if builtin_name else builtins / name
|
||||
if path.is_symlink() or not name.lower().endswith(".dll") or not source.is_file() or not path.is_file():
|
||||
if name.lower().endswith(".dll") and source.is_file():
|
||||
yield folder, name, windows / folder / name, source, machines, builtins, backups.get(name, ())
|
||||
|
||||
|
||||
def newest_foreign_backup(backups):
|
||||
return backups[-1][1] if backups else None
|
||||
|
||||
|
||||
def restore_compatible_system_dlls(prefix, proton, env=None):
|
||||
restored = []
|
||||
for folder, name, path, source, machines, builtins, backups in prefix_system_dlls(prefix, proton, env):
|
||||
if not path.is_symlink() or not path.is_file():
|
||||
continue
|
||||
try:
|
||||
if not os.path.samefile(path, source):
|
||||
continue
|
||||
machine = pe_machine(path)
|
||||
if machine is None or PE["machine_compatible"](path, machines, machine):
|
||||
continue
|
||||
link = windows / folder / (name + ".bl-new")
|
||||
backup = windows / folder / (name + FOREIGN_SUFFIX)
|
||||
serial = 1
|
||||
while os.path.lexists(backup):
|
||||
backup = windows / folder / (name + FOREIGN_SUFFIX + ".%d" % serial)
|
||||
serial += 1
|
||||
except OSError:
|
||||
continue
|
||||
backup = newest_foreign_backup(backups)
|
||||
if backup is None or backup.is_symlink() or not backup.is_file():
|
||||
continue
|
||||
machine = pe_machine(backup)
|
||||
if machine is None or not PE["machine_compatible"](backup, machines, machine, builtins, name):
|
||||
continue
|
||||
try:
|
||||
os.replace(backup, path)
|
||||
except OSError:
|
||||
continue
|
||||
restored.append("%s/%s (machine 0x%x)" % (folder, name, machine))
|
||||
return restored
|
||||
|
||||
|
||||
def repair_foreign_system_dlls(prefix, proton, env=None):
|
||||
repaired = []
|
||||
for folder, name, path, source, machines, builtins, backups in prefix_system_dlls(prefix, proton, env):
|
||||
if path.is_symlink() or not path.is_file():
|
||||
continue
|
||||
machine = pe_machine(path)
|
||||
if machine is None or PE["machine_compatible"](path, machines, machine, builtins):
|
||||
continue
|
||||
link = path.parent / (name + ".bl-new")
|
||||
backup = path.parent / (name + FOREIGN_SUFFIX)
|
||||
if backups:
|
||||
backup = path.parent / (name + FOREIGN_SUFFIX + ".%d" % (backups[-1][0] + 1))
|
||||
try:
|
||||
os.symlink(os.path.relpath(source, path.parent), link)
|
||||
os.replace(path, backup)
|
||||
try:
|
||||
os.symlink(os.path.relpath(source, path.parent), link)
|
||||
os.replace(path, backup)
|
||||
try:
|
||||
os.replace(link, path)
|
||||
except OSError:
|
||||
if not os.path.lexists(path) and os.path.lexists(backup):
|
||||
os.replace(backup, path)
|
||||
raise
|
||||
os.replace(link, path)
|
||||
except OSError:
|
||||
if link.is_symlink():
|
||||
link.unlink()
|
||||
continue
|
||||
repaired.append("%s/%s (machine 0x%x)" % (folder, name, machine))
|
||||
if not os.path.lexists(path) and os.path.lexists(backup):
|
||||
os.replace(backup, path)
|
||||
raise
|
||||
except OSError:
|
||||
if link.is_symlink():
|
||||
link.unlink()
|
||||
continue
|
||||
repaired.append("%s/%s (machine 0x%x)" % (folder, name, machine))
|
||||
return repaired
|
||||
|
||||
|
||||
@@ -1242,7 +1297,7 @@ def main():
|
||||
return 2
|
||||
env = game_gpu(os.environ.copy())
|
||||
mic_enabled = env.get("BL_MIC_ENABLED")
|
||||
debug_dir = env.get("BL_DEBUG_DIR", "")
|
||||
debug_dir = session_debug_dir(env)
|
||||
prefix_path = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
|
||||
app_id = game_id(env)
|
||||
components = ""
|
||||
@@ -1272,10 +1327,14 @@ def main():
|
||||
components = win_components(prefix_path, app_id, command[0], effective_env)
|
||||
if prefix_path and command:
|
||||
try:
|
||||
restored = restore_compatible_system_dlls(prefix_path, command[0], effective_env)
|
||||
fixed = repair_foreign_system_dlls(prefix_path, command[0], effective_env)
|
||||
except OSError as error:
|
||||
fixed = []
|
||||
restored = fixed = []
|
||||
print("droiddeck-game-env: prefix system DLL check skipped (%s)" % error, file=sys.stderr)
|
||||
if restored:
|
||||
print("droiddeck-game-env: restored system DLLs this Proton's own programs do not load: %s" % ", ".join(restored),
|
||||
file=sys.stderr)
|
||||
if fixed:
|
||||
print("droiddeck-game-env: replaced foreign-architecture system DLLs with this Proton's own: %s" % ", ".join(fixed),
|
||||
file=sys.stderr)
|
||||
@@ -1300,6 +1359,8 @@ def main():
|
||||
fixes = {}
|
||||
if waiting:
|
||||
command = skip_red_launcher(command)
|
||||
if len(command) > 2:
|
||||
death_stranding_allocator(app_id, command[2])
|
||||
ubisoft_overlay_off(env)
|
||||
project_zomboid_jvm(command)
|
||||
fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], [])
|
||||
@@ -1320,6 +1381,9 @@ def main():
|
||||
if "vblank_mode" in config.get("shared", {}):
|
||||
fixes.pop("vblank_mode", None)
|
||||
env = apply_config(env, launch_config, app_id, fixes)
|
||||
note = keyboard_helper_off(env)
|
||||
if note:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
else:
|
||||
path = Path.home() / ".config/droiddeck/game-environment.json"
|
||||
try:
|
||||
|
||||
@@ -972,6 +972,7 @@ case $mode in
|
||||
bl_session_pressure() {
|
||||
bl_memory_read
|
||||
[ "$_bl_game" = 1 ] && bl_memory_critical || return 0
|
||||
[ "${BL_ZRAM_IDLE:-1}" = 1 ] && bl_game_focused 0 || return 0
|
||||
local _wait=$_bl_tier_backoff _before _pids _targets
|
||||
[ "$_bl_available" -ge $((_bl_headroom / 2)) ] || [ "$_bl_tier_pushed" -lt 0 ] || _wait=30
|
||||
[ "$_bl_tier_at" -lt 0 ] || [ $((SECONDS - _bl_tier_at)) -ge "$_wait" ] || return 0
|
||||
@@ -1103,7 +1104,7 @@ case $mode in
|
||||
local id
|
||||
id=$(sed -n 's/.*"focusedApp"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' \
|
||||
"$BL_LAUNCH_DIR/agent/focus.json" 2>/dev/null | head -1)
|
||||
[ -n "$id" ] || return 1
|
||||
[ -n "$id" ] || return "${1:-1}"
|
||||
case " ${_bl_apps-} " in
|
||||
*" $id "*) return 0 ;;
|
||||
esac
|
||||
|
||||
@@ -479,13 +479,15 @@ def save_state(compat, state):
|
||||
os.replace(temp, compat / STATE)
|
||||
|
||||
|
||||
def foreign_component(rel, path, machines):
|
||||
def foreign_component(rel, path, machines, dist=None):
|
||||
parts = Path(rel).parts
|
||||
folder = parts[2] if len(parts) > 2 and parts[:2] == ("drive_c", "windows") else None
|
||||
if not machines or folder not in PE_MACHINES or not rel.lower().endswith(".dll"):
|
||||
return False
|
||||
machine = pe_machine(path)
|
||||
return machine is not None and not machine_compatible(path, machines[folder][1], machine)
|
||||
libdir, compatible = machines[folder]
|
||||
builtins = dist / libdir if dist else None
|
||||
return machine is not None and not machine_compatible(path, compatible, machine, builtins)
|
||||
|
||||
|
||||
def pending_for(app_id, pending=PENDING):
|
||||
@@ -546,6 +548,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
|
||||
skipped = set()
|
||||
placed_stems = set()
|
||||
machines = PE["proton_pe_machines"](proton, env) if proton else None
|
||||
dist = Path(proton).parent / "files/lib/wine" if proton else None
|
||||
saved_overrides = state.get("overrides") if isinstance(state.get("overrides"), dict) else {}
|
||||
saved_requires = state.get("requires") if isinstance(state.get("requires"), dict) else {}
|
||||
recorded = [c for c in state.get("components", []) if isinstance(c, str) and valid_id(c)]
|
||||
@@ -585,7 +588,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
|
||||
kept_requires[cid] = list(requires)
|
||||
values += [(cid, value) for value in registry]
|
||||
for rel, src in files:
|
||||
foreign = foreign_component(rel, src, machines)
|
||||
foreign = foreign_component(rel, src, machines, dist)
|
||||
if foreign:
|
||||
skipped.add(Path(rel).stem.lower())
|
||||
changed = False
|
||||
@@ -606,7 +609,7 @@ def apply(compat_path, app_id, selection=SELECTION, store=STORE, pending=PENDING
|
||||
path = existing(pfx / rel)
|
||||
saved = compat / BACKUP / rel
|
||||
if saved.is_file():
|
||||
if foreign_component(rel, saved, machines):
|
||||
if foreign_component(rel, saved, machines, dist):
|
||||
if path is not None and not path.is_symlink():
|
||||
path.unlink()
|
||||
continue
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/python3
|
||||
import re
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -76,18 +76,105 @@ def pe_has_arm64ec_metadata(path):
|
||||
return False
|
||||
|
||||
|
||||
# Only x64 code and members of the same runtime family import these, so an x64 copy loads in an
|
||||
# ARM64EC prefix, and games check for a newer version than Wine's builtins report.
|
||||
VC_RUNTIME = re.compile(r"(msvc[pr]\d.*|vcruntime\d.*|vcomp\d*|vcamp\d.*|vccorlib\d.*|concrt\d.*|mfcm?\d.*)\.dll",
|
||||
re.IGNORECASE)
|
||||
def pe_imports(path):
|
||||
try:
|
||||
with open(path, "rb") as source:
|
||||
image = source.read()
|
||||
except OSError:
|
||||
return None
|
||||
try:
|
||||
if image[:2] != b"MZ":
|
||||
return None
|
||||
pe_offset = int.from_bytes(image[60:64], "little")
|
||||
if image[pe_offset:pe_offset + 4] != b"PE\0\0":
|
||||
return None
|
||||
section_count = int.from_bytes(image[pe_offset + 6:pe_offset + 8], "little")
|
||||
optional_size = int.from_bytes(image[pe_offset + 20:pe_offset + 22], "little")
|
||||
optional = pe_offset + 24
|
||||
magic = int.from_bytes(image[optional:optional + 2], "little")
|
||||
directories = optional + (112 if magic == 0x20B else 96)
|
||||
if directories > len(image):
|
||||
return None
|
||||
directory_count = int.from_bytes(image[directories - 4:directories], "little")
|
||||
sections = []
|
||||
for index in range(min(section_count, 96)):
|
||||
entry = optional + optional_size + index * 40
|
||||
if entry + 40 > len(image):
|
||||
return None
|
||||
sections.append((int.from_bytes(image[entry + 12:entry + 16], "little"),
|
||||
max(int.from_bytes(image[entry + 8:entry + 12], "little"),
|
||||
int.from_bytes(image[entry + 16:entry + 20], "little")),
|
||||
int.from_bytes(image[entry + 20:entry + 24], "little")))
|
||||
|
||||
def offset(rva):
|
||||
for address, size, raw in sections:
|
||||
if address <= rva < address + size:
|
||||
return rva - address + raw
|
||||
return None
|
||||
|
||||
names = set()
|
||||
for directory, step, field in ((1, 20, 12), (13, 32, 4)):
|
||||
if directory >= directory_count:
|
||||
continue
|
||||
if directories + directory * 8 + 8 > len(image):
|
||||
return None
|
||||
rva = int.from_bytes(image[directories + directory * 8:directories + directory * 8 + 4], "little")
|
||||
entry = offset(rva) if rva else None
|
||||
if rva and entry is None:
|
||||
return None
|
||||
while entry is not None:
|
||||
if entry + step > len(image):
|
||||
return None
|
||||
name_rva = int.from_bytes(image[entry + field:entry + field + 4], "little")
|
||||
if not name_rva:
|
||||
break
|
||||
name = offset(name_rva)
|
||||
end = image.find(b"\0", name) if name is not None else -1
|
||||
if end < 0:
|
||||
return None
|
||||
names.add(image[name:end].decode("ascii", "replace").lower())
|
||||
entry += step
|
||||
return names
|
||||
except (IndexError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def machine_compatible(path, machines, machine=None):
|
||||
PROGRAM_IMPORTS = {}
|
||||
|
||||
|
||||
def program_imports(builtins):
|
||||
key = str(builtins)
|
||||
if key not in PROGRAM_IMPORTS:
|
||||
try:
|
||||
files = {name.lower(): Path(builtins) / name for name in os.listdir(builtins)}
|
||||
except OSError:
|
||||
files = None
|
||||
pending = [name for name in files or () if name.endswith(".exe") and pe_machine(files[name]) in (None, 0xAA64)]
|
||||
seen = set()
|
||||
while pending and files is not None:
|
||||
name = pending.pop()
|
||||
if name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
if name in files:
|
||||
imports = pe_imports(files[name])
|
||||
if imports is None:
|
||||
files = None
|
||||
else:
|
||||
pending.extend(imports)
|
||||
PROGRAM_IMPORTS[key] = None if files is None else frozenset(name for name in seen if name.endswith(".dll"))
|
||||
return PROGRAM_IMPORTS[key]
|
||||
|
||||
|
||||
def machine_compatible(path, machines, machine=None, builtins=None, name=None):
|
||||
machine = pe_machine(path) if machine is None else machine
|
||||
if machine == 0x8664 and 0xA641 in machines and VC_RUNTIME.fullmatch(Path(path).name):
|
||||
return True
|
||||
if machine == 0x8664 and 0xA641 in machines:
|
||||
if pe_has_arm64ec_metadata(path):
|
||||
return True
|
||||
imported = program_imports(builtins) if builtins is not None else None
|
||||
return imported is not None and (name or Path(path).name).lower() not in imported
|
||||
if machine == 0x8664 and pe_has_arm64ec_metadata(path):
|
||||
return 0xA641 in machines
|
||||
return False
|
||||
return machine in machines
|
||||
|
||||
|
||||
|
||||
@@ -197,6 +197,172 @@ def wine(argv, source_env=None):
|
||||
pass
|
||||
|
||||
|
||||
# PlayFab Game Saves picks its provider from the Gaming Runtime unless HKLM\SOFTWARE\Microsoft\GamingServices
|
||||
# ForceUseInprocGameSaves is set, and its in-process provider needs a save folder the title never passes on Windows.
|
||||
# The runtime has no GRTS saves, so titles such as Forza Horizon 6 stop with E:0-17. xodus-nexus ships a proxy
|
||||
# (scripts/runtime-compat/playfab-save-folder.c, MIT) that keeps the title's own SDK as nexus_pgs_native.dll and
|
||||
# supplies both; this stages it the same way.
|
||||
PGS_PROXY = RUNTIME / 'compat' / 'PlayFabGameSave.dll'
|
||||
PGS_NATIVE = 'nexus_pgs_native.dll'
|
||||
PGS_EXPORTS = (
|
||||
'PFGameSaveFilesAddUserWithUiAsync', 'PFGameSaveFilesAddUserWithUiResult', 'PFGameSaveFilesGetFolder',
|
||||
'PFGameSaveFilesGetFolderSize', 'PFGameSaveFilesGetRemainingQuota', 'PFGameSaveFilesGetSaveDescriptionForDebug',
|
||||
'PFGameSaveFilesGetSaveDescriptionSizeForDebug', 'PFGameSaveFilesGetStatsJsonForDebug',
|
||||
'PFGameSaveFilesGetStatsJsonSizeForDebug', 'PFGameSaveFilesInitialize', 'PFGameSaveFilesIsConnectedToCloud',
|
||||
'PFGameSaveFilesPauseUploadForDebug', 'PFGameSaveFilesResetCloudAsync', 'PFGameSaveFilesResetCloudResult',
|
||||
'PFGameSaveFilesResumeUploadForDebug', 'PFGameSaveFilesSetActiveDeviceChangedCallback',
|
||||
'PFGameSaveFilesSetActiveDevicePollForceChangeForDebug', 'PFGameSaveFilesSetActiveDevicePollIntervalForDebug',
|
||||
'PFGameSaveFilesSetForceNullPendingManifestForDebug', 'PFGameSaveFilesSetForceOutOfStorageErrorForDebug',
|
||||
'PFGameSaveFilesSetForceSyncFailedErrorForDebug', 'PFGameSaveFilesSetMockDataFolderForDebug',
|
||||
'PFGameSaveFilesSetMockDeviceIdForDebug', 'PFGameSaveFilesSetMockForceOfflineForDebug',
|
||||
'PFGameSaveFilesSetMockManifestOffsetForDebug', 'PFGameSaveFilesSetMockRootFolderForDebug',
|
||||
'PFGameSaveFilesSetSaveDescriptionAsync', 'PFGameSaveFilesSetSaveDescriptionResult',
|
||||
'PFGameSaveFilesSetUiActiveDeviceContentionResponse', 'PFGameSaveFilesSetUiCallbacks',
|
||||
'PFGameSaveFilesSetUiConflictResponse', 'PFGameSaveFilesSetUiOutOfStorageResponse',
|
||||
'PFGameSaveFilesSetUiProgressResponse', 'PFGameSaveFilesSetUiSyncFailedResponse',
|
||||
'PFGameSaveFilesSetWriteManifestsToDiskForDebug', 'PFGameSaveFilesUiProgressGetProgress',
|
||||
'PFGameSaveFilesUninitializeAsync', 'PFGameSaveFilesUninitializeResult', 'PFGameSaveFilesUploadWithUiAsync',
|
||||
'PFGameSaveFilesUploadWithUiResult',
|
||||
)
|
||||
|
||||
|
||||
def pe_exports(data):
|
||||
"""(export address table size, [(name, ordinal index, forwarder or None) for each named export]) of an x64
|
||||
PE image, or None. The table size also counts exports that have no name."""
|
||||
def u16(offset):
|
||||
return int.from_bytes(data[offset:offset + 2], 'little')
|
||||
|
||||
def u32(offset):
|
||||
return int.from_bytes(data[offset:offset + 4], 'little')
|
||||
|
||||
def string(offset):
|
||||
end = data.find(b'\0', offset)
|
||||
return None if offset is None or end < 0 else data[offset:end].decode('ascii', 'replace')
|
||||
|
||||
if len(data) < 256 or data[:2] != b'MZ':
|
||||
return None
|
||||
pe = u32(60)
|
||||
if data[pe:pe + 4] != b'PE\0\0' or u16(pe + 4) != 0x8664:
|
||||
return None
|
||||
count, optional_size = u16(pe + 6), u16(pe + 20)
|
||||
optional = pe + 24
|
||||
if optional_size < 120 or u16(optional) != 0x20B or u32(optional + 108) < 1:
|
||||
return None
|
||||
sections = optional + optional_size
|
||||
|
||||
def offset_of(address):
|
||||
for index in range(count):
|
||||
section = sections + index * 40
|
||||
start, size, raw = u32(section + 12), u32(section + 16), u32(section + 20)
|
||||
if start <= address < start + size and raw + address - start < len(data):
|
||||
return raw + address - start
|
||||
return None
|
||||
|
||||
directory_rva, directory_size = u32(optional + 112), u32(optional + 116)
|
||||
directory = offset_of(directory_rva)
|
||||
if directory is None or u32(directory + 16) != 1:
|
||||
return None
|
||||
functions, names = u32(directory + 20), u32(directory + 24)
|
||||
function_table, name_table, ordinal_table = (offset_of(u32(directory + 28)), offset_of(u32(directory + 32)),
|
||||
offset_of(u32(directory + 36)))
|
||||
if None in (function_table, name_table, ordinal_table):
|
||||
return None
|
||||
exports = []
|
||||
for index in range(names):
|
||||
name = string(offset_of(u32(name_table + 4 * index)))
|
||||
ordinal = u16(ordinal_table + 2 * index)
|
||||
address = u32(function_table + 4 * ordinal) if ordinal < functions else 0
|
||||
if name is None or not address:
|
||||
return None
|
||||
forward = string(offset_of(address)) if directory_rva <= address < directory_rva + directory_size else None
|
||||
exports.append((name, ordinal, forward))
|
||||
return functions, exports
|
||||
|
||||
|
||||
def playfab_sdk(data):
|
||||
"""The PlayFab Game Saves SDK the proxy was written for: exactly its 40 exports, all named, none forwarded."""
|
||||
parsed = pe_exports(data)
|
||||
if parsed is None or parsed[0] != len(PGS_EXPORTS):
|
||||
return False
|
||||
exports = parsed[1]
|
||||
return ([(name, ordinal) for name, ordinal, _ in exports] == list(zip(PGS_EXPORTS, range(len(PGS_EXPORTS))))
|
||||
and all(forward is None for _, _, forward in exports))
|
||||
|
||||
|
||||
def playfab_proxy(data):
|
||||
"""A save-folder proxy (this one or an earlier build): the same 40 exports, forwarding into nexus_pgs_native."""
|
||||
parsed = pe_exports(data)
|
||||
if parsed is None or parsed[0] != len(PGS_EXPORTS):
|
||||
return False
|
||||
exports = parsed[1]
|
||||
return ([name for name, _, _ in exports] == list(PGS_EXPORTS)
|
||||
and any((forward or '').startswith(PGS_NATIVE[:-4] + '.') for _, _, forward in exports))
|
||||
|
||||
|
||||
def kept_sdk(native):
|
||||
"""True when nexus_pgs_native.dll is a regular file holding a recognised SDK."""
|
||||
return not native.is_symlink() and native.is_file() and playfab_sdk(native.read_bytes())
|
||||
|
||||
|
||||
def replace_file(directory, name, data):
|
||||
descriptor, temporary = tempfile.mkstemp(prefix='.droiddeck-pgs-', dir=directory)
|
||||
try:
|
||||
with os.fdopen(descriptor, 'wb') as file:
|
||||
file.write(data)
|
||||
file.flush()
|
||||
os.fsync(file.fileno())
|
||||
os.chmod(temporary, 0o644)
|
||||
os.replace(temporary, Path(directory) / name)
|
||||
except BaseException:
|
||||
try:
|
||||
os.unlink(temporary)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def stage_playfab_proxy(folder):
|
||||
"""Put the save-folder proxy in front of every PlayFab Game Saves SDK in the game folder. Returns how many."""
|
||||
try:
|
||||
proxy = PGS_PROXY.read_bytes()
|
||||
except OSError:
|
||||
return 0
|
||||
staged = 0
|
||||
for root, _, files in os.walk(folder):
|
||||
directory = Path(root)
|
||||
for name in files:
|
||||
if name.lower() != 'playfabgamesave.dll':
|
||||
continue
|
||||
path = directory / name
|
||||
native = directory / PGS_NATIVE
|
||||
try:
|
||||
if path.is_symlink():
|
||||
continue
|
||||
data = path.read_bytes()
|
||||
if playfab_sdk(data):
|
||||
# A first launch, or a game update that brought a new SDK: the update's copy becomes the native one,
|
||||
# but only in place of nothing or of an earlier SDK copy, never over an unknown file or a link.
|
||||
if os.path.lexists(native) and not kept_sdk(native):
|
||||
print('droiddeck-xbox: unknown %s next to the PlayFab Game Saves SDK in %s; left unchanged'
|
||||
% (PGS_NATIVE, directory), file=sys.stderr)
|
||||
continue
|
||||
replace_file(directory, PGS_NATIVE, data)
|
||||
elif not playfab_proxy(data):
|
||||
print('droiddeck-xbox: PlayFab Game Saves SDK with unknown exports in %s; left unchanged' % directory,
|
||||
file=sys.stderr)
|
||||
continue
|
||||
elif not kept_sdk(native):
|
||||
print('droiddeck-xbox: PlayFab save proxy without its SDK in %s; left unchanged' % directory,
|
||||
file=sys.stderr)
|
||||
continue
|
||||
if data != proxy:
|
||||
replace_file(directory, name, proxy)
|
||||
staged += 1
|
||||
except OSError as error:
|
||||
print('droiddeck-xbox: PlayFab save proxy not staged in %s (%s)' % (directory, error), file=sys.stderr)
|
||||
return staged
|
||||
|
||||
|
||||
def renew_lease(ask, channel, product, lease, stopped):
|
||||
while not stopped.wait(15):
|
||||
response = ask(channel, {'op': 'xbox-renew', 'id': product, 'lease': lease}, timeout=10)
|
||||
@@ -255,6 +421,12 @@ def launch(command, env):
|
||||
pass
|
||||
if roots:
|
||||
owned_env['XODUS_CONTENT_ROOTS'] = ';'.join(roots)
|
||||
# No DLL override for the proxy or the kept SDK: Wine has no builtin of either, so both load from the
|
||||
# game folder as they are. Forcing them native-only (as Nexus does) made Forza Horizon 6 fail with E:0-0-4.
|
||||
try:
|
||||
stage_playfab_proxy(folder)
|
||||
except Exception as error:
|
||||
print('droiddeck-xbox: PlayFab save proxy skipped (%s)' % error, file=sys.stderr)
|
||||
return wine([reply['exe']], owned_env)
|
||||
finally:
|
||||
stopped.set()
|
||||
|
||||
Executable
+62
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deletes test builds nobody can still need: a closed PR's at once, a merged PR's once a Preview build carries the merge."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from update_catalog import ApiError, GitHub, current_file, in_preview, previous_catalog, q # noqa: E402
|
||||
|
||||
TEST_TAG = re.compile(r"^pr-([1-9][0-9]*)(\.0)?$")
|
||||
|
||||
|
||||
def retired(pull: dict, source: GitHub, repo: str, preview_commit: str | None) -> bool:
|
||||
if pull.get("state") == "open":
|
||||
return False
|
||||
if not pull.get("merged_at"):
|
||||
return True
|
||||
return in_preview(source, repo, pull, preview_commit)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--source-repo", default=os.environ.get("GITHUB_REPOSITORY", "Droid-Deck/DroidDeck"))
|
||||
parser.add_argument("--ci-repo", default="Droid-Deck/DroidDeck-CI")
|
||||
parser.add_argument("--pr", type=int, help="only this PR's test build")
|
||||
args = parser.parse_args()
|
||||
source = GitHub(os.environ.get("SOURCE_GITHUB_TOKEN", ""))
|
||||
ci = GitHub(os.environ["CI_GITHUB_TOKEN"])
|
||||
catalog = previous_catalog(current_file(ci, args.ci_repo, "catalog.json")) or {}
|
||||
preview_commit = (catalog.get("preview") or {}).get("commit")
|
||||
failed = False
|
||||
for release in ci.get_all(f"/repos/{args.ci_repo}/releases"):
|
||||
tag = release.get("tag_name") or ""
|
||||
match = TEST_TAG.fullmatch(tag)
|
||||
if not match or (args.pr and int(match.group(1)) != args.pr):
|
||||
continue
|
||||
number = int(match.group(1))
|
||||
try:
|
||||
pull = source.get(f"/repos/{args.source_repo}/pulls/{number}")
|
||||
if not retired(pull, source, args.source_repo, preview_commit):
|
||||
print(f"Keeping {tag}: PR #{number} is {'open' if pull.get('state') == 'open' else 'merged, not yet in a Preview build'}")
|
||||
continue
|
||||
ci.request("DELETE", f"/repos/{args.ci_repo}/releases/{release['id']}")
|
||||
try:
|
||||
ci.request("DELETE", f"/repos/{args.ci_repo}/git/refs/tags/{q(tag)}")
|
||||
except ApiError as e:
|
||||
if e.status not in (404, 422):
|
||||
raise
|
||||
print(f"Deleted {tag}")
|
||||
except ApiError as e:
|
||||
print(f"{tag}: {e}", file=sys.stderr)
|
||||
failed = True
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -109,7 +109,8 @@ def required():
|
||||
['comet', 'GalaxyCommunication.exe', 'update-permissions.exe', 'LICENSE', 'version']]
|
||||
paths += ['assets/linuxfs/usr/local/lib/droiddeck-xbox/' + name for name in
|
||||
['xodus-cli', 'xodus-service', 'version', 'backend.lock.json', 'runtime.lock.json', 'LICENSE.xodus', 'LICENSE.nexus', 'LICENSE.LGPL-2.1', 'LICENSE.nghttp2',
|
||||
'windows/xgameruntime.dll', 'windows/winhttp.dll', 'windows/windows.web.dll', 'windows/twinapi.appcore.dll', 'windows/libnghttp2.dll']]
|
||||
'windows/xgameruntime.dll', 'windows/winhttp.dll', 'windows/windows.web.dll', 'windows/twinapi.appcore.dll', 'windows/libnghttp2.dll',
|
||||
'compat/PlayFabGameSave.dll', 'LICENSE.runtime-compat']]
|
||||
for driver in ['linux-wine11', 'linux-wine11-systhread']:
|
||||
paths += ['assets/directaudio/' + driver + '/' + name for name in
|
||||
['aarch64-unix/winedirectaudio.so', 'aarch64-windows/winedirectaudio.drv',
|
||||
|
||||
+25
-11
@@ -40,23 +40,37 @@ if [ "$pkg" != "$P" ]; then
|
||||
&& die "$variant: the manifest still names $P in an authority or task"
|
||||
fi
|
||||
|
||||
"$BUILD_TOOLS/zipalign" -p -f 4 "$work/renamed.apk" "$work/aligned.apk"
|
||||
|
||||
"$BUILD_TOOLS/apksigner" rotate --out "$work/lineage" \
|
||||
--old-signer --ks "$TESTKEY" --ks-type PKCS12 --ks-pass env:TESTKEY_PASSWORD \
|
||||
--ks-key-alias testkey --key-pass env:TESTKEY_PASSWORD --set-rollback false \
|
||||
--new-signer --ks "$RELEASE_KEYSTORE" --ks-type PKCS12 --ks-pass env:RELEASE_STORE_PASSWORD \
|
||||
--ks-key-alias "$RELEASE_KEY_ALIAS" --key-pass env:RELEASE_STORE_PASSWORD
|
||||
|
||||
"$BUILD_TOOLS/apksigner" sign \
|
||||
--ks "$TESTKEY" --ks-type PKCS12 --ks-pass env:TESTKEY_PASSWORD \
|
||||
--ks-key-alias testkey --key-pass env:TESTKEY_PASSWORD \
|
||||
--next-signer --ks "$RELEASE_KEYSTORE" --ks-type PKCS12 --ks-pass env:RELEASE_STORE_PASSWORD \
|
||||
--ks-key-alias "$RELEASE_KEY_ALIAS" --key-pass env:RELEASE_STORE_PASSWORD \
|
||||
--lineage "$work/lineage" --rotation-min-sdk-version 28 \
|
||||
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true --v4-signing-enabled false \
|
||||
--out "$out" "$work/aligned.apk"
|
||||
rm -f "$out.idsig"
|
||||
sign() {
|
||||
"$BUILD_TOOLS/apksigner" sign \
|
||||
--ks "$TESTKEY" --ks-type PKCS12 --ks-pass env:TESTKEY_PASSWORD \
|
||||
--ks-key-alias testkey --key-pass env:TESTKEY_PASSWORD \
|
||||
--next-signer --ks "$RELEASE_KEYSTORE" --ks-type PKCS12 --ks-pass env:RELEASE_STORE_PASSWORD \
|
||||
--ks-key-alias "$RELEASE_KEY_ALIAS" --key-pass env:RELEASE_STORE_PASSWORD \
|
||||
--lineage "$work/lineage" --rotation-min-sdk-version 28 \
|
||||
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true --v4-signing-enabled false \
|
||||
--out "$2" "$1"
|
||||
rm -f "$2.idsig"
|
||||
}
|
||||
|
||||
companion=assets/shortcuts.apk
|
||||
if unzip -l "$work/renamed.apk" "$companion" >/dev/null 2>&1; then
|
||||
mkdir -p "$work/companion/assets"
|
||||
unzip -p "$work/renamed.apk" "$companion" > "$work/companion-in.apk"
|
||||
sign "$work/companion-in.apk" "$work/companion/$companion"
|
||||
companion_v3=$("$BUILD_TOOLS/apksigner" verify --min-sdk-version 28 --print-certs "$work/companion/$companion" | sed -n 's/^.*Signer.* certificate SHA-256 digest: //p' | sort -u)
|
||||
[ "$companion_v3" = "$expected" ] || die "$variant: the system keys companion is not signed with DroidDeck's key"
|
||||
(cd "$work/companion" && zip -q -0 "$work/renamed.apk" "$companion")
|
||||
fi
|
||||
|
||||
"$BUILD_TOOLS/zipalign" -p -f 4 "$work/renamed.apk" "$work/aligned.apk"
|
||||
|
||||
sign "$work/aligned.apk" "$out"
|
||||
|
||||
"$BUILD_TOOLS/apksigner" verify --min-sdk-version 26 "$out" >/dev/null || die "$variant: does not verify"
|
||||
listing=$(unzip -l "$out")
|
||||
|
||||
@@ -184,8 +184,12 @@ def source_meta(source: GitHub, repo: str, ref: str):
|
||||
return code, version, variants, signer
|
||||
|
||||
|
||||
def asset_for_suffix(assets: list[dict], suffix: str, all_suffixes: list[str]):
|
||||
def asset_for_suffix(assets: list[dict], suffix: str, all_suffixes: list[str], commit: str = ""):
|
||||
others = [s for s in all_suffixes if s and s != suffix]
|
||||
# A test build's release briefly holds the previous push's APKs too; the one named for this commit wins.
|
||||
current = f"-{commit[:7].lower()}{suffix}.apk" if len(commit) >= 7 else None
|
||||
if current:
|
||||
assets = sorted(assets, key=lambda a: not (a.get("name") or "").lower().endswith(current))
|
||||
for asset in assets:
|
||||
name = asset.get("name", "")
|
||||
if not name.endswith(f"{suffix}.apk"):
|
||||
@@ -220,7 +224,7 @@ def release_entry(
|
||||
suffixes = [suffix for _, suffix in variants]
|
||||
apks = {}
|
||||
for package, suffix in variants:
|
||||
asset = asset_for_suffix(release.get("assets") or [], suffix, suffixes)
|
||||
asset = asset_for_suffix(release.get("assets") or [], suffix, suffixes, commit)
|
||||
if not asset:
|
||||
continue
|
||||
asset.update(
|
||||
@@ -246,24 +250,30 @@ def release_entry(
|
||||
}
|
||||
|
||||
|
||||
def complete_apks(preview: dict, variants: list[tuple[str, str]]) -> bool:
|
||||
apks = preview.get("apks") or {}
|
||||
return set(apks) == {package for package, _ in variants} and all(
|
||||
SHA256.fullmatch((apk.get("sha256") or "").lower()) and SHA256.fullmatch((apk.get("signerSha256") or "").lower())
|
||||
for apk in apks.values()
|
||||
)
|
||||
|
||||
|
||||
def newest_complete(ordered: list[dict], variants: list[tuple[str, str]]) -> dict | None:
|
||||
"""The Preview to offer and to judge merges by: the newest one whose APKs have all been uploaded."""
|
||||
return next((p for p in ordered if complete_apks(p, variants)), None)
|
||||
|
||||
|
||||
def preview_history_entry(release: dict, preview: dict, variants: list[tuple[str, str]]):
|
||||
tag = release.get("tag_name") or ""
|
||||
tag_match = MAIN_TAG.fullmatch(tag)
|
||||
commit = (preview.get("commit") or "").lower()
|
||||
expected_packages = {package for package, _ in variants}
|
||||
apks = preview.get("apks") or {}
|
||||
if (
|
||||
release.get("draft")
|
||||
or not release.get("prerelease")
|
||||
or not tag_match
|
||||
or not re.fullmatch(r"[0-9a-f]{40}", commit)
|
||||
or not commit.startswith(tag_match.group(1))
|
||||
or set(apks) != expected_packages
|
||||
or any(
|
||||
not SHA256.fullmatch((apk.get("sha256") or "").lower())
|
||||
or not SHA256.fullmatch((apk.get("signerSha256") or "").lower())
|
||||
for apk in apks.values()
|
||||
)
|
||||
or not complete_apks(preview, variants)
|
||||
):
|
||||
return None
|
||||
return {
|
||||
@@ -341,6 +351,38 @@ class Cache:
|
||||
return self.commits[sha]
|
||||
|
||||
|
||||
MERGED_GRACE_DAYS = 3
|
||||
|
||||
|
||||
def in_preview(source: GitHub, repo: str, pull: dict, preview_commit: str | None, now_millis: int | None = None) -> bool:
|
||||
"""Whether the newest Preview build was built from a main that already holds the PR's merge.
|
||||
|
||||
A merge that main's build skips (documentation only) never reaches a Preview build, so after
|
||||
MERGED_GRACE_DAYS it counts as carried anyway.
|
||||
"""
|
||||
merge = pull.get("merge_commit_sha") or ""
|
||||
merged_at = iso_millis(pull.get("merged_at"))
|
||||
if not merged_at or not merge:
|
||||
return False
|
||||
now = now_millis if now_millis is not None else int(time.time() * 1000)
|
||||
if now - merged_at > MERGED_GRACE_DAYS * 86_400_000:
|
||||
return True
|
||||
if not preview_commit:
|
||||
return False
|
||||
try:
|
||||
status = source.get(f"/repos/{repo}/compare/{q(merge)}...{q(preview_commit)}").get("status")
|
||||
except ApiError:
|
||||
return False
|
||||
return status in ("ahead", "identical")
|
||||
|
||||
|
||||
def keeps_test_build(pull: dict) -> bool:
|
||||
"""An open PR keeps its test build; a merged one keeps it until a Preview build carries the merge."""
|
||||
if pull.get("draft") or (pull.get("base") or {}).get("ref") != "main":
|
||||
return False
|
||||
return pull.get("state") == "open" or bool(pull.get("merged_at"))
|
||||
|
||||
|
||||
def unique_previews(previews: list[dict]) -> list[dict]:
|
||||
ordered = sorted(previews, key=lambda r: (r.get("committedAt") or r["publishedAt"], r["publishedAt"]), reverse=True)
|
||||
result = []
|
||||
@@ -381,6 +423,7 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str, pr
|
||||
previews = []
|
||||
preview_history = []
|
||||
tests = []
|
||||
merged_pulls: dict[int, dict | None] = {}
|
||||
for release in releases:
|
||||
if release.get("draft"):
|
||||
continue
|
||||
@@ -421,7 +464,7 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str, pr
|
||||
pull = source.get(f"/repos/{source_repo}/pulls/{pr}")
|
||||
except ApiError:
|
||||
continue
|
||||
if pull.get("state") != "open" or pull.get("draft") or pull.get("base", {}).get("ref") != "main":
|
||||
if not keeps_test_build(pull):
|
||||
continue
|
||||
commit = release_body_value(body, "Commit")
|
||||
if not commit or not re.fullmatch(r"[0-9a-f]{7,40}", commit):
|
||||
@@ -443,6 +486,7 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str, pr
|
||||
except (ApiError, KeyError):
|
||||
pass
|
||||
title, summary = ci_description(release)
|
||||
merged_pulls[pr] = pull if pull.get("state") != "open" else None
|
||||
tests.append(
|
||||
release_entry(
|
||||
release,
|
||||
@@ -468,6 +512,9 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str, pr
|
||||
)
|
||||
|
||||
ordered = unique_previews(previews)
|
||||
usable = newest_complete(ordered, main_variants)
|
||||
newest = usable["commit"] if usable else None
|
||||
tests = [t for t in tests if not (merged_pulls.get(t["pr"]) and in_preview(source, source_repo, merged_pulls[t["pr"]], newest))]
|
||||
tests.sort(key=lambda r: r["publishedAt"], reverse=True)
|
||||
return {
|
||||
"schema": 1,
|
||||
@@ -476,7 +523,7 @@ def build_catalog(source: GitHub, ci: GitHub, source_repo: str, ci_repo: str, pr
|
||||
"generatedAt": int(time.time() * 1000),
|
||||
"mainVersionCode": main_code,
|
||||
"stable": stable,
|
||||
"preview": ordered[0] if ordered else None,
|
||||
"preview": usable,
|
||||
"recentPreviews": recent_previews(preview_history),
|
||||
"previews": ordered,
|
||||
"tests": tests,
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
#include "mali_compat.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <spirv/unified1/spirv.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
VKAPI_ATTR VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface *interface);
|
||||
|
||||
struct object { void *dispatch; };
|
||||
static int instance_table, device_table;
|
||||
static struct object mock_instance = {&instance_table};
|
||||
static struct object mock_lacking = {&instance_table}, mock_capable = {&instance_table};
|
||||
static struct object mock_device = {&device_table}, mock_command_buffer = {&device_table};
|
||||
|
||||
static VkBool32 driver_saw_dual_source;
|
||||
static uint32_t *driver_code;
|
||||
static size_t driver_code_count;
|
||||
static VkPipelineColorBlendAttachmentState driver_attachments[4];
|
||||
static uint32_t driver_attachment_count;
|
||||
static VkColorBlendEquationEXT driver_equations[4];
|
||||
static uint32_t driver_equation_count;
|
||||
|
||||
#define MAIN 1
|
||||
#define VOID 2
|
||||
#define FUNCTION 3
|
||||
#define FLOAT 4
|
||||
#define VEC4 5
|
||||
#define OUTPUT_VEC4 6
|
||||
#define COLOR 7
|
||||
#define SECOND 8
|
||||
#define ONE 9
|
||||
#define ONES 10
|
||||
#define OUTPUT_FLOAT 11
|
||||
#define UINT 12
|
||||
#define ZERO 13
|
||||
#define LABEL 14
|
||||
#define CHANNEL 15
|
||||
#define BOUND 16
|
||||
|
||||
struct spirv { uint32_t w[256]; size_t n; };
|
||||
|
||||
static void op(struct spirv *s, SpvOp code, uint32_t count, const uint32_t *operands)
|
||||
{
|
||||
s->w[s->n++] = (count + 1) << 16 | code;
|
||||
for (uint32_t i = 0; i < count; i++)
|
||||
s->w[s->n++] = operands[i];
|
||||
}
|
||||
|
||||
#define OP(s, code, ...) \
|
||||
do { \
|
||||
const uint32_t operands_[] = {__VA_ARGS__}; \
|
||||
op(s, code, sizeof(operands_) / sizeof(operands_[0]), operands_); \
|
||||
} while (0)
|
||||
|
||||
static void fragment_shader(struct spirv *s, uint32_t version, bool dual_source)
|
||||
{
|
||||
s->n = 0;
|
||||
const uint32_t header[5] = {SpvMagicNumber, version, 0, BOUND, 0};
|
||||
memcpy(s->w, header, sizeof(header));
|
||||
s->n = 5;
|
||||
OP(s, SpvOpCapability, SpvCapabilityShader);
|
||||
OP(s, SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450);
|
||||
OP(s, SpvOpEntryPoint, SpvExecutionModelFragment, MAIN, 0x6e69616d, 0, COLOR, SECOND);
|
||||
OP(s, SpvOpExecutionMode, MAIN, SpvExecutionModeOriginUpperLeft);
|
||||
OP(s, SpvOpDecorate, COLOR, SpvDecorationLocation, 0);
|
||||
if (dual_source) {
|
||||
OP(s, SpvOpDecorate, COLOR, SpvDecorationIndex, 0);
|
||||
OP(s, SpvOpDecorate, SECOND, SpvDecorationLocation, 0);
|
||||
OP(s, SpvOpDecorate, SECOND, SpvDecorationIndex, 1);
|
||||
} else {
|
||||
OP(s, SpvOpDecorate, SECOND, SpvDecorationLocation, 1);
|
||||
}
|
||||
OP(s, SpvOpTypeVoid, VOID);
|
||||
OP(s, SpvOpTypeFunction, FUNCTION, VOID);
|
||||
OP(s, SpvOpTypeFloat, FLOAT, 32);
|
||||
OP(s, SpvOpTypeVector, VEC4, FLOAT, 4);
|
||||
OP(s, SpvOpTypePointer, OUTPUT_VEC4, SpvStorageClassOutput, VEC4);
|
||||
OP(s, SpvOpTypePointer, OUTPUT_FLOAT, SpvStorageClassOutput, FLOAT);
|
||||
OP(s, SpvOpTypeInt, UINT, 32, 0);
|
||||
OP(s, SpvOpConstant, FLOAT, ONE, 0x3f800000);
|
||||
OP(s, SpvOpConstantComposite, VEC4, ONES, ONE, ONE, ONE, ONE);
|
||||
OP(s, SpvOpConstant, UINT, ZERO, 0);
|
||||
OP(s, SpvOpVariable, OUTPUT_VEC4, COLOR, SpvStorageClassOutput);
|
||||
OP(s, SpvOpVariable, OUTPUT_VEC4, SECOND, SpvStorageClassOutput);
|
||||
OP(s, SpvOpFunction, VOID, MAIN, SpvFunctionControlMaskNone, FUNCTION);
|
||||
OP(s, SpvOpLabel, LABEL);
|
||||
OP(s, SpvOpStore, COLOR, ONES);
|
||||
OP(s, SpvOpStore, SECOND, ONES);
|
||||
OP(s, SpvOpAccessChain, OUTPUT_FLOAT, CHANNEL, SECOND, ZERO);
|
||||
OP(s, SpvOpStore, CHANNEL, ONE);
|
||||
s->w[s->n++] = 1u << 16 | SpvOpReturn;
|
||||
s->w[s->n++] = 1u << 16 | SpvOpFunctionEnd;
|
||||
}
|
||||
|
||||
static const uint32_t *find(const uint32_t *w, size_t count, SpvOp code, uint32_t position, uint32_t value)
|
||||
{
|
||||
for (size_t i = 5; i < count; i += w[i] >> 16) {
|
||||
if ((w[i] & 0xffff) == code && (w[i] >> 16) > position && w[i + position] == value)
|
||||
return &w[i];
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static uint32_t storage_of(const uint32_t *w, size_t count, uint32_t pointer_type)
|
||||
{
|
||||
const uint32_t *type = find(w, count, SpvOpTypePointer, 1, pointer_type);
|
||||
assert(type);
|
||||
return type[2];
|
||||
}
|
||||
|
||||
static bool in_interface(const uint32_t *w, size_t count, uint32_t id)
|
||||
{
|
||||
const uint32_t *entry = find(w, count, SpvOpEntryPoint, 2, MAIN);
|
||||
assert(entry);
|
||||
for (uint32_t i = 5; i < entry[0] >> 16; i++) {
|
||||
if (entry[i] == id)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static void save(const char *directory, const char *name, const uint32_t *words, size_t count)
|
||||
{
|
||||
if (!directory)
|
||||
return;
|
||||
char path[512];
|
||||
snprintf(path, sizeof(path), "%s/%s", directory, name);
|
||||
FILE *file = fopen(path, "wb");
|
||||
assert(file);
|
||||
assert(fwrite(words, sizeof(uint32_t), count, file) == count);
|
||||
fclose(file);
|
||||
}
|
||||
|
||||
static void check_stripped(const uint32_t *w, size_t count, bool second_listed)
|
||||
{
|
||||
assert(!spirv_uses_dual_source(w, count));
|
||||
const uint32_t *second = find(w, count, SpvOpVariable, 2, SECOND);
|
||||
const uint32_t *color = find(w, count, SpvOpVariable, 2, COLOR);
|
||||
assert(second && second[3] == SpvStorageClassPrivate);
|
||||
assert(storage_of(w, count, second[1]) == SpvStorageClassPrivate);
|
||||
assert(color && color[3] == SpvStorageClassOutput && color[1] == OUTPUT_VEC4);
|
||||
assert(!find(w, count, SpvOpDecorate, 1, SECOND));
|
||||
const uint32_t *location = find(w, count, SpvOpDecorate, 1, COLOR);
|
||||
assert(location && location[2] == SpvDecorationLocation && location[3] == 0);
|
||||
const uint32_t *channel = find(w, count, SpvOpAccessChain, 2, CHANNEL);
|
||||
assert(channel && storage_of(w, count, channel[1]) == SpvStorageClassPrivate);
|
||||
assert(storage_of(w, count, OUTPUT_FLOAT) == SpvStorageClassOutput);
|
||||
assert(in_interface(w, count, COLOR));
|
||||
assert(in_interface(w, count, SECOND) == second_listed);
|
||||
}
|
||||
|
||||
static void test_spirv(const char *directory)
|
||||
{
|
||||
struct spirv dual, plain;
|
||||
struct spirv_code out;
|
||||
|
||||
fragment_shader(&dual, 0x00010000, true);
|
||||
save(directory, "dual-1.0.spv", dual.w, dual.n);
|
||||
assert(spirv_uses_dual_source(dual.w, dual.n));
|
||||
assert(spirv_strip_dual_source(dual.w, dual.n, &out));
|
||||
check_stripped(out.words, out.count, false);
|
||||
save(directory, "stripped-1.0.spv", out.words, out.count);
|
||||
free(out.words);
|
||||
|
||||
fragment_shader(&dual, 0x00010400, true);
|
||||
assert(spirv_strip_dual_source(dual.w, dual.n, &out));
|
||||
check_stripped(out.words, out.count, true);
|
||||
save(directory, "stripped-1.4.spv", out.words, out.count);
|
||||
free(out.words);
|
||||
|
||||
fragment_shader(&plain, 0x00010000, false);
|
||||
save(directory, "plain-1.0.spv", plain.w, plain.n);
|
||||
assert(!spirv_uses_dual_source(plain.w, plain.n));
|
||||
assert(spirv_strip_dual_source(plain.w, plain.n, &out));
|
||||
assert(out.count == plain.n && !memcmp(out.words, plain.w, plain.n * sizeof(uint32_t)));
|
||||
free(out.words);
|
||||
|
||||
uint32_t truncated[5] = {SpvMagicNumber, 0x00010000, 0, BOUND, 0};
|
||||
assert(!spirv_uses_dual_source(truncated, 5));
|
||||
assert(!spirv_strip_dual_source(truncated, 5, &out));
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
|
||||
VkInstance *instance)
|
||||
{
|
||||
*instance = (VkInstance)&mock_instance;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_destroy_instance(VkInstance instance, const VkAllocationCallbacks *allocator) {}
|
||||
|
||||
static VkResult VKAPI_CALL mock_extensions(VkPhysicalDevice physical, const char *layer, uint32_t *count,
|
||||
VkExtensionProperties *properties)
|
||||
{
|
||||
*count = 0;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_features(VkPhysicalDevice physical, VkPhysicalDeviceFeatures *features)
|
||||
{
|
||||
memset(features, 0, sizeof(*features));
|
||||
features->dualSrcBlend = physical == (VkPhysicalDevice)&mock_capable;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_features2(VkPhysicalDevice physical, VkPhysicalDeviceFeatures2 *features)
|
||||
{
|
||||
mock_features(physical, &features->features);
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_properties(VkPhysicalDevice physical, VkPhysicalDeviceProperties *properties)
|
||||
{
|
||||
memset(properties, 0, sizeof(*properties));
|
||||
strcpy(properties->deviceName, "mock");
|
||||
properties->limits.maxFragmentDualSrcAttachments = physical == (VkPhysicalDevice)&mock_capable;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_properties2(VkPhysicalDevice physical, VkPhysicalDeviceProperties2 *properties)
|
||||
{
|
||||
mock_properties(physical, &properties->properties);
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_memory_properties(VkPhysicalDevice physical, VkPhysicalDeviceMemoryProperties *properties)
|
||||
{
|
||||
memset(properties, 0, sizeof(*properties));
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_format_properties2(VkPhysicalDevice physical, VkFormat format, VkFormatProperties2 *out)
|
||||
{
|
||||
memset(&out->formatProperties, 0, sizeof(out->formatProperties));
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL mock_image_format_properties2(VkPhysicalDevice physical,
|
||||
const VkPhysicalDeviceImageFormatInfo2 *info,
|
||||
VkImageFormatProperties2 *properties)
|
||||
{
|
||||
return VK_ERROR_FORMAT_NOT_SUPPORTED;
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL mock_create_device(VkPhysicalDevice physical, const VkDeviceCreateInfo *info,
|
||||
const VkAllocationCallbacks *allocator, VkDevice *device)
|
||||
{
|
||||
driver_saw_dual_source = info->pEnabledFeatures && info->pEnabledFeatures->dualSrcBlend;
|
||||
for (const VkBaseInStructure *p = info->pNext; p; p = p->pNext) {
|
||||
if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 &&
|
||||
((const VkPhysicalDeviceFeatures2 *)p)->features.dualSrcBlend)
|
||||
driver_saw_dual_source = VK_TRUE;
|
||||
}
|
||||
VkPhysicalDeviceFeatures supported;
|
||||
mock_features(physical, &supported);
|
||||
if (driver_saw_dual_source && !supported.dualSrcBlend)
|
||||
return VK_ERROR_FEATURE_NOT_PRESENT;
|
||||
*device = (VkDevice)&mock_device;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_destroy_device(VkDevice device, const VkAllocationCallbacks *allocator) {}
|
||||
|
||||
static void capture_code(const uint32_t *words, size_t size)
|
||||
{
|
||||
free(driver_code);
|
||||
driver_code_count = size / sizeof(uint32_t);
|
||||
driver_code = malloc(size);
|
||||
memcpy(driver_code, words, size);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL mock_create_shader_module(VkDevice device, const VkShaderModuleCreateInfo *info,
|
||||
const VkAllocationCallbacks *allocator, VkShaderModule *module)
|
||||
{
|
||||
capture_code(info->pCode, info->codeSize);
|
||||
*module = (VkShaderModule)0x1000;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_destroy_shader_module(VkDevice device, VkShaderModule module,
|
||||
const VkAllocationCallbacks *allocator) {}
|
||||
|
||||
static VkResult VKAPI_CALL mock_create_graphics_pipelines(VkDevice device, VkPipelineCache cache, uint32_t count,
|
||||
const VkGraphicsPipelineCreateInfo *infos,
|
||||
const VkAllocationCallbacks *allocator, VkPipeline *pipelines)
|
||||
{
|
||||
const VkPipelineColorBlendStateCreateInfo *blend = infos[0].pColorBlendState;
|
||||
driver_attachment_count = blend->attachmentCount;
|
||||
memcpy(driver_attachments, blend->pAttachments, blend->attachmentCount * sizeof(*driver_attachments));
|
||||
const VkShaderModuleCreateInfo *module = infos[0].pStages[0].pNext;
|
||||
assert(module && module->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
|
||||
capture_code(module->pCode, module->codeSize);
|
||||
pipelines[0] = (VkPipeline)0x2000;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL mock_set_blend_equation(VkCommandBuffer cmd, uint32_t first, uint32_t count,
|
||||
const VkColorBlendEquationEXT *equations)
|
||||
{
|
||||
for (uint32_t i = 0; i < count; i++)
|
||||
driver_equations[first + i] = equations[i];
|
||||
if (first + count > driver_equation_count)
|
||||
driver_equation_count = first + count;
|
||||
}
|
||||
|
||||
#define MOCK(name, function) if (!strcmp(requested, name)) return (PFN_vkVoidFunction)function
|
||||
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gipa(VkInstance instance, const char *requested)
|
||||
{
|
||||
MOCK("vkCreateInstance", mock_create_instance);
|
||||
MOCK("vkDestroyInstance", mock_destroy_instance);
|
||||
MOCK("vkCreateDevice", mock_create_device);
|
||||
MOCK("vkEnumerateDeviceExtensionProperties", mock_extensions);
|
||||
MOCK("vkGetPhysicalDeviceFeatures", mock_features);
|
||||
MOCK("vkGetPhysicalDeviceFeatures2", mock_features2);
|
||||
MOCK("vkGetPhysicalDeviceProperties", mock_properties);
|
||||
MOCK("vkGetPhysicalDeviceProperties2", mock_properties2);
|
||||
MOCK("vkGetPhysicalDeviceMemoryProperties", mock_memory_properties);
|
||||
MOCK("vkGetPhysicalDeviceFormatProperties2", mock_format_properties2);
|
||||
MOCK("vkGetPhysicalDeviceImageFormatProperties2", mock_image_format_properties2);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_gdpa(VkDevice device, const char *requested)
|
||||
{
|
||||
MOCK("vkDestroyDevice", mock_destroy_device);
|
||||
MOCK("vkCreateShaderModule", mock_create_shader_module);
|
||||
MOCK("vkDestroyShaderModule", mock_destroy_shader_module);
|
||||
MOCK("vkCreateGraphicsPipelines", mock_create_graphics_pipelines);
|
||||
MOCK("vkCmdSetColorBlendEquationEXT", mock_set_blend_equation);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static PFN_vkGetInstanceProcAddr layer_gipa;
|
||||
static PFN_vkGetDeviceProcAddr layer_gdpa;
|
||||
|
||||
static VkResult create_device(VkPhysicalDevice physical, const void *chain, const VkPhysicalDeviceFeatures *enabled,
|
||||
VkDevice *device)
|
||||
{
|
||||
VkLayerDeviceLink link = {NULL, mock_gipa, mock_gdpa};
|
||||
VkLayerDeviceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, chain, VK_LAYER_LINK_INFO, {&link}};
|
||||
VkDeviceCreateInfo info = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &loader, 0, 0, NULL, 0, NULL, 0, NULL, enabled};
|
||||
PFN_vkCreateDevice create = (PFN_vkCreateDevice)layer_gipa((VkInstance)&mock_instance, "vkCreateDevice");
|
||||
return create(physical, &info, NULL, device);
|
||||
}
|
||||
|
||||
static void destroy_device(VkDevice device)
|
||||
{
|
||||
((PFN_vkDestroyDevice)layer_gdpa(device, "vkDestroyDevice"))(device, NULL);
|
||||
}
|
||||
|
||||
static const VkPipelineColorBlendAttachmentState dual_attachment = {
|
||||
VK_TRUE, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_OP_ADD,
|
||||
VK_BLEND_FACTOR_SRC1_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, VK_BLEND_OP_ADD, 0xf,
|
||||
};
|
||||
|
||||
static const VkPipelineColorBlendAttachmentState plain_attachment = {
|
||||
VK_TRUE, VK_BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_CONSTANT_ALPHA, VK_BLEND_OP_ADD,
|
||||
VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA, VK_BLEND_OP_ADD, 0xf,
|
||||
};
|
||||
|
||||
static void create_pipeline(VkDevice device, VkPipelineColorBlendAttachmentState *attachments,
|
||||
VkShaderModuleCreateInfo *module)
|
||||
{
|
||||
VkPipelineShaderStageCreateInfo stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, module, 0,
|
||||
VK_SHADER_STAGE_FRAGMENT_BIT, VK_NULL_HANDLE, "main", NULL};
|
||||
VkPipelineColorBlendStateCreateInfo blend = {VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0,
|
||||
VK_FALSE, VK_LOGIC_OP_COPY, 2, attachments, {0}};
|
||||
VkGraphicsPipelineCreateInfo info = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 1,
|
||||
.pStages = &stage, .pColorBlendState = &blend};
|
||||
VkPipeline pipeline;
|
||||
PFN_vkCreateGraphicsPipelines create =
|
||||
(PFN_vkCreateGraphicsPipelines)layer_gdpa(device, "vkCreateGraphicsPipelines");
|
||||
assert(create(device, VK_NULL_HANDLE, 1, &info, NULL, &pipeline) == VK_SUCCESS);
|
||||
assert(stage.pNext == module && blend.pAttachments == attachments);
|
||||
}
|
||||
|
||||
static bool same_attachment(const VkPipelineColorBlendAttachmentState *a, const VkPipelineColorBlendAttachmentState *b)
|
||||
{
|
||||
return !memcmp(a, b, sizeof(*a));
|
||||
}
|
||||
|
||||
static void test_lacking_device(void)
|
||||
{
|
||||
VkPhysicalDevice physical = (VkPhysicalDevice)&mock_lacking;
|
||||
VkPhysicalDeviceFeatures features;
|
||||
((PFN_vkGetPhysicalDeviceFeatures)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures"))(physical,
|
||||
&features);
|
||||
assert(features.dualSrcBlend);
|
||||
VkPhysicalDeviceFeatures2 queried = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
|
||||
((PFN_vkGetPhysicalDeviceFeatures2)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures2"))(physical,
|
||||
&queried);
|
||||
assert(queried.features.dualSrcBlend);
|
||||
VkPhysicalDeviceProperties properties;
|
||||
((PFN_vkGetPhysicalDeviceProperties)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceProperties"))(
|
||||
physical, &properties);
|
||||
assert(properties.limits.maxFragmentDualSrcAttachments == 1);
|
||||
|
||||
VkDevice device;
|
||||
VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE};
|
||||
assert(create_device(physical, NULL, &enabled, &device) == VK_SUCCESS);
|
||||
assert(!driver_saw_dual_source && enabled.dualSrcBlend);
|
||||
destroy_device(device);
|
||||
|
||||
VkPhysicalDeviceFeatures2 chained = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, NULL, {.dualSrcBlend = VK_TRUE}};
|
||||
assert(create_device(physical, &chained, NULL, &device) == VK_SUCCESS);
|
||||
assert(!driver_saw_dual_source && chained.features.dualSrcBlend);
|
||||
|
||||
struct spirv dual;
|
||||
fragment_shader(&dual, 0x00010300, true);
|
||||
VkShaderModuleCreateInfo module = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, dual.n * sizeof(uint32_t),
|
||||
dual.w};
|
||||
VkShaderModule handle;
|
||||
assert(((PFN_vkCreateShaderModule)layer_gdpa(device, "vkCreateShaderModule"))(device, &module, NULL, &handle) ==
|
||||
VK_SUCCESS);
|
||||
check_stripped(driver_code, driver_code_count, false);
|
||||
((PFN_vkDestroyShaderModule)layer_gdpa(device, "vkDestroyShaderModule"))(device, handle, NULL);
|
||||
|
||||
VkPipelineColorBlendAttachmentState attachments[2] = {dual_attachment, plain_attachment};
|
||||
create_pipeline(device, attachments, &module);
|
||||
check_stripped(driver_code, driver_code_count, false);
|
||||
assert(module.pCode == dual.w && spirv_uses_dual_source(module.pCode, module.codeSize / sizeof(uint32_t)));
|
||||
assert(driver_attachment_count == 2);
|
||||
assert(driver_attachments[0].srcColorBlendFactor == VK_BLEND_FACTOR_ONE);
|
||||
assert(driver_attachments[0].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
|
||||
assert(driver_attachments[0].srcAlphaBlendFactor == VK_BLEND_FACTOR_SRC_ALPHA);
|
||||
assert(driver_attachments[0].dstAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
|
||||
assert(driver_attachments[0].colorWriteMask == 0xf && driver_attachments[0].blendEnable);
|
||||
assert(same_attachment(&driver_attachments[1], &plain_attachment));
|
||||
assert(same_attachment(&attachments[0], &dual_attachment));
|
||||
|
||||
VkColorBlendEquationEXT equations[2] = {
|
||||
{VK_BLEND_FACTOR_SRC1_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE,
|
||||
VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD},
|
||||
{VK_BLEND_FACTOR_DST_COLOR, VK_BLEND_FACTOR_SRC_COLOR, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
|
||||
VK_BLEND_FACTOR_CONSTANT_COLOR, VK_BLEND_OP_ADD},
|
||||
};
|
||||
VkCommandBuffer cmd = (VkCommandBuffer)&mock_command_buffer;
|
||||
PFN_vkCmdSetColorBlendEquationEXT set_equation =
|
||||
(PFN_vkCmdSetColorBlendEquationEXT)layer_gdpa(device, "vkCmdSetColorBlendEquationEXT");
|
||||
assert(set_equation != (PFN_vkCmdSetColorBlendEquationEXT)mock_set_blend_equation);
|
||||
set_equation(cmd, 1, 2, equations);
|
||||
assert(driver_equation_count == 3);
|
||||
assert(driver_equations[1].srcColorBlendFactor == VK_BLEND_FACTOR_SRC_ALPHA);
|
||||
assert(driver_equations[1].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA);
|
||||
assert(driver_equations[1].srcAlphaBlendFactor == VK_BLEND_FACTOR_ONE);
|
||||
assert(!memcmp(&driver_equations[2], &equations[1], sizeof(equations[1])));
|
||||
assert(equations[0].srcColorBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR);
|
||||
destroy_device(device);
|
||||
}
|
||||
|
||||
static void test_capable_device(void)
|
||||
{
|
||||
VkPhysicalDevice physical = (VkPhysicalDevice)&mock_capable;
|
||||
VkPhysicalDeviceProperties properties;
|
||||
((PFN_vkGetPhysicalDeviceProperties)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceProperties"))(
|
||||
physical, &properties);
|
||||
assert(properties.limits.maxFragmentDualSrcAttachments == 1);
|
||||
|
||||
VkDevice device;
|
||||
VkPhysicalDeviceFeatures enabled = {.dualSrcBlend = VK_TRUE};
|
||||
assert(create_device(physical, NULL, &enabled, &device) == VK_SUCCESS && driver_saw_dual_source);
|
||||
assert(layer_gdpa(device, "vkCreateGraphicsPipelines") == (PFN_vkVoidFunction)mock_create_graphics_pipelines);
|
||||
assert(layer_gdpa(device, "vkCreateShaderModule") == (PFN_vkVoidFunction)mock_create_shader_module);
|
||||
assert(layer_gdpa(device, "vkCmdSetColorBlendEquationEXT") == (PFN_vkVoidFunction)mock_set_blend_equation);
|
||||
destroy_device(device);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
test_spirv(argc > 1 ? argv[1] : NULL);
|
||||
|
||||
setenv("WINEPREFIX", "/nonexistent", 1);
|
||||
unsetenv("DROIDDECK_MALI_COMPAT");
|
||||
unsetenv("DROIDDECK_MALI_COMPAT_TRACE");
|
||||
VkNegotiateLayerInterface negotiate = {LAYER_NEGOTIATE_INTERFACE_STRUCT, NULL, 2, NULL, NULL, NULL};
|
||||
assert(vkNegotiateLoaderLayerInterfaceVersion(&negotiate) == VK_SUCCESS);
|
||||
layer_gipa = negotiate.pfnGetInstanceProcAddr;
|
||||
layer_gdpa = negotiate.pfnGetDeviceProcAddr;
|
||||
|
||||
VkLayerInstanceLink link = {NULL, mock_gipa, NULL};
|
||||
VkLayerInstanceCreateInfo loader = {VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO, NULL, VK_LAYER_LINK_INFO, {&link}};
|
||||
VkInstanceCreateInfo info = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = &loader};
|
||||
VkInstance instance;
|
||||
PFN_vkCreateInstance create_instance = (PFN_vkCreateInstance)layer_gipa(NULL, "vkCreateInstance");
|
||||
assert(create_instance(&info, NULL, &instance) == VK_SUCCESS);
|
||||
|
||||
test_lacking_device();
|
||||
test_capable_device();
|
||||
|
||||
((PFN_vkDestroyInstance)layer_gipa(instance, "vkDestroyInstance"))(instance, NULL);
|
||||
free(driver_code);
|
||||
printf("mali compat layer ok\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define BTN_LEFT 0x110
|
||||
#define BTN_RIGHT 0x111
|
||||
#define BTN_MIDDLE 0x112
|
||||
#define INPUT_SPACE_W 1920
|
||||
#define INPUT_SPACE_H 1080
|
||||
#include "input_msg.inc"
|
||||
#include "pen_state.inc"
|
||||
|
||||
enum { MOTION, PRESS, RELEASE };
|
||||
struct event { int kind; uint32_t button; double x, y; int raw_valid; };
|
||||
struct constraint { int is_lock; };
|
||||
static struct constraint *g_active_constraint;
|
||||
static struct surface *g_grab;
|
||||
static int g_raw_valid;
|
||||
static struct event events[16];
|
||||
static int nevents, logs;
|
||||
static uint32_t held;
|
||||
|
||||
static void scene_size(int *w, int *h) { *w = 3840; *h = 2160; }
|
||||
static void vkp_output_size(int *w, int *h) { *w = 0; *h = 0; }
|
||||
static int vkp_output_to_scene(double ox, double oy, double *x, double *y) {
|
||||
(void)ox; (void)oy; (void)x; (void)y;
|
||||
return 0;
|
||||
}
|
||||
static void pointer_event(double x, double y, uint32_t button, int pressed) {
|
||||
assert(!button && !pressed && nevents < 16);
|
||||
events[nevents++] = (struct event){MOTION, 0, x, y, g_raw_valid};
|
||||
g_raw_valid = 1;
|
||||
}
|
||||
static void pointer_button(uint32_t button, int pressed) {
|
||||
assert(button >= BTN_LEFT && button <= BTN_MIDDLE && nevents < 16);
|
||||
uint32_t bit = 1u << (button - BTN_LEFT);
|
||||
if (pressed) assert(!(held & bit));
|
||||
else assert(held & bit);
|
||||
held = pressed ? held | bit : held & ~bit;
|
||||
events[nevents++] = (struct event){pressed ? PRESS : RELEASE, button, 0, 0, g_raw_valid};
|
||||
}
|
||||
static void pen_log_target(void) { logs++; }
|
||||
#include "pen.inc"
|
||||
|
||||
static void pen(int flags, double x, double y) {
|
||||
struct input_msg m = {13, flags, (int)(x * 256), (int)(y * 256), 0};
|
||||
nevents = 0;
|
||||
deliver_pen(&m);
|
||||
}
|
||||
|
||||
static void motion(int i, double x, double y) {
|
||||
assert(events[i].kind == MOTION && events[i].x == x && events[i].y == y);
|
||||
}
|
||||
|
||||
static void button(int i, int kind, uint32_t code) {
|
||||
assert(events[i].kind == kind && events[i].button == code);
|
||||
}
|
||||
|
||||
static void expect(int count, uint32_t buttons) {
|
||||
assert(nevents == count && held == buttons);
|
||||
assert(g_pen.buttons == (int)buttons);
|
||||
}
|
||||
|
||||
#define L (1u << 0)
|
||||
#define R (1u << 1)
|
||||
#define M (1u << 2)
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
const char *c = argv[1];
|
||||
if (!strcmp(c, "hover")) {
|
||||
pen(PEN_IN, 100.5, 50.25);
|
||||
expect(1, 0); motion(0, 201, 100.5);
|
||||
pen(PEN_IN, 2000, -4);
|
||||
expect(1, 0); motion(0, 3839, 0);
|
||||
assert(g_pen.in && logs == 2);
|
||||
pen(0, 2000, -4);
|
||||
expect(0, 0);
|
||||
assert(!g_pen.in && logs == 2);
|
||||
} else if (!strcmp(c, "tip")) {
|
||||
pen(PEN_IN, 10, 10);
|
||||
expect(1, 0);
|
||||
pen(PEN_IN | PEN_TIP, 10, 10);
|
||||
expect(2, L); motion(0, 20, 20); button(1, PRESS, BTN_LEFT);
|
||||
pen(PEN_IN | PEN_TIP, 11, 10);
|
||||
expect(1, L); motion(0, 22, 20);
|
||||
pen(PEN_IN, 12, 10);
|
||||
expect(2, 0); motion(0, 24, 20); button(1, RELEASE, BTN_LEFT);
|
||||
pen(PEN_IN | PEN_TIP, 12, 10);
|
||||
pen(PEN_IN, 12, 10);
|
||||
pen(0, 12, 10);
|
||||
expect(0, 0);
|
||||
} else if (!strcmp(c, "buttons")) {
|
||||
pen(PEN_IN | PEN_RIGHT, 10, 10);
|
||||
expect(2, R); motion(0, 20, 20); button(1, PRESS, BTN_RIGHT);
|
||||
pen(PEN_IN | PEN_RIGHT | PEN_MIDDLE, 10, 10);
|
||||
expect(2, R | M); button(1, PRESS, BTN_MIDDLE);
|
||||
pen(PEN_IN | PEN_MIDDLE | PEN_TIP, 11, 10);
|
||||
expect(3, L | M); motion(0, 22, 20); button(1, PRESS, BTN_LEFT); button(2, RELEASE, BTN_RIGHT);
|
||||
pen(PEN_IN | PEN_RIGHT, 12, 10);
|
||||
expect(4, R); motion(0, 24, 20); button(1, PRESS, BTN_RIGHT);
|
||||
button(2, RELEASE, BTN_LEFT); button(3, RELEASE, BTN_MIDDLE);
|
||||
pen(PEN_IN, 12, 10);
|
||||
expect(2, 0); button(1, RELEASE, BTN_RIGHT);
|
||||
} else if (!strcmp(c, "out")) {
|
||||
pen(PEN_IN | PEN_TIP | PEN_RIGHT | PEN_MIDDLE, 10, 10);
|
||||
expect(4, L | R | M); motion(0, 20, 20);
|
||||
button(1, PRESS, BTN_LEFT); button(2, PRESS, BTN_RIGHT); button(3, PRESS, BTN_MIDDLE);
|
||||
pen(PEN_TIP | PEN_RIGHT | PEN_MIDDLE, 30, 30);
|
||||
expect(3, 0);
|
||||
button(0, RELEASE, BTN_LEFT); button(1, RELEASE, BTN_RIGHT); button(2, RELEASE, BTN_MIDDLE);
|
||||
assert(!g_pen.in && !g_pen.buttons);
|
||||
pen(0, 30, 30);
|
||||
expect(0, 0);
|
||||
} else if (!strcmp(c, "lock")) {
|
||||
struct constraint lock = {1}, confine = {0};
|
||||
g_active_constraint = &lock;
|
||||
pen(PEN_IN, 10, 10);
|
||||
expect(0, 0);
|
||||
assert(g_pen.in && logs == 1);
|
||||
pen(PEN_IN | PEN_TIP, 11, 10);
|
||||
expect(1, L); button(0, PRESS, BTN_LEFT);
|
||||
pen(PEN_IN | PEN_TIP, 40, 10);
|
||||
expect(0, L);
|
||||
pen(PEN_IN | PEN_RIGHT, 40, 10);
|
||||
expect(2, R); button(0, PRESS, BTN_RIGHT); button(1, RELEASE, BTN_LEFT);
|
||||
pen(0, 40, 10);
|
||||
expect(1, 0); button(0, RELEASE, BTN_RIGHT);
|
||||
g_active_constraint = &confine;
|
||||
pen(PEN_IN, 10, 10);
|
||||
expect(1, 0); motion(0, 20, 20);
|
||||
} else if (!strcmp(c, "lost")) {
|
||||
pen(PEN_IN | PEN_TIP, 10, 10);
|
||||
expect(2, L); motion(0, 20, 20); button(1, PRESS, BTN_LEFT);
|
||||
pen(0, 10, 10);
|
||||
expect(1, 0); button(0, RELEASE, BTN_LEFT);
|
||||
pen(PEN_IN | PEN_TIP | PEN_MIDDLE, 10, 10);
|
||||
expect(3, L | M);
|
||||
pen(PEN_IN, 50, 10);
|
||||
expect(3, 0); motion(0, 100, 20); button(1, RELEASE, BTN_LEFT); button(2, RELEASE, BTN_MIDDLE);
|
||||
} else {
|
||||
assert(!strcmp(c, "raw"));
|
||||
g_raw_valid = 1;
|
||||
pen(PEN_IN, 10, 10);
|
||||
assert(!events[0].raw_valid && g_raw_valid);
|
||||
pen(PEN_IN, 11, 10);
|
||||
assert(events[0].raw_valid);
|
||||
pen(PEN_IN | PEN_TIP, 12, 10);
|
||||
assert(events[0].raw_valid && events[1].raw_valid);
|
||||
pen(0, 12, 10);
|
||||
assert(!g_raw_valid);
|
||||
g_raw_valid = 1;
|
||||
pen(0, 12, 10);
|
||||
assert(g_raw_valid);
|
||||
}
|
||||
puts("PASS");
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
#include <assert.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define BTN_LEFT 0x110
|
||||
#define BTN_RIGHT 0x111
|
||||
#define BTN_MIDDLE 0x112
|
||||
#define INPUT_SPACE_W 1920
|
||||
#define INPUT_SPACE_H 1080
|
||||
#define WL_POINTER_FRAME_SINCE_VERSION 5
|
||||
#define WL_POINTER_BUTTON_STATE_RELEASED 0
|
||||
#define WL_POINTER_BUTTON_STATE_PRESSED 1
|
||||
#include "input_msg.inc"
|
||||
#include "pen_state.inc"
|
||||
|
||||
typedef int32_t wl_fixed_t;
|
||||
struct wl_client { int id; };
|
||||
struct wl_resource { struct wl_client *client; };
|
||||
struct wl_display { int unused; };
|
||||
struct surface { struct wl_resource *resource; int placed, x, y; };
|
||||
struct seat_pointer { struct wl_resource *ptr, *focus; };
|
||||
struct constraint { int is_lock; struct surface *surface; };
|
||||
|
||||
static struct wl_client client_a, client_b;
|
||||
static struct wl_resource surface_a = {&client_a}, surface_b = {&client_b};
|
||||
static struct wl_resource pointer_a = {&client_a}, pointer_b = {&client_b};
|
||||
static struct surface a = {&surface_a, 1, 0, 0}, b = {&surface_b, 1, 1000, 0};
|
||||
static struct seat_pointer g_ptrs[2] = {{&pointer_a, NULL}, {&pointer_b, NULL}};
|
||||
static int g_nptrs = 2;
|
||||
static struct wl_display *g_display;
|
||||
static struct constraint *g_active_constraint;
|
||||
static struct surface *g_desktop, *g_grab, *g_key_target, *g_ime_click;
|
||||
static double g_ptr_x, g_ptr_y, g_raw_x, g_raw_y;
|
||||
static int g_ptr_known, g_raw_valid;
|
||||
static atomic_int g_cursor_composite;
|
||||
|
||||
enum { ENTER, LEAVE, PRESS, RELEASE };
|
||||
struct event { int kind; struct wl_resource *pointer, *surface; uint32_t button; };
|
||||
static struct event events[32];
|
||||
static int nevents;
|
||||
|
||||
static void record(int kind, struct wl_resource *pointer, struct wl_resource *surface, uint32_t button) {
|
||||
assert(nevents < 32);
|
||||
events[nevents++] = (struct event){kind, pointer, surface, button};
|
||||
}
|
||||
|
||||
static void scene_size(int *w, int *h) { *w = 2000; *h = 1000; }
|
||||
static void vkp_output_size(int *w, int *h) { *w = 0; *h = 0; }
|
||||
static int vkp_output_to_scene(double ox, double oy, double *x, double *y) {
|
||||
(void)ox; (void)oy; (void)x; (void)y;
|
||||
return 0;
|
||||
}
|
||||
static struct surface *toplevel_at(double x, double y) {
|
||||
(void)y;
|
||||
return x < 1000 ? &a : &b;
|
||||
}
|
||||
static void confine_clamp(struct constraint *k, double *x, double *y) { (void)k; (void)x; (void)y; }
|
||||
static void schedule_render(void) {}
|
||||
static void publish_query_state(void) {}
|
||||
static void constraints_focus_entered(struct wl_resource *target, struct wl_client *client) {
|
||||
(void)target; (void)client;
|
||||
}
|
||||
static void droiddeck_text_input_refocus(void) {}
|
||||
static void pen_log_target(void) {}
|
||||
static struct surface *dying;
|
||||
static void wl_display_flush_clients(struct wl_display *display) {
|
||||
(void)display;
|
||||
if (!dying || !nevents || events[nevents - 1].kind != RELEASE) return;
|
||||
if (g_grab == dying) g_grab = NULL;
|
||||
if (g_pen.grab == dying) g_pen.grab = NULL;
|
||||
dying = NULL;
|
||||
}
|
||||
static uint32_t now_ms(void) { return 0; }
|
||||
static uint32_t wl_display_next_serial(struct wl_display *display) { (void)display; return 0; }
|
||||
static int wl_resource_get_version(struct wl_resource *r) { (void)r; return 7; }
|
||||
static struct wl_client *wl_resource_get_client(struct wl_resource *r) { return r->client; }
|
||||
static wl_fixed_t wl_fixed_from_double(double d) { return (wl_fixed_t)(d * 256); }
|
||||
static int send_relative_motion(struct wl_client *client, double dx, double dy) {
|
||||
(void)client; (void)dx; (void)dy;
|
||||
return 0;
|
||||
}
|
||||
static void wl_pointer_send_enter(struct wl_resource *p, uint32_t serial, struct wl_resource *s,
|
||||
wl_fixed_t x, wl_fixed_t y) {
|
||||
(void)serial; (void)x; (void)y;
|
||||
record(ENTER, p, s, 0);
|
||||
}
|
||||
static void wl_pointer_send_leave(struct wl_resource *p, uint32_t serial, struct wl_resource *s) {
|
||||
(void)serial;
|
||||
record(LEAVE, p, s, 0);
|
||||
}
|
||||
static void wl_pointer_send_motion(struct wl_resource *p, uint32_t t, wl_fixed_t x, wl_fixed_t y) {
|
||||
(void)p; (void)t; (void)x; (void)y;
|
||||
}
|
||||
static void wl_pointer_send_frame(struct wl_resource *p) { (void)p; }
|
||||
static void wl_pointer_send_button(struct wl_resource *p, uint32_t serial, uint32_t t, uint32_t button,
|
||||
uint32_t state) {
|
||||
(void)serial; (void)t;
|
||||
record(state == WL_POINTER_BUTTON_STATE_PRESSED ? PRESS : RELEASE, p, NULL, button);
|
||||
}
|
||||
#include "pointer.inc"
|
||||
#include "pen.inc"
|
||||
|
||||
static void pen(int flags, double x) {
|
||||
struct input_msg m = {13, flags, (int)(x * INPUT_SPACE_W / 2000 * 256), 100 * 256, 0};
|
||||
nevents = 0;
|
||||
deliver_pen(&m);
|
||||
}
|
||||
|
||||
static void focus(int i, struct wl_resource *pointer, struct wl_resource *surface) {
|
||||
assert(i < nevents && events[i].kind == ENTER && events[i].pointer == pointer && events[i].surface == surface);
|
||||
}
|
||||
|
||||
static void left(int i, struct wl_resource *pointer, struct wl_resource *surface) {
|
||||
assert(i < nevents && events[i].kind == LEAVE && events[i].pointer == pointer && events[i].surface == surface);
|
||||
}
|
||||
|
||||
static void button(int i, int kind, uint32_t code) {
|
||||
assert(i < nevents && events[i].kind == kind && events[i].pointer == &pointer_a && events[i].button == code);
|
||||
}
|
||||
|
||||
static void hover_away(void) {
|
||||
assert(!g_grab);
|
||||
pen(PEN_IN, 1500);
|
||||
assert(nevents == 2);
|
||||
left(0, &pointer_a, &surface_a); focus(1, &pointer_b, &surface_b);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
assert(argc == 2);
|
||||
const char *c = argv[1];
|
||||
pen(PEN_IN, 500);
|
||||
assert(nevents == 1);
|
||||
focus(0, &pointer_a, &surface_a);
|
||||
pen(PEN_IN | PEN_TIP, 500);
|
||||
assert(nevents == 1 && g_grab == &a);
|
||||
button(0, PRESS, BTN_LEFT);
|
||||
if (!strcmp(c, "side")) {
|
||||
pen(PEN_IN | PEN_TIP | PEN_RIGHT, 600);
|
||||
assert(nevents == 1 && g_grab == &a);
|
||||
button(0, PRESS, BTN_RIGHT);
|
||||
pen(PEN_IN | PEN_TIP, 700);
|
||||
assert(nevents == 1 && g_grab == &a);
|
||||
button(0, RELEASE, BTN_RIGHT);
|
||||
pen(PEN_IN | PEN_TIP, 1500);
|
||||
assert(nevents == 0 && g_grab == &a);
|
||||
pen(PEN_IN, 1500);
|
||||
assert(nevents == 1);
|
||||
button(0, RELEASE, BTN_LEFT);
|
||||
} else if (!strcmp(c, "swap")) {
|
||||
pen(PEN_IN | PEN_RIGHT, 600);
|
||||
assert(nevents == 2 && g_grab == &a);
|
||||
button(0, PRESS, BTN_RIGHT); button(1, RELEASE, BTN_LEFT);
|
||||
pen(PEN_IN | PEN_RIGHT, 1500);
|
||||
assert(nevents == 0 && g_grab == &a);
|
||||
pen(PEN_IN, 1500);
|
||||
assert(nevents == 1);
|
||||
button(0, RELEASE, BTN_RIGHT);
|
||||
} else if (!strcmp(c, "mouse")) {
|
||||
pointer_button(BTN_RIGHT, 1);
|
||||
pointer_button(BTN_RIGHT, 0);
|
||||
pen(PEN_IN | PEN_TIP, 1500);
|
||||
assert(nevents == 0 && g_grab == &a);
|
||||
pen(PEN_IN, 1500);
|
||||
assert(nevents == 1);
|
||||
button(0, RELEASE, BTN_LEFT);
|
||||
} else {
|
||||
assert(!strcmp(c, "gone"));
|
||||
pen(PEN_IN | PEN_TIP | PEN_RIGHT, 600);
|
||||
assert(nevents == 1 && g_grab == &a);
|
||||
dying = &a;
|
||||
pen(PEN_IN | PEN_TIP, 700);
|
||||
assert(nevents == 1 && !dying && !g_grab && !g_pen.grab);
|
||||
button(0, RELEASE, BTN_RIGHT);
|
||||
pen(PEN_IN, 700);
|
||||
assert(nevents == 1);
|
||||
button(0, RELEASE, BTN_LEFT);
|
||||
}
|
||||
hover_away();
|
||||
puts("PASS");
|
||||
}
|
||||
@@ -47,6 +47,47 @@ class LogTest(Temp):
|
||||
self.assertRegex(log.read_text(), r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d \[\d+\] second\n$")
|
||||
|
||||
|
||||
class StoreDebugEnvironmentTest(Temp):
|
||||
def config(self, enabled):
|
||||
config = self.tmp / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True, exist_ok=True)
|
||||
config.write_text(json.dumps({"version": 1, "gameDebugLogs": enabled}))
|
||||
|
||||
def env(self, values=None):
|
||||
debug_dir = self.tmp / "session"
|
||||
debug_dir.mkdir(exist_ok=True)
|
||||
base = {"HOME": str(self.tmp), "BL_DEBUG_DIR": str(debug_dir)}
|
||||
base.update(values or {})
|
||||
return base
|
||||
|
||||
def test_store_proton_command_gets_debug_defaults_when_enabled(self):
|
||||
self.config(True)
|
||||
with mock.patch.dict(os.environ, self.env(), clear=True):
|
||||
result = BNET["proton_env"]()
|
||||
self.assertEqual(result["PROTON_LOG"], "1")
|
||||
self.assertEqual(result["DXVK_LOG_LEVEL"], "debug")
|
||||
self.assertEqual(result["PROTON_LOG_DIR"], str(self.tmp / "session"))
|
||||
self.assertIn("+seh", result["WINEDEBUG"])
|
||||
|
||||
def test_store_proton_command_keeps_debug_off_when_disabled(self):
|
||||
self.config(False)
|
||||
with mock.patch.dict(os.environ, self.env(), clear=True):
|
||||
result = BNET["proton_env"]()
|
||||
self.assertNotIn("PROTON_LOG", result)
|
||||
self.assertNotIn("DXVK_LOG_LEVEL", result)
|
||||
|
||||
def test_store_proton_command_keeps_user_debug_values(self):
|
||||
self.config(True)
|
||||
values = {"PROTON_LOG": "0", "DXVK_LOG_LEVEL": "none", "WINEDEBUG": "-all", "PROTON_LOG_DIR": "/custom"}
|
||||
with mock.patch.dict(os.environ, self.env(values), clear=True):
|
||||
result = BNET["proton_env"]()
|
||||
self.assertEqual(result["PROTON_LOG"], "1")
|
||||
self.assertEqual(result["DXVK_LOG_LEVEL"], "debug")
|
||||
self.assertEqual(result["PROTON_LOG_DIR"], str(self.tmp / "session"))
|
||||
self.assertIn("+seh", result["WINEDEBUG"])
|
||||
self.assertIn("-all", result["WINEDEBUG"])
|
||||
|
||||
|
||||
class IdTest(unittest.TestCase):
|
||||
def test_the_prefix_id_is_the_shortcut_id_the_app_names(self):
|
||||
self.assertEqual(int(BNET["APP_ID"]), zlib.crc32(b'"droiddeck-battlenet"Battle.net') | 0x80000000)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
class DirectAudioWatchdogTest(unittest.TestCase):
|
||||
def test_recovery_threshold_callback_race_and_forced_exit(self):
|
||||
source = pathlib.Path('tools/directaudio/sink/module-directaudio-native-sink.c').read_text()
|
||||
watchdog = source[source.index('static void watchdog('):source.index('static void close_output(')]
|
||||
callback = source[source.index('static void record_callback('):
|
||||
source.index('static aaudio_data_callback_result_t out_cb(')]
|
||||
constants = '\n'.join(line for line in source.splitlines()
|
||||
if line.startswith(('#define DA_FREEZE_GAP_NS ', '#define DA_CB_STALL_NS ',
|
||||
'#define DA_HOST_RESTART_STALLS ')))
|
||||
harness = r'''
|
||||
#include <assert.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
typedef void AAudioStream;
|
||||
struct userdata {
|
||||
bool watchdog_on;
|
||||
AAudioStream *aq;
|
||||
uint64_t wd_last_tick_ns, last_cb_ns;
|
||||
unsigned int cb_count, wd_last_cb;
|
||||
uint64_t stall_state;
|
||||
};
|
||||
static uint64_t clock_ns = 10000000000ull;
|
||||
static unsigned int reopens;
|
||||
static bool callback_race;
|
||||
static struct userdata *current;
|
||||
static uint64_t now_ns(void) { return clock_ns; }
|
||||
static void request_reopen(struct userdata *u, const char *why) { reopens++; }
|
||||
#define pa_log(...) ((void)0)
|
||||
CALLBACK
|
||||
static bool exchange(uint64_t *value, uint64_t *expected, uint64_t next,
|
||||
int weak, int success, int failure) {
|
||||
if (callback_race) {
|
||||
struct userdata *u = current;
|
||||
record_callback(u);
|
||||
__atomic_add_fetch(&u->cb_count, 1, __ATOMIC_SEQ_CST);
|
||||
}
|
||||
return __atomic_compare_exchange_n(value, expected, next, weak, success, failure);
|
||||
}
|
||||
#define __atomic_compare_exchange_n exchange
|
||||
WATCHDOG
|
||||
static void cleanup(void) { _exit(99); }
|
||||
static void tick(struct userdata *u) {
|
||||
clock_ns += 1000000000ull;
|
||||
watchdog(u);
|
||||
}
|
||||
int main(int argc, char **argv) {
|
||||
struct userdata state = {.watchdog_on = true, .aq = (void *)1};
|
||||
struct userdata *u = &state;
|
||||
current = u;
|
||||
watchdog(u);
|
||||
if (argc > 1 && strcmp(argv[1], "zero") == 0) {
|
||||
callback_race = true;
|
||||
tick(u);
|
||||
assert(reopens == 0 && (uint32_t) u->stall_state == 0);
|
||||
return 0;
|
||||
}
|
||||
tick(u);
|
||||
assert(reopens == 1 && (uint32_t) u->stall_state == 1);
|
||||
tick(u);
|
||||
assert(reopens == 2 && (uint32_t) u->stall_state == 2);
|
||||
if (argc > 1 && strcmp(argv[1], "exit") == 0) {
|
||||
atexit(cleanup);
|
||||
tick(u);
|
||||
return 42;
|
||||
}
|
||||
callback_race = true;
|
||||
tick(u);
|
||||
assert(reopens == 2 && (uint32_t) u->stall_state == 0);
|
||||
callback_race = false;
|
||||
tick(u);
|
||||
assert(reopens == 2 && (uint32_t) u->stall_state == 0);
|
||||
tick(u);
|
||||
assert(reopens == 3 && (uint32_t) u->stall_state == 1);
|
||||
u->watchdog_on = false;
|
||||
tick(u);
|
||||
assert(reopens == 3 && (uint32_t) u->stall_state == 1);
|
||||
return 0;
|
||||
}
|
||||
'''.replace('CALLBACK', callback).replace('WATCHDOG', watchdog)
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = pathlib.Path(folder)
|
||||
(path / 'watchdog.c').write_text(constants + '\n' + harness)
|
||||
subprocess.run(['cc', '-std=c11', '-Werror', str(path / 'watchdog.c'),
|
||||
'-o', str(path / 'watchdog')], check=True, capture_output=True)
|
||||
subprocess.run([str(path / 'watchdog')], check=True, timeout=5)
|
||||
subprocess.run([str(path / 'watchdog'), 'zero'], check=True, timeout=5)
|
||||
result = subprocess.run([str(path / 'watchdog'), 'exit'], timeout=5)
|
||||
self.assertEqual(1, result.returncode)
|
||||
@@ -887,17 +887,28 @@ class BrokerTest(EpicTestCase):
|
||||
folder.mkdir()
|
||||
(folder / ".droiddeck-store.json").write_text(json.dumps({"store": "epic", "id": "Fig", "args": ["-x"]}))
|
||||
(folder / ".droiddeck-launch.bat").write_text('if exist "%~dp0.droiddeck-epic-args" goto client\r\n')
|
||||
debug_dir = self.tmp / "session"
|
||||
debug_dir.mkdir()
|
||||
config = self.home / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
config.write_text(json.dumps({"version": 1, "gameDebugLogs": True}))
|
||||
calls = []
|
||||
|
||||
def popen(command, env=None, cwd=None, start_new_session=False):
|
||||
calls.append((command, env.get("DROIDDECK_EPIC_HANDLED"), start_new_session))
|
||||
calls.append((command, env.get("DROIDDECK_EPIC_HANDLED"), env.get("BL_DEBUG_DIR"),
|
||||
env.get("PROTON_LOG"), env.get("WINEDEBUG"), start_new_session))
|
||||
return mock.Mock(wait=mock.Mock(return_value=7))
|
||||
|
||||
running = []
|
||||
with mock.patch.object(subprocess, "Popen", popen):
|
||||
code = G["run_game"]({"exe": str(folder / "Fig.exe"), "args": ["-epicapp=Fig"]}, {"PATH": "/usr/bin"}, running)
|
||||
with mock.patch.dict(os.environ, {"HOME": str(self.home), "BL_DEBUG_DIR": str(debug_dir),
|
||||
"PROTON_LOG": "0", "WINEDEBUG": "-all"}), \
|
||||
mock.patch.object(subprocess, "Popen", popen):
|
||||
code = G["run_game"]({"exe": str(folder / "Fig.exe"), "args": ["-epicapp=Fig"]},
|
||||
{"PATH": "/usr/bin", "BL_DEBUG_DIR": str(debug_dir)}, running)
|
||||
self.assertEqual(7, code)
|
||||
self.assertEqual(([G["PROTON_RUN"], str(folder / ".droiddeck-launch.bat")], "1", True), calls[0])
|
||||
self.assertEqual(([G["PROTON_RUN"], str(folder / ".droiddeck-launch.bat")], "1", str(debug_dir), "1",
|
||||
mock.ANY, True), calls[0])
|
||||
self.assertIn("+seh", calls[0][4])
|
||||
self.assertEqual([], running)
|
||||
self.assertEqual(b"-epicapp=Fig -x\r\n", (folder / ".droiddeck-epic-args").read_bytes())
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import json
|
||||
import os
|
||||
import runpy
|
||||
import shutil
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -473,7 +474,6 @@ class PrepareTest(FexTestCase):
|
||||
for name in names:
|
||||
library = root / "lib" / arch / name
|
||||
expected = sniper if name == "libwayland-cursor.so.0" else provider
|
||||
self.assertEqual(library.resolve(), (expected / "files/lib" / arch / name).resolve())
|
||||
self.assertEqual(library.read_bytes(), b"old ABI" if expected == sniper else b"new ABI " + name.encode())
|
||||
self.assertEqual((root / "lib" / arch / "libffi.so.7").read_bytes(), b"old ffi")
|
||||
self.assertEqual((sniper / "files/lib/x86_64-linux-gnu/libwayland-client.so.0").read_bytes(), b"old ABI")
|
||||
@@ -591,8 +591,7 @@ class PrepareTest(FexTestCase):
|
||||
fex, _ = self.quiet(FEX["prepare"])
|
||||
for arch in ("x86_64-linux-gnu", "i386-linux-gnu"):
|
||||
for name in names:
|
||||
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).resolve(),
|
||||
provider / "files/lib" / arch / name)
|
||||
self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new")
|
||||
self.assertEqual((sniper / "files/lib" / arch / name).read_bytes(), b"base")
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc"), "C compiler unavailable")
|
||||
@@ -644,7 +643,7 @@ class PrepareTest(FexTestCase):
|
||||
self.graphics(sniper)
|
||||
base = self.write(sniper / "files/lib/x86_64-linux-gnu/libwayland-client.so.0", b"base wayland")
|
||||
fex, _ = self.quiet(FEX["prepare"])
|
||||
self.assertEqual((Path(fex["rootfs"]) / "lib/x86_64-linux-gnu/libwayland-client.so.0").resolve(), base)
|
||||
self.assertEqual((Path(fex["rootfs"]) / "lib/x86_64-linux-gnu/libwayland-client.so.0").read_bytes(), b"base wayland")
|
||||
|
||||
def test_provider_symlinks_require_existing_targets_on_both_architectures(self):
|
||||
self.fex_tool()
|
||||
@@ -778,6 +777,72 @@ class PrepareTest(FexTestCase):
|
||||
self.assertIn("built the x86 runtime", said)
|
||||
self.assertNotIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
|
||||
|
||||
def test_the_built_x86_runtime_holds_nothing_that_leaves_it(self):
|
||||
self.fex_tool()
|
||||
sniper = self.runtime()
|
||||
FEX["materialize"](str(sniper))
|
||||
self.graphics(sniper)
|
||||
os.chmod(sniper / "files/share/ca", 0o750)
|
||||
self.quiet(FEX["prepare"])
|
||||
root = (self.home / ".local/share/droiddeck-fex/rootfs").resolve()
|
||||
self.assertEqual(stat.S_IMODE(os.stat(root / "share/ca").st_mode), 0o750)
|
||||
entries = 0
|
||||
for directory, dirs, files in os.walk(root):
|
||||
for name in dirs + files:
|
||||
path = Path(directory) / name
|
||||
entries += 1
|
||||
if path.is_symlink():
|
||||
self.assertFalse(os.path.isabs(os.readlink(path)), path)
|
||||
self.assertTrue(path.resolve().is_relative_to(root), path)
|
||||
self.assertGreater(entries, 10)
|
||||
self.assertEqual((root / "bin/[").read_bytes(), b"blob")
|
||||
self.assertEqual((root / "share/ca/real.crt").read_bytes(), b"cert")
|
||||
self.assertFalse(os.path.lexists(root / "ab"))
|
||||
|
||||
def test_guest_writes_do_not_mutate_runtime_blob_files(self):
|
||||
self.fex_tool()
|
||||
sniper = self.runtime()
|
||||
FEX["materialize"](str(sniper))
|
||||
self.graphics(sniper)
|
||||
self.quiet(FEX["prepare"])
|
||||
root = self.home / ".local/share/droiddeck-fex/rootfs"
|
||||
marker = root / ".droiddeck-fex"
|
||||
stamp = marker.read_text()
|
||||
marker.write_text("3\n" + stamp.partition("\n")[2])
|
||||
source = sniper / "files/ab/cdef-1.bin"
|
||||
guest = root / "bin/["
|
||||
guest.unlink()
|
||||
os.link(source, guest)
|
||||
self.assertEqual(os.stat(source).st_ino, os.stat(guest).st_ino)
|
||||
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
|
||||
self.assertNotEqual(os.stat(source).st_ino, os.stat(guest).st_ino)
|
||||
guest.write_bytes(b"guest mutation")
|
||||
self.assertEqual(source.read_bytes(), b"blob")
|
||||
self.assertEqual(guest.read_bytes(), b"guest mutation")
|
||||
|
||||
def test_a_rebuilt_x86_runtime_refreshes_the_steam_client_links_and_drops_read_only_trees(self):
|
||||
self.fex_tool()
|
||||
sniper = self.runtime()
|
||||
FEX["materialize"](str(sniper))
|
||||
self.graphics(sniper)
|
||||
base = sniper / "files"
|
||||
(base / str(self.home).lstrip("/") / ".steam").mkdir(parents=True)
|
||||
os.symlink(self.steam / "linuxarm64", base / str(self.home).lstrip("/") / ".steam/sdk64")
|
||||
self.write(self.steam / "linuxarm64/steamclient.so", elf(183))
|
||||
os.chmod(base / "share/ca", 0o500)
|
||||
self.addCleanup(os.chmod, base / "share/ca", 0o700)
|
||||
self.quiet(FEX["prepare"])
|
||||
rootfs = self.home / ".local/share/droiddeck-fex/rootfs"
|
||||
os.chmod(rootfs / "share/ca", 0o000)
|
||||
self.write(self.steam / "linux64/steamclient.so", elf(62))
|
||||
self.write(self.steam / "linux32/steamclient.so", elf(3))
|
||||
os.utime(self.steam / "steamapps/common/SteamLinuxRuntime_4/steamrt4_platform_4.0.20260928.262390/usr-mtree.txt.gz", ns=(1, 1))
|
||||
self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1])
|
||||
guest = rootfs / str(self.home).lstrip("/") / ".steam"
|
||||
self.assertEqual(os.readlink(guest / "sdk64"), str(self.steam / "linux64"))
|
||||
self.assertEqual(os.readlink(guest / "sdk32"), str(self.steam / "linux32"))
|
||||
self.assertEqual(sorted(os.listdir(rootfs.parent)), ["config", "lock", "rootfs", "status.json"])
|
||||
|
||||
def test_a_runtime_that_is_not_newer_is_left_out(self):
|
||||
self.fex_tool()
|
||||
sniper = self.runtime()
|
||||
|
||||
@@ -55,6 +55,19 @@ FAKE_ADB = textwrap.dedent('''\
|
||||
print("Result: Bundle[{json=" + json.dumps(answers) + "}]")
|
||||
elif args[:3] == ["shell", "dumpsys", "display"]:
|
||||
print(config.get("dumpsys_display", ""))
|
||||
elif args[:3] == ["shell", "dumpsys", "input"]:
|
||||
print(config.get("dumpsys_input", ""))
|
||||
elif args[:3] == ["shell", "uinput", "-"]:
|
||||
entry["stdin"] = sys.stdin.read()
|
||||
if "uinput_stdout" in config:
|
||||
print(config["uinput_stdout"])
|
||||
else:
|
||||
for line in entry["stdin"].splitlines():
|
||||
command = json.loads(line)
|
||||
if command["command"] == "sync":
|
||||
print(json.dumps({"reason": "sync", "id": command["id"], "syncToken": command["syncToken"]}))
|
||||
elif args[:1] == ["shell"] and len(args) == 2 and "command -v uinput" in args[1]:
|
||||
print(config.get("uinput_probe", ""))
|
||||
elif args[:3] == ["shell", "dumpsys", "power"]:
|
||||
print(" mWakefulness=Awake")
|
||||
elif args[:3] == ["shell", "dumpsys", "SurfaceFlinger"] and "-dump" in args:
|
||||
@@ -332,6 +345,21 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
|
||||
self.assertEqual(["exec-out", "screencap", "-p", "-d", "222"], shot["args"])
|
||||
|
||||
def test_screenshot_with_two_screens_takes_the_main_display(self):
|
||||
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
|
||||
code, out = self.run_ctl("screenshot", str(self.dir / "shot.png"))
|
||||
self.assertEqual(0, code)
|
||||
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
|
||||
self.assertEqual(["exec-out", "screencap", "-p", "-d", "111"], shot["args"])
|
||||
|
||||
def test_screenshot_with_one_screen_names_no_display(self):
|
||||
one = DUMPSYS_DISPLAY.split(" Display 4:")[0]
|
||||
self.configure({}, dumpsys_display=one)
|
||||
code, out = self.run_ctl("screenshot", str(self.dir / "shot.png"))
|
||||
self.assertEqual(0, code)
|
||||
shot = [c for c in self.calls() if c["args"][:2] == ["exec-out", "screencap"]][0]
|
||||
self.assertEqual(["exec-out", "screencap", "-p"], shot["args"])
|
||||
|
||||
def test_displays(self):
|
||||
self.configure({}, dumpsys_display=DUMPSYS_DISPLAY)
|
||||
code, out = self.run_ctl("displays")
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
import json
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
from test_droiddeckctl import FakeAdbTest, ctl
|
||||
|
||||
|
||||
def samples(*argv):
|
||||
return ctl.pen_samples(ctl.build_parser().parse_args(["input", "pen", *argv]))
|
||||
|
||||
|
||||
def phases(gesture):
|
||||
return [s["phase"] for s in gesture]
|
||||
|
||||
|
||||
def dumpsys_input(rotation=0, size=(1140, 2616), active=1, frame=None):
|
||||
other = ("Viewport INTERNAL: displayId=2, uniqueId=local:147, port=147, orientation=0, "
|
||||
"logicalFrame=[0, 0, 2248, 2480], physicalFrame=[0, 0, 2248, 2480], deviceSize=[2248, 2480], isActive=[0]")
|
||||
shown = (f"Viewport INTERNAL: displayId=0, uniqueId=local:148, port=148, orientation={rotation}, "
|
||||
f"logicalFrame=[0, 0, {size[0]}, {size[1]}], physicalFrame=[{', '.join(map(str, frame or (0, 0, *size)))}], "
|
||||
f"deviceSize=[{size[0]}, {size[1]}], isActive=[{active}]")
|
||||
reader = (f"Input Reader State (Nums of device: 11):\n Device 6: touchpanel_pen\n {other}\n"
|
||||
f" Configuration:\n Viewports:\n {other}\n {shown}\n OplusInputReader mMergeEnable = 0\n")
|
||||
return reader + "\nINPUT MANAGER (dumpsys input)\n\n" + reader
|
||||
|
||||
|
||||
def frames(commands):
|
||||
found, frame = [], {}
|
||||
for command in commands:
|
||||
if command["command"] == "inject":
|
||||
events = command["events"]
|
||||
for code, value in zip(events[1::3], events[2::3]):
|
||||
if code == "SYN_REPORT":
|
||||
found.append(frame)
|
||||
frame = {}
|
||||
else:
|
||||
frame[code] = value
|
||||
return found
|
||||
|
||||
|
||||
class PenSamplesTest(unittest.TestCase):
|
||||
def test_a_tap_hovers_lands_lifts_and_leaves(self):
|
||||
gesture = samples("tap", "0.5", "0.5", "--hold", "20")
|
||||
self.assertEqual(["hover"] * 10 + ["down", "move", "up"] + ["hover"] * 10 + ["out"], phases(gesture))
|
||||
times = [s["t"] for s in gesture]
|
||||
self.assertEqual(sorted(times), times)
|
||||
self.assertEqual([0, 8, 80, 100, 180, 180], [times[0], times[1], times[10], times[12], times[-2], times[-1]])
|
||||
self.assertEqual({0.5}, {s["pressure"] for s in gesture[10:13]})
|
||||
self.assertEqual({0}, {s["pressure"] for s in gesture[:10] + gesture[13:]})
|
||||
self.assertEqual({(0.5, 0.5, None)}, {(s["x"], s["y"], s["button"]) for s in gesture})
|
||||
|
||||
def test_without_hover_the_pen_lands_and_leaves_at_once(self):
|
||||
gesture = samples("tap", "0.5", "0.5", "--hover-ms", "0", "--hold", "0")
|
||||
self.assertEqual([("down", 0), ("up", 0), ("out", 0)], [(s["phase"], s["t"]) for s in gesture])
|
||||
|
||||
def test_a_stroke_ramps_pressure_and_tilt(self):
|
||||
gesture = samples("stroke", "0.25", "0.5", "0.75", "1", "--duration", "100", "--hover-ms", "20", "--rate", "100",
|
||||
"--pressure", "0.25:0.75", "--tilt-x=-30:30", "--tilt-y", "10")
|
||||
self.assertEqual(["hover", "hover", "down"] + ["move"] * 9 + ["up", "hover", "hover", "out"], phases(gesture))
|
||||
contact = gesture[2:13]
|
||||
self.assertEqual([(20, 0.25, 0.5, 0.25), (70, 0.5, 0.75, 0.5), (120, 0.75, 1, 0.75)],
|
||||
[(s["t"], s["x"], s["y"], s["pressure"]) for s in (contact[0], contact[5], contact[-1])])
|
||||
self.assertEqual((-30, 30), (gesture[0]["tilt_x"], gesture[-1]["tilt_x"]))
|
||||
self.assertAlmostEqual(-30 + 60 * 20 / 140, contact[0]["tilt_x"])
|
||||
self.assertEqual({10}, {s["tilt_y"] for s in gesture})
|
||||
|
||||
def test_hover_glides_to_the_target(self):
|
||||
gesture = samples("hover", "0.25", "0.25", "--to", "0.75", "0.5", "--duration", "300", "--distance", "5")
|
||||
self.assertEqual(["hover"] * 37 + ["out"], phases(gesture))
|
||||
self.assertEqual([(0.25, 0.25), (0.75, 0.5), (0.75, 0.5)],
|
||||
[(s["x"], s["y"]) for s in (gesture[0], gesture[-2], gesture[-1])])
|
||||
self.assertEqual((300, {5}), (gesture[-1]["t"], {s["distance"] for s in gesture}))
|
||||
|
||||
def test_a_side_button_is_held_while_hovering(self):
|
||||
gesture = samples("button", "secondary", "0.5", "0.5", "--hold", "40")
|
||||
self.assertEqual([80, 88, 96, 104, 112], [s["t"] for s in gesture if s["button"] == "secondary"])
|
||||
self.assertEqual(["hover"] * (len(gesture) - 1) + ["out"], phases(gesture))
|
||||
self.assertEqual((200, None), (gesture[-1]["t"], gesture[-2]["button"]))
|
||||
|
||||
|
||||
class PenUinputTest(FakeAdbTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.configure({}, dumpsys_input=dumpsys_input())
|
||||
|
||||
def pen(self, *argv):
|
||||
return self.run_ctl("input", "pen", *argv)
|
||||
|
||||
def script(self):
|
||||
[call] = [c for c in self.calls() if c["args"][:3] == ["shell", "uinput", "-"]]
|
||||
return [json.loads(line) for line in call["stdin"].splitlines()]
|
||||
|
||||
def test_a_stroke_draws_with_a_virtual_direct_pen(self):
|
||||
code, out = self.pen("stroke", "0.25", "0.5", "0.75", "0.5", "--duration", "100", "--rate", "100",
|
||||
"--hover-ms", "20", "--pressure", "0.2:1")
|
||||
self.assertEqual(0, code)
|
||||
self.assertEqual({"ok": True, "command": "input", "type": "pen", "samples": 16, "deviceSerial": "fake-1",
|
||||
"viewport": {"display": 0, "rotation": 0, "size": [1140, 2616]}},
|
||||
{k: v for k, v in out.items() if k != "ms"})
|
||||
self.assertFalse(self.calls("input"))
|
||||
commands = self.script()
|
||||
register = commands[0]
|
||||
bits = {c["type"]: c["data"] for c in register["configuration"]}
|
||||
self.assertEqual(("register", "virtual", ["EV_KEY", "EV_ABS"], ["INPUT_PROP_DIRECT"]),
|
||||
(register["command"], register["bus"], bits["UI_SET_EVBIT"], bits["UI_SET_PROPBIT"]))
|
||||
self.assertEqual({"BTN_TOOL_PEN", "BTN_TOOL_RUBBER", "BTN_TOUCH", "BTN_STYLUS", "BTN_STYLUS2"},
|
||||
set(bits["UI_SET_KEYBIT"]))
|
||||
ranges = {a["code"]: (a["info"]["minimum"], a["info"]["maximum"]) for a in register["abs_info"]}
|
||||
self.assertEqual({"ABS_X": (0, 1140 * 16 - 1), "ABS_Y": (0, 2616 * 16 - 1), "ABS_PRESSURE": (0, 4095),
|
||||
"ABS_DISTANCE": (0, 255), "ABS_TILT_X": (-90, 90), "ABS_TILT_Y": (-90, 90)}, ranges)
|
||||
self.assertEqual(set(bits["UI_SET_ABSBIT"]), set(ranges))
|
||||
self.assertEqual({"id": 1, "command": "delay", "duration": 1000}, commands[1])
|
||||
self.assertNotIn("updateTimeBase", [c["command"] for c in commands])
|
||||
self.assertEqual(140, sum(c["duration"] for c in commands[2:-2] if c["command"] == "delay"))
|
||||
self.assertEqual([{"id": 1, "command": "delay", "duration": 300},
|
||||
{"id": 1, "command": "sync", "syncToken": ctl.UINPUT_SYNC}], commands[-2:])
|
||||
drawn = frames(commands)
|
||||
self.assertEqual({"BTN_TOOL_PEN": 1, "ABS_X": 4560, "ABS_Y": 20928, "ABS_PRESSURE": 0, "ABS_DISTANCE": 0,
|
||||
"ABS_TILT_X": 0, "ABS_TILT_Y": 0}, drawn[0])
|
||||
self.assertEqual([{"ABS_X": 4561}, {"BTN_TOUCH": 1, "ABS_X": 4560, "ABS_PRESSURE": 819}], drawn[1:3])
|
||||
self.assertEqual([{"ABS_X": 13680, "ABS_PRESSURE": 4095}, {"BTN_TOUCH": 0, "ABS_PRESSURE": 0}, {"ABS_X": 13681},
|
||||
{"ABS_X": 13680}, {"BTN_TOOL_PEN": 0}], drawn[-5:])
|
||||
pressures = [f["ABS_PRESSURE"] for f in drawn[2:-4]]
|
||||
self.assertEqual(sorted(pressures), pressures)
|
||||
|
||||
def test_positions_and_tilt_follow_the_rotation(self):
|
||||
cases = {0: ([1000, 2000], 4000, 24000, 30, -10), 1: ([2000, 1000], 3999, 8000, 10, 30),
|
||||
2: ([1000, 2000], 11999, 7999, -30, 10), 3: ([2000, 1000], 12000, 23999, -10, -30)}
|
||||
for rotation, (size, x, y, tilt_x, tilt_y) in cases.items():
|
||||
with self.subTest(rotation=rotation):
|
||||
self.configure({}, dumpsys_input=dumpsys_input(rotation, size))
|
||||
self.log.unlink(missing_ok=True)
|
||||
code, out = self.pen("tap", "0.25", "0.75", "--tilt-x", "30", "--tilt-y=-10")
|
||||
self.assertEqual((0, rotation), (code, out["viewport"]["rotation"]))
|
||||
commands = self.script()
|
||||
self.assertEqual([15999, 31999], [a["info"]["maximum"] for a in commands[0]["abs_info"][:2]])
|
||||
first = frames(commands)[0]
|
||||
self.assertEqual((x, y, tilt_x, tilt_y),
|
||||
tuple(first[key] for key in ("ABS_X", "ABS_Y", "ABS_TILT_X", "ABS_TILT_Y")))
|
||||
|
||||
def test_the_mapping_inverts_aosps_input_coordinates_example(self):
|
||||
self.assertEqual((0, 2, 0, 0), ctl.uinput_point(2 / 4, 2 / 3, 0, 0, 1, 3, 4, [0, 0, 4, 3]))
|
||||
self.assertEqual((2, 3, 0, 0), ctl.uinput_point(1, 1, 0, 0, 0, 3, 4, [0, 0, 3, 4]))
|
||||
self.assertEqual((0, 0, 0, 0), ctl.uinput_point(1, 1, 0, 0, 2, 3, 4, [0, 0, 3, 4]))
|
||||
|
||||
def test_positions_map_onto_the_physical_frame(self):
|
||||
cases = {0: ((1000, 2000), (100, 250, 900, 1750), ("1", "0.05"), (14399, 5200)),
|
||||
1: ((2000, 1000), (250, 100, 1750, 900), ("0.05", "1"), (1600, 5200))}
|
||||
for rotation, (size, frame, position, first) in cases.items():
|
||||
with self.subTest(rotation=rotation):
|
||||
self.configure({}, dumpsys_input=dumpsys_input(rotation, size, frame=frame))
|
||||
self.log.unlink(missing_ok=True)
|
||||
self.assertEqual(0, self.pen("tap", *position)[0])
|
||||
drawn = frames(self.script())
|
||||
self.assertEqual(first, (drawn[0]["ABS_X"], drawn[0]["ABS_Y"]))
|
||||
self.assertTrue(all(1600 <= f.get("ABS_X", 1600) < 14400 for f in drawn))
|
||||
|
||||
def test_eraser_and_buttons_use_the_stylus_keys(self):
|
||||
for button, side in (("primary", "BTN_STYLUS"), ("secondary", "BTN_STYLUS2")):
|
||||
with self.subTest(button=button):
|
||||
self.log.unlink(missing_ok=True)
|
||||
code, _ = self.pen("button", button, "0.5", "0.5", "--hold", "40", "--tool", "eraser", "--distance", "12")
|
||||
self.assertEqual(0, code)
|
||||
drawn = frames(self.script())
|
||||
keys = [(key, value) for frame in drawn for key, value in frame.items() if key.startswith("BTN_")]
|
||||
self.assertEqual([("BTN_TOOL_RUBBER", 1), (side, 1), (side, 0), ("BTN_TOOL_RUBBER", 0)], keys)
|
||||
self.assertEqual(12, drawn[0]["ABS_DISTANCE"])
|
||||
|
||||
def test_a_still_pen_keeps_reporting_at_the_rate(self):
|
||||
code, out = self.pen("hover", "1", "0.5", "--duration", "100", "--rate", "50")
|
||||
self.assertEqual(0, code)
|
||||
commands = self.script()
|
||||
drawn = frames(commands)
|
||||
self.assertEqual(out["samples"], len(drawn))
|
||||
self.assertEqual([18239, 18238, 18239, 18238, 18239, 18238], [f["ABS_X"] for f in drawn[:-1]])
|
||||
self.assertEqual([20, 20, 20, 20, 20, 300], [c["duration"] for c in commands[2:] if c["command"] == "delay"])
|
||||
|
||||
def test_a_contact_without_pressure_still_touches(self):
|
||||
code, _ = self.pen("tap", "0.5", "0.5", "--pressure", "0", "--hover-ms", "0", "--hold", "0", "--distance", "5")
|
||||
self.assertEqual(0, code)
|
||||
drawn = frames(self.script())
|
||||
self.assertEqual((1, 1, 1, 0),
|
||||
tuple(drawn[0][key] for key in ("BTN_TOOL_PEN", "BTN_TOUCH", "ABS_PRESSURE", "ABS_DISTANCE")))
|
||||
self.assertEqual([{"BTN_TOUCH": 0, "ABS_PRESSURE": 0, "ABS_DISTANCE": 5}, {"BTN_TOOL_PEN": 0}], drawn[1:])
|
||||
|
||||
def test_bad_values_are_refused(self):
|
||||
cases = [
|
||||
(("tap", "1.5", "0.5"), "Positions are fractions of the screen"),
|
||||
(("hover", "0.5", "0.5", "--to", "nan", "0.5"), "Positions are fractions of the screen"),
|
||||
(("stroke", "0", "0", "1", "1", "--pressure", "0.5:1.5"), "--pressure must be 0..1"),
|
||||
(("tap", "0.5", "0.5", "--tilt-x=-91"), "--tilt-x and --tilt-y must be -90..90"),
|
||||
(("tap", "0.5", "0.5", "--tilt-y", "120"), "--tilt-x and --tilt-y must be -90..90"),
|
||||
(("hover", "0.5", "0.5", "--distance", "256"), "--distance must be 0..255"),
|
||||
(("tap", "0.5", "0.5", "--rate", "1e9"), "--rate must be 1..1000 Hz"),
|
||||
(("button", "primary", "0.5", "0.5", "--hold", "-5"), "--hold must not be negative"),
|
||||
(("tap", "0.5", "0.5", "--hover-ms", "-1"), "--hover-ms must not be negative"),
|
||||
(("stroke", "0", "0", "1", "1", "--duration", "40000"), "lasts 40160 ms, more than 30000"),
|
||||
(("hover", "0.5", "0.5", "--duration", "1000000000"), "more than 30000"),
|
||||
]
|
||||
with unittest.mock.patch.object(ctl, "pen_times", side_effect=AssertionError):
|
||||
for argv, message in cases:
|
||||
with self.subTest(message=message):
|
||||
code, out = self.pen(*argv)
|
||||
self.assertEqual((2, "INVALID_INPUT"), (code, out["error"]["code"]))
|
||||
self.assertIn(message, out["error"]["message"])
|
||||
self.assertFalse(self.calls())
|
||||
self.assertEqual(30_000, samples("tap", "1", "1", "--hover-ms", "14970")[-1]["t"])
|
||||
|
||||
def test_a_shell_without_uinput_is_unavailable(self):
|
||||
for probe, message in (("no-uinput", "no `uinput` command"), ("no-dev-uinput", "cannot write /dev/uinput")):
|
||||
with self.subTest(probe=probe):
|
||||
self.configure({}, dumpsys_input=dumpsys_input(), uinput_probe=probe)
|
||||
code, out = self.pen("tap", "0.5", "0.5")
|
||||
self.assertEqual((3, "UINPUT_UNAVAILABLE"), (code, out["error"]["code"]))
|
||||
self.assertIn(message, out["error"]["message"])
|
||||
self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "uinput"]])
|
||||
|
||||
def test_a_missing_or_dark_display_is_refused(self):
|
||||
for dump, message in (("Input Reader State (Nums of device: 0):\n", "no internal display viewport"),
|
||||
(dumpsys_input(active=0), "Display 0 is off")):
|
||||
with self.subTest(message=message):
|
||||
self.configure({}, dumpsys_input=dump)
|
||||
code, out = self.pen("tap", "0.5", "0.5")
|
||||
self.assertEqual((3, "NO_VIEWPORT"), (code, out["error"]["code"]))
|
||||
self.assertIn(message, out["error"]["message"])
|
||||
self.assertFalse([c for c in self.calls() if c["args"][:2] == ["shell", "uinput"]])
|
||||
|
||||
def test_uinput_that_stops_early_fails(self):
|
||||
self.configure({}, dumpsys_input=dumpsys_input(), uinput_stdout="")
|
||||
code, out = self.pen("tap", "0.5", "0.5")
|
||||
self.assertEqual((3, "UINPUT_FAILED"), (code, out["error"]["code"]))
|
||||
self.assertIn("adb logcat -s UINPUT", out["error"]["message"])
|
||||
|
||||
def test_the_viewport_android_maps_touchscreens_to(self):
|
||||
self.assertEqual({"display": 0, "rotation": 0, "size": [1140, 2616], "frame": [0, 0, 1140, 2616], "active": True},
|
||||
ctl.input_viewport(dumpsys_input()))
|
||||
device = " Device 7: touchpanel\n Viewport INTERNAL: displayId=0, orientation=0, deviceSize=[1140, 2616]\n"
|
||||
self.assertEqual(1, ctl.input_viewport(device + dumpsys_input(1, (2480, 2248)))["rotation"])
|
||||
newest = (" Viewports:\n Viewport INTERNAL: displayId=3, uniqueId=local:1, port=<none>, orientation=3, "
|
||||
"densityDpi=420 xDpi=409.432007, yDpi=411.891998, logicalFrame=[0, 0, 2400, 1080], "
|
||||
"physicalFrame=[0, 0, 2400, 1080], deviceSize=[2400, 1080], isActive=[1]\n"
|
||||
" Viewport INTERNAL: displayId=5, uniqueId=local:3, port=2, orientation=0, "
|
||||
"deviceSize=[1080, 2400], isActive=[1]\n"
|
||||
" Viewport EXTERNAL: displayId=0, uniqueId=local:2, port=1, orientation=0, "
|
||||
"deviceSize=[1920, 1080], isActive=[1]\n")
|
||||
self.assertEqual({"display": 3, "rotation": 3, "size": [2400, 1080], "frame": [0, 0, 2400, 1080], "active": True},
|
||||
ctl.input_viewport(newest))
|
||||
older = ("Viewport INTERNAL: displayId=0, orientation=2, logicalFrame=[0, 0, 720, 1280], "
|
||||
"physicalFrame=[-3, 0, 717, 1280], deviceSize=[720, 1280]")
|
||||
self.assertEqual({"display": 0, "rotation": 2, "size": [720, 1280], "frame": [-3, 0, 717, 1280], "active": True},
|
||||
ctl.input_viewport(older))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1069,26 +1069,36 @@ class LauncherTest(SyncTestCase):
|
||||
dist = self.dist_of(pack["id"], tool)
|
||||
game_env = runpy.run_path(str(BIN / "droiddeck-game-env"))
|
||||
command = [str(tool / "proton"), "waitforexitandrun", "game.exe"]
|
||||
env = self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="1", WINEESYNC="1")
|
||||
calls = []
|
||||
cases = (
|
||||
({}, {"WINEDLLOVERRIDES": "tabtip.exe=d"}),
|
||||
({"WINEDLLOVERRIDES": "dxgi=n"}, {"WINEDLLOVERRIDES": "dxgi=n;tabtip.exe=d"}),
|
||||
({"WINEDLLOVERRIDES": "dxgi=n;tabtip.exe=b"}, {"WINEDLLOVERRIDES": "dxgi=n;tabtip.exe=b"}),
|
||||
({"SteamDeck": "1"}, {"SteamDeck": "1"}),
|
||||
)
|
||||
for inherited, expected in cases:
|
||||
with self.subTest(inherited=inherited):
|
||||
env = self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="1", WINEESYNC="1", **inherited)
|
||||
calls = []
|
||||
|
||||
def execvpe(path, args, environment):
|
||||
calls.append((path, list(args), dict(environment)))
|
||||
if len(calls) == 1:
|
||||
raise PermissionError("denied")
|
||||
raise SystemExit(0)
|
||||
def execvpe(path, args, environment):
|
||||
calls.append((path, list(args), dict(environment)))
|
||||
if len(calls) == 1:
|
||||
raise PermissionError("denied")
|
||||
raise SystemExit(0)
|
||||
|
||||
with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(sys, "argv", ["droiddeck-game-env"] + command), \
|
||||
mock.patch("os.execvpe", execvpe), contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
with self.assertRaises(SystemExit):
|
||||
game_env["main"]()
|
||||
self.assertEqual([call[:2] for call in calls], [(str(dist / "proton"), [str(dist / "proton")] + command[1:]),
|
||||
(str(tool / "proton"), command)])
|
||||
self.assertEqual((calls[0][2]["WINEESYNC"], calls[0][2]["PROTON_NO_ESYNC"], calls[0][2]["BL_SYNC_PACK"]), ("0", "1", pack["id"]))
|
||||
self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="0", WINEESYNC="1",
|
||||
vblank_mode="0", GAMESCOPE_WSI_MIN_IMAGE_COUNT="8",
|
||||
GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT="1"))
|
||||
self.assertIn("could not start (", said.getvalue())
|
||||
with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(sys, "argv", ["droiddeck-game-env"] + command), \
|
||||
mock.patch("os.execvpe", execvpe), contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
with self.assertRaises(SystemExit):
|
||||
game_env["main"]()
|
||||
self.assertEqual([call[:2] for call in calls], [(str(dist / "proton"), [str(dist / "proton")] + command[1:]),
|
||||
(str(tool / "proton"), command)])
|
||||
self.assertEqual((calls[0][2]["WINEESYNC"], calls[0][2]["PROTON_NO_ESYNC"], calls[0][2]["BL_SYNC_PACK"]), ("0", "1", pack["id"]))
|
||||
self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="0", WINEESYNC="1",
|
||||
vblank_mode="0", GAMESCOPE_WSI_MIN_IMAGE_COUNT="8",
|
||||
GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT="1", **expected))
|
||||
self.assertEqual(calls[0][2].get("WINEDLLOVERRIDES"), expected.get("WINEDLLOVERRIDES"))
|
||||
self.assertEqual(calls[0][2].get("SteamDeck"), expected.get("SteamDeck"))
|
||||
self.assertIn("could not start (", said.getvalue())
|
||||
|
||||
def test_generated_launchers_run_the_dist_proton(self):
|
||||
root = self.store()
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import fcntl
|
||||
import mmap
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
@@ -5,6 +7,8 @@ import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
|
||||
@@ -14,6 +18,14 @@ HEADER = 64
|
||||
EVENT = 24
|
||||
CAPACITY = 4096
|
||||
DESCRIPTION = 1824
|
||||
RING_SIZE = HEADER + CAPACITY * EVENT
|
||||
DECK_IMU = 64
|
||||
TRITON_BLOCK = 256
|
||||
TRITON_MAGIC = 0x4E525454
|
||||
TOUCH_MAGIC = 0x31484354
|
||||
TOUCH_RING_SIZE = 256
|
||||
PAD_TYPE_DECK = 0
|
||||
PAD_TYPE_STEAM = 1
|
||||
READER = r"""
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
@@ -215,6 +227,72 @@ int main(int argc, char **argv)
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
HIDRAW_PROBE = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/hidraw.h>
|
||||
#include <poll.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int fd = open(argv[1], O_RDONLY | O_NONBLOCK);
|
||||
if (fd < 0) {
|
||||
puts(errno == ENOENT ? "refused" : "failed");
|
||||
return 0;
|
||||
}
|
||||
struct hidraw_devinfo info;
|
||||
if (ioctl(fd, HIDIOCGRAWINFO, &info) < 0)
|
||||
return 1;
|
||||
struct pollfd ready = {fd, POLLIN, 0};
|
||||
unsigned char report[64];
|
||||
if (poll(&ready, 1, 2000) != 1 || read(fd, report, sizeof(report)) <= 0)
|
||||
return 2;
|
||||
printf("%04hx:%04hx report %02x\n", info.vendor, info.product, report[0]);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
FEATURE_PROBE = r"""
|
||||
#include <fcntl.h>
|
||||
#include <linux/hidraw.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/ioctl.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
unsigned char id = (unsigned char)strtoul(argv[1], NULL, 0);
|
||||
int fd = open("/dev/hidraw18", O_RDWR);
|
||||
if (fd < 0)
|
||||
return 1;
|
||||
int count = argc > 2 ? atoi(argv[2]) : 200, wrong = 0;
|
||||
for (int i = 0; i < count; i++) {
|
||||
unsigned char report[64] = {id};
|
||||
if (ioctl(fd, HIDIOCGFEATURE(sizeof(report)), report) < 0 || report[0] != id || report[1] != id)
|
||||
wrong++;
|
||||
}
|
||||
printf("%d wrong\n", wrong);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
IMU_MODE_PROBE = r"""
|
||||
#include <fcntl.h>
|
||||
#include <linux/hidraw.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/ioctl.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
unsigned mode = (unsigned)strtoul(argv[1], NULL, 0);
|
||||
int fd = open("/dev/hidraw16", O_RDWR);
|
||||
if (fd < 0)
|
||||
return 1;
|
||||
unsigned char report[65] = {0x00, 0x87, 3, 48, mode & 0xff, mode >> 8};
|
||||
return ioctl(fd, HIDIOCSFEATURE(sizeof(report)), report) < 0;
|
||||
}
|
||||
"""
|
||||
OVERLAY_READ = r"""
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
@@ -348,6 +426,117 @@ class FakeinputRingTest(unittest.TestCase):
|
||||
self.assertEqual(run.returncode, 0, run.stderr)
|
||||
self.assertEqual(run.stdout, "JSIOCGNAME -1 EINVAL\n28de:11ff Microsoft X-Box 360 pad 0\n")
|
||||
|
||||
def pad_ring(self, pad_type, triton_connected=False):
|
||||
hooks, ring = self.ring(virtual=False)
|
||||
data = bytearray(ring.read_bytes()) + bytearray(DECK_IMU + TRITON_BLOCK)
|
||||
struct.pack_into("<I", data, RING_SIZE + 44, 0x80000000 | pad_type)
|
||||
struct.pack_into("<II", data, RING_SIZE + DECK_IMU, TRITON_MAGIC, 1 if triton_connected else 0)
|
||||
ring.write_bytes(bytes(data))
|
||||
env = dict(os.environ, FAKE_EVDEV_DIR=str(hooks), FAKE_EVDEV_DECK="1", FAKE_EVDEV_TRITON="1",
|
||||
FAKE_EVDEV_MEMFD_PATHS="0=" + str(ring))
|
||||
return ring, env
|
||||
|
||||
def as_process(self, binary, name):
|
||||
named = self.tmp / name
|
||||
shutil.copy(binary, named)
|
||||
return str(named)
|
||||
|
||||
def assert_opened_by_steam_and_remote_play_only(self, device, expected, env):
|
||||
library, probe = self.build("-m64", HIDRAW_PROBE, "hidraw-probe")
|
||||
env = dict(env, LD_PRELOAD=str(library))
|
||||
for name, want in (("steam", expected), ("streaming_client", expected), ("game", "refused\n")):
|
||||
with self.subTest(name=name):
|
||||
run = subprocess.run([self.as_process(probe, name), device], capture_output=True, text=True,
|
||||
timeout=10, env=env)
|
||||
self.assertEqual(run.returncode, 0, run.stderr)
|
||||
self.assertEqual(run.stdout, want)
|
||||
|
||||
def test_the_deck_pad_opens_in_steam_and_its_remote_play_client_only(self):
|
||||
_, env = self.pad_ring(PAD_TYPE_DECK)
|
||||
self.assert_opened_by_steam_and_remote_play_only("/dev/hidraw16", "28de:1205 report 01\n", env)
|
||||
|
||||
def test_the_steam_controller_pad_opens_in_steam_and_its_remote_play_client_only(self):
|
||||
_, env = self.pad_ring(PAD_TYPE_STEAM)
|
||||
self.assert_opened_by_steam_and_remote_play_only("/dev/hidraw19", "28de:1302 report 42\n", env)
|
||||
|
||||
def test_the_touch_controller_opens_in_steam_and_its_remote_play_client_only(self):
|
||||
_, env = self.pad_ring(PAD_TYPE_DECK)
|
||||
touch = self.tmp / "touchctl"
|
||||
data = bytearray(TOUCH_RING_SIZE)
|
||||
struct.pack_into("<I", data, 0, TOUCH_MAGIC)
|
||||
struct.pack_into("<I", data, 56, 1)
|
||||
touch.write_bytes(bytes(data))
|
||||
env["FAKE_TOUCHCTL_RING"] = str(touch)
|
||||
self.assert_opened_by_steam_and_remote_play_only("/dev/hidraw17", "0000:11fb report 00\n", env)
|
||||
|
||||
def ask_paired_controller(self, probes, locks_unavailable=False, held=False, count=200):
|
||||
library, probe = self.build("-m64", FEATURE_PROBE, "feature-probe")
|
||||
ring, env = self.pad_ring(PAD_TYPE_DECK, triton_connected=True)
|
||||
env["LD_PRELOAD"] = str(library)
|
||||
lock = Path(env["FAKE_EVDEV_DIR"]) / ".triton-feature.lock"
|
||||
if locks_unavailable:
|
||||
lock.mkdir()
|
||||
holder = open(lock, "w") if held else None
|
||||
if holder:
|
||||
self.addCleanup(holder.close)
|
||||
fcntl.flock(holder, fcntl.LOCK_EX)
|
||||
block = RING_SIZE + DECK_IMU
|
||||
stop = threading.Event()
|
||||
|
||||
def controller():
|
||||
with open(ring, "r+b") as f, mmap.mmap(f.fileno(), 0) as shared:
|
||||
served = 0
|
||||
while not stop.is_set():
|
||||
request = struct.unpack_from("<Q", shared, block + 168)[0]
|
||||
if request == served:
|
||||
time.sleep(0.0001)
|
||||
continue
|
||||
report_id = struct.unpack_from("<I", shared, block + 184)[0]
|
||||
struct.pack_into("<i", shared, block + 188, 2)
|
||||
struct.pack_into("<BB", shared, block + 192, report_id, report_id)
|
||||
struct.pack_into("<Q", shared, block + 176, request)
|
||||
served = request
|
||||
|
||||
thread = threading.Thread(target=controller)
|
||||
thread.start()
|
||||
try:
|
||||
runs = [subprocess.Popen([self.as_process(probe, name), report_id, str(count)], stdout=subprocess.PIPE,
|
||||
text=True, env=env)
|
||||
for name, report_id in probes]
|
||||
outputs = [run.communicate(timeout=60)[0] for run in runs]
|
||||
finally:
|
||||
stop.set()
|
||||
thread.join()
|
||||
self.assertEqual([run.returncode for run in runs], [0] * len(probes))
|
||||
return outputs
|
||||
|
||||
def test_steam_and_its_remote_play_client_take_turns_with_the_paired_controllers_features(self):
|
||||
outputs = self.ask_paired_controller((("steam", "0x11"), ("streaming_client", "0x22")))
|
||||
self.assertEqual(outputs, ["0 wrong\n", "0 wrong\n"])
|
||||
|
||||
def test_without_the_lock_only_steam_asks_the_paired_controller(self):
|
||||
outputs = self.ask_paired_controller((("steam", "0x11"), ("streaming_client", "0x22")), locks_unavailable=True)
|
||||
self.assertEqual(outputs, ["0 wrong\n", "200 wrong\n"])
|
||||
|
||||
def test_a_stopped_lock_holder_does_not_stall_steam_or_its_remote_play_client(self):
|
||||
started = time.monotonic()
|
||||
outputs = self.ask_paired_controller((("steam", "0x11"), ("streaming_client", "0x22")), held=True, count=3)
|
||||
self.assertEqual(outputs, ["3 wrong\n", "3 wrong\n"])
|
||||
self.assertLess(time.monotonic() - started, 20)
|
||||
|
||||
def test_steam_turning_motion_off_leaves_it_on_for_its_remote_play_client(self):
|
||||
library, probe = self.build("-m64", IMU_MODE_PROBE, "imu-mode-probe")
|
||||
ring, env = self.pad_ring(PAD_TYPE_DECK)
|
||||
env["LD_PRELOAD"] = str(library)
|
||||
pids = {}
|
||||
for name, mode in (("steam", "0x18"), ("streaming_client", "0x18"), ("steam", "0x00")):
|
||||
run = subprocess.Popen([self.as_process(probe, name), mode], env=env)
|
||||
self.assertEqual(run.wait(timeout=10), 0)
|
||||
pids[name] = run.pid
|
||||
data = ring.read_bytes()
|
||||
self.assertEqual(struct.unpack_from("<I", data, RING_SIZE + 4)[0], 0x80000000)
|
||||
self.assertEqual(struct.unpack_from("<II", data, RING_SIZE + 52), (0x80000018, pids["streaming_client"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,145 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
|
||||
RING_MAGIC = 0x46494252
|
||||
DESCRIPTION_MAGIC = 0x46495544
|
||||
HEADER = 64
|
||||
EVENT = 24
|
||||
CAPACITY = 4096
|
||||
DESCRIPTION = 1824
|
||||
|
||||
GAME = r"""
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int rumble(int fd, unsigned short strong) {
|
||||
struct ff_effect effect;
|
||||
memset(&effect, 0, sizeof(effect));
|
||||
effect.id = -1;
|
||||
effect.type = FF_RUMBLE;
|
||||
effect.u.rumble.strong_magnitude = strong;
|
||||
effect.u.rumble.weak_magnitude = 20000;
|
||||
if (ioctl(fd, EVIOCSFF, &effect) < 0) return -1;
|
||||
struct input_event play;
|
||||
memset(&play, 0, sizeof(play));
|
||||
play.type = EV_FF;
|
||||
play.code = effect.id;
|
||||
play.value = 1;
|
||||
if (write(fd, &play, sizeof(play)) != sizeof(play)) return -1;
|
||||
return effect.id;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int fd = open("/dev/input/event16", O_RDWR | O_NONBLOCK);
|
||||
if (fd < 0) return 1;
|
||||
if (argv[1][0] == 'p') {
|
||||
int other = open("/dev/input/event16", O_RDWR | O_NONBLOCK);
|
||||
if (other < 0 || rumble(fd, 40000) < 0 || rumble(other, 30000) < 0) return 2;
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
if (argv[1][0] == 'k') {
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
if (rumble(fd, 40000) < 0) _exit(2);
|
||||
close(fd);
|
||||
_exit(0);
|
||||
}
|
||||
int status = 0;
|
||||
waitpid(child, &status, 0);
|
||||
return WEXITSTATUS(status);
|
||||
}
|
||||
struct ff_effect effect;
|
||||
effect.id = rumble(fd, 40000);
|
||||
if (effect.id < 0) return 2;
|
||||
if (argv[1][0] == 'e') ioctl(fd, EVIOCRMFF, effect.id);
|
||||
else if (argv[1][0] == 'c') close(fd);
|
||||
else if (argv[1][0] == 'f') {
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
close(fd);
|
||||
_exit(0);
|
||||
}
|
||||
waitpid(child, NULL, 0);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "linux" and shutil.which("g++") and shutil.which("gcc"), "needs Linux, gcc and g++")
|
||||
class FakeinputRumbleStopTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
cls.addClassCleanup(shutil.rmtree, cls.tmp, True)
|
||||
cls.library = cls.tmp / "libfakeinput.so"
|
||||
subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread", "-std=c++17",
|
||||
"-static-libstdc++", "-static-libgcc", "-Wl,--exclude-libs,ALL", "-o", str(cls.library),
|
||||
str(SOURCE), "-ldl"], check=True)
|
||||
cls.game = cls.tmp / "game"
|
||||
(cls.tmp / "game.c").write_text(GAME)
|
||||
subprocess.run(["gcc", "-o", str(cls.game), str(cls.tmp / "game.c")], check=True)
|
||||
cls.hooks = cls.tmp / "hooks"
|
||||
cls.hooks.mkdir()
|
||||
(cls.hooks / "event16").touch()
|
||||
ring = bytearray(HEADER + CAPACITY * EVENT + DESCRIPTION)
|
||||
struct.pack_into("<IIIIQQQ", ring, 0, RING_MAGIC, 2, EVENT, CAPACITY, 0, 0, 0)
|
||||
struct.pack_into("<IiHHHHI80s", ring, HEADER + CAPACITY * EVENT, DESCRIPTION_MAGIC, os.getpid(),
|
||||
3, 0x28de, 0x11ff, 1, 16, b"Microsoft X-Box 360 pad 0")
|
||||
(cls.hooks / ".uinput-event16").write_bytes(bytes(ring))
|
||||
|
||||
def packets(self, ending):
|
||||
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.addCleanup(server.close)
|
||||
try:
|
||||
server.bind("\0droiddeck-rumble")
|
||||
except OSError:
|
||||
self.skipTest("the rumble socket name is taken on this machine")
|
||||
server.listen(16)
|
||||
server.settimeout(0.5)
|
||||
env = dict(os.environ, LD_PRELOAD=str(self.library), FAKE_EVDEV_DIR=str(self.hooks), FAKE_EVDEV_VIBRATION="1")
|
||||
run = subprocess.run([str(self.game), ending], env=env, capture_output=True, timeout=10)
|
||||
self.assertEqual(run.returncode, 0, run.stderr)
|
||||
got = []
|
||||
while True:
|
||||
try:
|
||||
client, _ = server.accept()
|
||||
except socket.timeout:
|
||||
return got
|
||||
with client:
|
||||
got.append(struct.unpack("<4H", client.recv(8))[:3])
|
||||
|
||||
def test_closing_the_controller_stops_its_held_rumble(self):
|
||||
self.assertEqual(self.packets("close")[-1], (0, 0, 0))
|
||||
|
||||
def test_erasing_the_playing_effect_stops_it(self):
|
||||
self.assertEqual(self.packets("erase")[-1], (0, 0, 0))
|
||||
|
||||
def test_a_forked_child_closing_its_copy_leaves_the_parents_rumble(self):
|
||||
self.assertEqual(self.packets("fork")[-1], (40000, 20000, 0xffff))
|
||||
|
||||
def test_a_child_that_plays_on_an_inherited_controller_stops_it_on_close(self):
|
||||
self.assertEqual(self.packets("kid")[-1], (0, 0, 0))
|
||||
|
||||
def test_closing_an_older_handle_leaves_the_newer_rumble_on_the_slot(self):
|
||||
self.assertEqual(self.packets("pair")[-1], (30000, 20000, 0xffff))
|
||||
|
||||
def test_a_held_effect_still_plays_until_then(self):
|
||||
self.assertIn((40000, 20000, 0xffff), self.packets("keep"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -33,6 +33,94 @@ class SupergiantDotnetReporterTest(unittest.TestCase):
|
||||
self.assertIsNone(MODULE["supergiant_dotnet_reporter"](game))
|
||||
|
||||
|
||||
class DeathStrandingAllocatorTest(unittest.TestCase):
|
||||
def make_exe(self, name="ds.exe", size=None, window=None, tail=None):
|
||||
folder = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, folder, True)
|
||||
path = os.path.join(folder, name)
|
||||
with open(path, "wb") as game:
|
||||
game.truncate(MODULE["DS_SIZE"] if size is None else size)
|
||||
game.seek(MODULE["DS_WINDOW_OFFSET"] - 1)
|
||||
game.write(b"<" + (MODULE["DS_WINDOW"] if window is None else window) + (MODULE["DS_ORIGINAL"] if tail is None else tail) + b">")
|
||||
return path
|
||||
|
||||
def read_tail(self, path):
|
||||
with open(path, "rb") as game:
|
||||
game.seek(MODULE["DS_WINDOW_OFFSET"] - 1)
|
||||
return game.read(len(MODULE["DS_WINDOW"]) + len(MODULE["DS_ORIGINAL"]) + 2)
|
||||
|
||||
def run_fix(self, path, app_id="1850570"):
|
||||
errors = io.StringIO()
|
||||
with mock.patch("sys.stderr", errors):
|
||||
return MODULE["death_stranding_allocator"](app_id, path), errors.getvalue()
|
||||
|
||||
def test_window_and_patch_have_the_measured_shape(self):
|
||||
self.assertEqual(41, len(MODULE["DS_WINDOW"]))
|
||||
self.assertEqual(6, len(MODULE["DS_ORIGINAL"]))
|
||||
self.assertEqual(6, len(MODULE["DS_FIXED"]))
|
||||
self.assertEqual(0x38FE1B9, MODULE["DS_WINDOW_OFFSET"] + len(MODULE["DS_WINDOW"]))
|
||||
|
||||
def test_replaces_only_the_jump_in_the_original_build(self):
|
||||
path = self.make_exe()
|
||||
patched, message = self.run_fix(path)
|
||||
self.assertTrue(patched)
|
||||
self.assertIn("Death Stranding", message)
|
||||
self.assertEqual(b"<" + MODULE["DS_WINDOW"] + MODULE["DS_FIXED"] + b">", self.read_tail(path))
|
||||
self.assertEqual(MODULE["DS_SIZE"], os.path.getsize(path))
|
||||
|
||||
def test_an_already_patched_game_is_left_alone(self):
|
||||
path = self.make_exe(tail=MODULE["DS_FIXED"])
|
||||
before = os.stat(path).st_mtime_ns
|
||||
self.assertEqual((False, ""), self.run_fix(path))
|
||||
self.assertEqual(before, os.stat(path).st_mtime_ns)
|
||||
self.assertEqual(b"<" + MODULE["DS_WINDOW"] + MODULE["DS_FIXED"] + b">", self.read_tail(path))
|
||||
|
||||
def test_a_second_run_changes_nothing(self):
|
||||
path = self.make_exe()
|
||||
self.assertTrue(self.run_fix(path)[0])
|
||||
after_first = self.read_tail(path)
|
||||
self.assertEqual((False, ""), self.run_fix(path))
|
||||
self.assertEqual(after_first, self.read_tail(path))
|
||||
|
||||
def test_other_builds_of_the_game_are_not_touched(self):
|
||||
for size, window in ((MODULE["DS_SIZE"] + 1, None), (None, bytes(len(MODULE["DS_WINDOW"])))):
|
||||
path = self.make_exe(size=size, window=window)
|
||||
before = self.read_tail(path)
|
||||
self.assertEqual((False, ""), self.run_fix(path))
|
||||
self.assertEqual(before, self.read_tail(path))
|
||||
|
||||
def test_an_unknown_instruction_at_the_patch_site_is_not_touched(self):
|
||||
path = self.make_exe(tail=bytes.fromhex("0f85a6000000"))
|
||||
before = self.read_tail(path)
|
||||
self.assertEqual((False, ""), self.run_fix(path))
|
||||
self.assertEqual(before, self.read_tail(path))
|
||||
|
||||
def test_other_executables_are_ignored(self):
|
||||
path = self.make_exe(name="game.exe")
|
||||
before = self.read_tail(path)
|
||||
self.assertEqual((False, ""), self.run_fix(path))
|
||||
self.assertEqual(before, self.read_tail(path))
|
||||
|
||||
def test_other_games_are_not_touched_even_with_a_matching_file(self):
|
||||
for app_id in ("440", "", None):
|
||||
path = self.make_exe()
|
||||
before = self.read_tail(path)
|
||||
self.assertEqual((False, ""), self.run_fix(path, app_id))
|
||||
self.assertEqual(before, self.read_tail(path))
|
||||
|
||||
def test_both_death_stranding_app_ids_are_patched(self):
|
||||
for app_id in ("1850570", "1190460"):
|
||||
self.assertTrue(self.run_fix(self.make_exe(), app_id)[0])
|
||||
|
||||
def test_the_file_name_check_ignores_case(self):
|
||||
self.assertTrue(self.run_fix(self.make_exe(name="DS.EXE"))[0])
|
||||
|
||||
def test_a_missing_game_file_is_reported_without_raising(self):
|
||||
patched, message = self.run_fix(os.path.join(tempfile.gettempdir(), "droiddeck-no-such-folder", "ds.exe"))
|
||||
self.assertFalse(patched)
|
||||
self.assertIn("not applied", message)
|
||||
|
||||
|
||||
def mapping_of(text):
|
||||
tokens = COMPAT["tokenize"](text)
|
||||
return COMPAT["read_mapping"](tokens, COMPAT["mapping_block"](tokens))
|
||||
@@ -723,6 +811,7 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
"install_scripts_done": lambda scripts, env: False,
|
||||
"scripts_digest": lambda scripts: None,
|
||||
"win_components": lambda *args: seen_components.append(args[3]) or "",
|
||||
"restore_compatible_system_dlls": lambda *args: [],
|
||||
"repair_foreign_system_dlls": lambda *args: seen_repair.append(args[2]) or [],
|
||||
"gl_vsync": lambda env: False,
|
||||
"game_images": lambda env: None,
|
||||
@@ -756,6 +845,61 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(["0"], [env["PROTON_USE_ARM64"] for env in seen_repair])
|
||||
self.assertEqual(["0"], [env["PROTON_USE_ARM64"] for env in seen_start])
|
||||
|
||||
def test_keyboard_helper_is_off_unless_steam_keyboard_or_the_user_wants_it(self):
|
||||
cases = (
|
||||
({}, "tabtip.exe=d"),
|
||||
({"WINEDLLOVERRIDES": "dxgi=n"}, "dxgi=n;tabtip.exe=d"),
|
||||
({"WINEDLLOVERRIDES": "tabtipx=d"}, "tabtipx=d;tabtip.exe=d"),
|
||||
({"SteamDeck": "0"}, "tabtip.exe=d"),
|
||||
({"SteamDeck": "1"}, None),
|
||||
({"SteamDeck": "1", "WINEDLLOVERRIDES": "dxgi=n"}, "dxgi=n"),
|
||||
({"WINEDLLOVERRIDES": "tabtip.exe=b"}, "tabtip.exe=b"),
|
||||
({"WINEDLLOVERRIDES": "dxgi=n; TabTip.EXE=n,b"}, "dxgi=n; TabTip.EXE=n,b"),
|
||||
({"WINEDLLOVERRIDES": "dxgi=n; TabTip=n,b"}, "dxgi=n; TabTip=n,b;tabtip.exe=d"),
|
||||
({"WINEDLLOVERRIDES": "d3d11 tabtip.exe"}, "d3d11 tabtip.exe;tabtip.exe=d"),
|
||||
({"WINEDLLOVERRIDES": "tabtip.exe;dxgi=n"}, "tabtip.exe;dxgi=n;tabtip.exe=d"),
|
||||
({"WINEDLLOVERRIDES": "d3d11,tabtip.exe=b"}, "d3d11,tabtip.exe=b"),
|
||||
({"WINEDLLOVERRIDES": "d3d11 tabtip.exe=b"}, "d3d11 tabtip.exe=b"),
|
||||
({"WINEDLLOVERRIDES": "d3d11\ttabtip.exe=b"}, "d3d11\ttabtip.exe=b"),
|
||||
({"WINEDLLOVERRIDES": "d3d11\ttabtip=b"}, "d3d11\ttabtip=b;tabtip.exe=d"),
|
||||
({"WINEDLLOVERRIDES": "d3d11 dxgi=n"}, "d3d11 dxgi=n;tabtip.exe=d"),
|
||||
({"WINEDLLOVERRIDES": "*tabtip.exe=b"}, "*tabtip.exe=b"),
|
||||
({"WINEDLLOVERRIDES": "TabTip.exe.DLL=b"}, "TabTip.exe.DLL=b"),
|
||||
({"WINEDLLOVERRIDES": "d3d11,*tabtip.exe.dll=n"}, "d3d11,*tabtip.exe.dll=n"),
|
||||
({"WINEDLLOVERRIDES": "*tabtip=b"}, "*tabtip=b;tabtip.exe=d"),
|
||||
({"WINEDLLOVERRIDES": "tabtip.dll=b"}, "tabtip.dll=b;tabtip.exe=d"),
|
||||
)
|
||||
for before, overrides in cases:
|
||||
with self.subTest(env=before):
|
||||
env = dict(before)
|
||||
note = MODULE["keyboard_helper_off"](env)
|
||||
self.assertEqual(env.get("WINEDLLOVERRIDES"), overrides)
|
||||
self.assertEqual(note is not None, overrides != before.get("WINEDLLOVERRIDES"))
|
||||
|
||||
def test_game_launch_turns_the_keyboard_helper_off_and_keeps_user_choices(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
probe = home / "probe"
|
||||
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('WINEDLLOVERRIDES', 'unset'))\n")
|
||||
probe.chmod(0o755)
|
||||
config = home / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
cases = (
|
||||
("waitforexitandrun", {}, "tabtip.exe=d"),
|
||||
("waitforexitandrun", {"WINEDLLOVERRIDES": "dxgi=n"}, "dxgi=n;tabtip.exe=d"),
|
||||
("waitforexitandrun", {"SteamDeck": "1"}, "unset"),
|
||||
("waitforexitandrun", {"WINEDLLOVERRIDES": "tabtip.exe=b"}, "tabtip.exe=b"),
|
||||
("run", {}, "unset"),
|
||||
)
|
||||
for verb, profile, expected in cases:
|
||||
with self.subTest(verb=verb, profile=profile):
|
||||
config.write_text(json.dumps({"version": 1, "games": {"42": profile}}))
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("SteamDeck", "WINEDLLOVERRIDES")}
|
||||
env.update(HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/42")
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), verb],
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
self.assertEqual(result.stdout.strip().splitlines()[-1], expected)
|
||||
|
||||
def test_optional_xbox_loader_failure_keeps_stock_launch(self):
|
||||
from unittest.mock import patch
|
||||
for error in (FileNotFoundError('missing'), RuntimeError('module initialization failed')):
|
||||
@@ -1172,6 +1316,8 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
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], [])
|
||||
(game / "data_game_windows_x86_64/Sentry.Godot.dll").touch()
|
||||
self.assertNotIn("WINEDLLOVERRIDES", MODULE["engine_fixes"](str(game / "Game.exe"), [])[0])
|
||||
script = Path(tmp) / "GDScript Game"
|
||||
script.mkdir()
|
||||
for name in ("Game.exe", "Game.pck", "libsentry.windows.release.x86_64.dll"):
|
||||
@@ -1592,6 +1738,35 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
self.assertEqual(result["FEX_TSOENABLED"], "0")
|
||||
self.assertEqual(result["WINEDLLOVERRIDES"], "dxgi=n;libsentry=d")
|
||||
|
||||
def test_game_dll_overrides_follow_droiddecks_own(self):
|
||||
fixes = {"WINEDLLOVERRIDES": "msvcp100=n,b"}
|
||||
config = {"version": 1, "shared": {}, "games": {"42": {"WINEDLLOVERRIDES": "windowscodecs,windowscodecsext=n"}}}
|
||||
result = MODULE["apply_config"]({}, config, "42", fixes)
|
||||
self.assertEqual(result["WINEDLLOVERRIDES"], "msvcp100=n,b;windowscodecs,windowscodecsext=n")
|
||||
|
||||
def test_game_dll_overrides_edge_cases(self):
|
||||
fixes = {"WINEDLLOVERRIDES": "msvcp100=n,b"}
|
||||
env = {"WINEDLLOVERRIDES": "dxgi=n"}
|
||||
for game, shared, expected in (
|
||||
({"WINEDLLOVERRIDES": "msvcp100=b"}, {}, "msvcp100=n,b;msvcp100=b"),
|
||||
({"WINEDLLOVERRIDES": ""}, {}, "msvcp100=n,b"),
|
||||
({"WINEDLLOVERRIDES": None}, {}, None),
|
||||
({"WINEDLLOVERRIDES": "d3d9=n"}, {"WINEDLLOVERRIDES": "xinput1_3=n"}, "msvcp100=n,b;d3d9=n"),
|
||||
({}, {}, "dxgi=n;msvcp100=n,b"),
|
||||
({"WINEDLLOVERRIDES": "x" * 8179}, {}, "msvcp100=n,b;" + "x" * 8179),
|
||||
):
|
||||
with self.subTest(game=game, shared=shared):
|
||||
config = {"version": 1, "shared": shared, "games": {"42": game, "43": {"WINEDLLOVERRIDES": "d3d11=n"}}}
|
||||
result = MODULE["apply_config"](env, config, "42", fixes)
|
||||
self.assertEqual(result.get("WINEDLLOVERRIDES"), expected)
|
||||
self.assertEqual(MODULE["apply_config"](env, config, "43")["WINEDLLOVERRIDES"], "d3d11=n")
|
||||
stderr = io.StringIO()
|
||||
config = {"version": 1, "shared": {}, "games": {"42": {"WINEDLLOVERRIDES": "x" * 8192}}}
|
||||
with mock.patch("sys.stderr", stderr):
|
||||
result = MODULE["apply_config"](env, config, "42", fixes)
|
||||
self.assertEqual(result["WINEDLLOVERRIDES"], "x" * 8192)
|
||||
self.assertIn("too long", stderr.getvalue())
|
||||
|
||||
def test_invalid_configuration_is_atomic(self):
|
||||
env = {"ORIGINAL": "unchanged"}
|
||||
for entries in ({"A": "ok", "BAD=KEY": "x"}, {"A": "bad\0value"}, {"A": 1}):
|
||||
@@ -2718,6 +2893,39 @@ def arm64ec_pe_image():
|
||||
return bytes(image)
|
||||
|
||||
|
||||
def program_image(machine, imports):
|
||||
image = bytearray(0x400)
|
||||
image[:2] = b"MZ"
|
||||
image[60:64] = (64).to_bytes(4, "little")
|
||||
image[64:68] = b"PE\0\0"
|
||||
coff = 68
|
||||
image[coff:coff + 2] = machine.to_bytes(2, "little")
|
||||
image[coff + 2:coff + 4] = (1).to_bytes(2, "little")
|
||||
image[coff + 16:coff + 18] = (240).to_bytes(2, "little")
|
||||
optional = coff + 20
|
||||
image[optional:optional + 2] = (0x20B).to_bytes(2, "little")
|
||||
image[optional + 108:optional + 112] = (16).to_bytes(4, "little")
|
||||
image[optional + 120:optional + 124] = (0x1000).to_bytes(4, "little")
|
||||
image[optional + 124:optional + 128] = (20 * (len(imports) + 1)).to_bytes(4, "little")
|
||||
section = optional + 240
|
||||
image[section + 8:section + 12] = (0x200).to_bytes(4, "little")
|
||||
image[section + 12:section + 16] = (0x1000).to_bytes(4, "little")
|
||||
image[section + 16:section + 20] = (0x200).to_bytes(4, "little")
|
||||
image[section + 20:section + 24] = (0x200).to_bytes(4, "little")
|
||||
name = 20 * (len(imports) + 1)
|
||||
for index, dll in enumerate(imports):
|
||||
image[0x200 + index * 20 + 12:0x200 + index * 20 + 16] = (0x1000 + name).to_bytes(4, "little")
|
||||
image[0x200 + name:0x200 + name + len(dll)] = dll.encode()
|
||||
name += len(dll) + 1
|
||||
return bytes(image)
|
||||
|
||||
|
||||
def bytes_path(folder, data):
|
||||
path = folder / "image.exe"
|
||||
path.write_bytes(data)
|
||||
return path
|
||||
|
||||
|
||||
class ForeignSystemDllTest(unittest.TestCase):
|
||||
def prefix(self, tmp, arm=True):
|
||||
proton = Path(tmp) / "Proton"
|
||||
@@ -2729,7 +2937,8 @@ class ForeignSystemDllTest(unittest.TestCase):
|
||||
for libdir, machine in (("aarch64-windows", 0xAA64), ("i386-windows", 0x14C)):
|
||||
(dist / libdir).mkdir(parents=True)
|
||||
for name in ("ucrtbase.dll", "rpcrt4.dll"):
|
||||
(dist / libdir / name).write_bytes(pe_image(machine))
|
||||
(dist / libdir / name).write_bytes(program_image(machine, []))
|
||||
(dist / "aarch64-windows/wineboot.exe").write_bytes(program_image(0xAA64, ["UCRTBASE.dll", "rpcrt4.dll"]))
|
||||
windows = Path(tmp) / "compat/pfx/drive_c/windows"
|
||||
for folder in ("system32", "syswow64"):
|
||||
(windows / folder).mkdir(parents=True)
|
||||
@@ -2769,16 +2978,148 @@ class ForeignSystemDllTest(unittest.TestCase):
|
||||
self.assertFalse((system32 / "ucrtbase.dll").is_symlink())
|
||||
self.assertEqual(0x8664, MODULE["pe_machine"](system32 / "userlib.dll"))
|
||||
|
||||
def test_x64_visual_cpp_runtime_in_arm64_system32_is_kept(self):
|
||||
def test_x64_dlls_proton_programs_do_not_import_are_kept_in_arm64_system32(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proton, compat, windows = self.prefix(tmp)
|
||||
builtins = proton.parent / "files/lib/wine/aarch64-windows"
|
||||
for name in ("msvcp140.dll", "VCRUNTIME140.dll", "msvcp_win.dll"):
|
||||
(builtins / name.lower()).write_bytes(pe_image(0xAA64))
|
||||
(builtins / "explorer.exe").write_bytes(program_image(0xAA64, ["shell32.dll"]))
|
||||
(builtins / "shell32.dll").write_bytes(program_image(0xAA64, ["msvcp_win.dll"]))
|
||||
names = ("vulkan-1.dll", "msvcp140.dll", "VCRUNTIME140.dll", "concrt140.dll", "d3dcompiler_43.dll",
|
||||
"winhttp.dll", "msvcp_win.dll")
|
||||
for name in names:
|
||||
(builtins / name.lower()).write_bytes(program_image(0xAA64, []))
|
||||
(windows / "system32" / name).write_bytes(pe_image(0x8664))
|
||||
self.assertEqual(["system32/msvcp_win.dll (machine 0x8664)"], self.run_repair(compat, proton))
|
||||
self.assertFalse((windows / "system32/msvcp140.dll").is_symlink())
|
||||
self.assertFalse((windows / "system32/VCRUNTIME140.dll").is_symlink())
|
||||
for name in names[:-1]:
|
||||
self.assertFalse((windows / "system32" / name).is_symlink())
|
||||
self.assertEqual(0x8664, MODULE["pe_machine"](windows / "system32" / name))
|
||||
|
||||
def test_repaired_dll_proton_programs_do_not_import_gets_its_native_copy_back(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proton, compat, windows = self.prefix(tmp)
|
||||
builtins = proton.parent / "files/lib/wine/aarch64-windows"
|
||||
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
|
||||
system32 = windows / "system32"
|
||||
for name in ("vulkan-1.dll", "ucrtbase.dll"):
|
||||
(system32 / name).symlink_to(os.path.relpath(builtins / name, system32))
|
||||
(system32 / (name + ".foreign-arch")).write_bytes(pe_image(0x8664))
|
||||
(system32 / "vulkan-1.dll.foreign-arch.1").write_bytes(pe_image(0x8664) + b"newest")
|
||||
restore = MODULE["restore_compatible_system_dlls"]
|
||||
self.assertEqual(["system32/vulkan-1.dll (machine 0x8664)"], restore(str(compat), str(proton)))
|
||||
self.assertFalse((system32 / "vulkan-1.dll").is_symlink())
|
||||
self.assertTrue((system32 / "vulkan-1.dll").read_bytes().endswith(b"newest"))
|
||||
self.assertFalse((system32 / "vulkan-1.dll.foreign-arch.1").exists())
|
||||
self.assertTrue((system32 / "ucrtbase.dll").is_symlink())
|
||||
self.assertEqual([], restore(str(compat), str(proton)))
|
||||
self.assertEqual([], self.run_repair(compat, proton))
|
||||
|
||||
def test_prefix_backup_directory_is_listed_once_per_pass(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proton, compat, windows = self.prefix(tmp)
|
||||
builtins = proton.parent / "files/lib/wine/aarch64-windows"
|
||||
system32 = windows / "system32"
|
||||
for index in range(12):
|
||||
name = "native_%02d.dll" % index
|
||||
(builtins / name).write_bytes(pe_image(0xAA64))
|
||||
(system32 / name).symlink_to(os.path.relpath(builtins / name, system32))
|
||||
(system32 / (name + ".foreign-arch")).write_bytes(pe_image(0x8664))
|
||||
(system32 / "ucrtbase.dll").write_bytes(pe_image(0x8664))
|
||||
original_listdir = os.listdir
|
||||
visited = []
|
||||
|
||||
def counted_listdir(folder):
|
||||
if Path(folder) == system32:
|
||||
visited.append(folder)
|
||||
return original_listdir(folder)
|
||||
|
||||
with mock.patch("os.listdir", side_effect=counted_listdir):
|
||||
restored = MODULE["restore_compatible_system_dlls"](str(compat), str(proton))
|
||||
fixed = self.run_repair(compat, proton)
|
||||
self.assertEqual(12, len(restored))
|
||||
self.assertEqual(["system32/ucrtbase.dll (machine 0x8664)"], fixed)
|
||||
# One system32 listing for restore and one for repair, regardless
|
||||
# of the number of DLLs and backup files in the prefix.
|
||||
self.assertEqual(2, len(visited))
|
||||
|
||||
def test_restore_takes_the_highest_backup_serial_across_gaps(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proton, compat, windows = self.prefix(tmp)
|
||||
builtins = proton.parent / "files/lib/wine/aarch64-windows"
|
||||
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
|
||||
system32 = windows / "system32"
|
||||
(system32 / "vulkan-1.dll").symlink_to(os.path.relpath(builtins / "vulkan-1.dll", system32))
|
||||
(system32 / "vulkan-1.dll.foreign-arch.2").write_bytes(pe_image(0x8664) + b"two")
|
||||
(system32 / "vulkan-1.dll.foreign-arch.10").write_bytes(pe_image(0x8664) + b"ten")
|
||||
self.assertEqual(["system32/vulkan-1.dll (machine 0x8664)"],
|
||||
MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
|
||||
self.assertTrue((system32 / "vulkan-1.dll").read_bytes().endswith(b"ten"))
|
||||
|
||||
def test_unreadable_proton_program_keeps_the_conservative_rule(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proton, compat, windows = self.prefix(tmp)
|
||||
builtins = proton.parent / "files/lib/wine/aarch64-windows"
|
||||
(builtins / "broken.exe").mkdir()
|
||||
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
|
||||
system32 = windows / "system32"
|
||||
(system32 / "concrt140.dll").write_bytes(pe_image(0x8664))
|
||||
(builtins / "concrt140.dll").write_bytes(pe_image(0xAA64))
|
||||
(system32 / "vulkan-1.dll").symlink_to(os.path.relpath(builtins / "vulkan-1.dll", system32))
|
||||
(system32 / "vulkan-1.dll.foreign-arch").write_bytes(pe_image(0x8664))
|
||||
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
|
||||
self.assertTrue((system32 / "vulkan-1.dll").is_symlink())
|
||||
self.assertEqual(["system32/concrt140.dll (machine 0x8664)"], self.run_repair(compat, proton))
|
||||
|
||||
def test_new_backup_goes_above_the_highest_existing_serial(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proton, compat, windows = self.prefix(tmp)
|
||||
system32 = windows / "system32"
|
||||
(system32 / "ucrtbase.dll").write_bytes(pe_image(0x8664) + b"newest")
|
||||
(system32 / "ucrtbase.dll.foreign-arch").write_bytes(pe_image(0x8664))
|
||||
(system32 / "ucrtbase.dll.foreign-arch.2").write_bytes(pe_image(0x8664))
|
||||
self.assertEqual(["system32/ucrtbase.dll (machine 0x8664)"], self.run_repair(compat, proton))
|
||||
self.assertTrue((system32 / "ucrtbase.dll.foreign-arch.3").read_bytes().endswith(b"newest"))
|
||||
self.assertFalse((system32 / "ucrtbase.dll.foreign-arch.1").exists())
|
||||
|
||||
def test_truncated_import_table_keeps_the_conservative_rule(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proton, compat, windows = self.prefix(tmp)
|
||||
builtins = proton.parent / "files/lib/wine/aarch64-windows"
|
||||
(builtins / "cut.exe").write_bytes(program_image(0xAA64, ["concrt140.dll"])[:0x20A])
|
||||
self.assertIsNone(MODULE["PE"]["pe_imports"](builtins / "cut.exe"))
|
||||
self.assertIsNone(MODULE["PE"]["pe_imports"](bytes_path(Path(tmp), program_image(0xAA64, ["a.dll"])[:200])))
|
||||
self.assertEqual(set(), MODULE["PE"]["pe_imports"](bytes_path(Path(tmp), program_image(0xAA64, []))))
|
||||
moved = bytearray(program_image(0xAA64, ["concrt140.dll"]))
|
||||
moved[208:212] = (0x3000).to_bytes(4, "little")
|
||||
self.assertIsNone(MODULE["PE"]["pe_imports"](bytes_path(Path(tmp), moved)))
|
||||
(builtins / "concrt140.dll").write_bytes(pe_image(0xAA64))
|
||||
(windows / "system32/concrt140.dll").write_bytes(pe_image(0x8664))
|
||||
self.assertEqual(["system32/concrt140.dll (machine 0x8664)"], self.run_repair(compat, proton))
|
||||
|
||||
def test_restore_leaves_other_links_and_x64_proton_alone(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proton, compat, windows = self.prefix(tmp)
|
||||
builtins = proton.parent / "files/lib/wine/aarch64-windows"
|
||||
(builtins / "vulkan-1.dll").write_bytes(pe_image(0xAA64))
|
||||
other = Path(tmp) / "other-vulkan-1.dll"
|
||||
other.write_bytes(pe_image(0xAA64))
|
||||
system32 = windows / "system32"
|
||||
(system32 / "vulkan-1.dll").symlink_to(other)
|
||||
(system32 / "vulkan-1.dll.foreign-arch").write_bytes(pe_image(0x8664))
|
||||
(system32 / "rpcrt4.dll").symlink_to(os.path.relpath(builtins / "rpcrt4.dll", system32))
|
||||
(system32 / "rpcrt4.dll.foreign-arch").write_bytes(pe_image(0x14C))
|
||||
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
|
||||
self.assertTrue((system32 / "vulkan-1.dll").is_symlink())
|
||||
self.assertTrue((system32 / "rpcrt4.dll").is_symlink())
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proton, compat, windows = self.prefix(tmp, arm=False)
|
||||
dist = proton.parent / "files/lib/wine/x86_64-windows"
|
||||
dist.mkdir(parents=True)
|
||||
(dist / "vulkan-1.dll").write_bytes(pe_image(0x8664))
|
||||
system32 = windows / "system32"
|
||||
(system32 / "vulkan-1.dll").symlink_to(os.path.relpath(dist / "vulkan-1.dll", system32))
|
||||
(system32 / "vulkan-1.dll.foreign-arch").write_bytes(pe_image(0xAA64))
|
||||
self.assertEqual([], MODULE["restore_compatible_system_dlls"](str(compat), str(proton)))
|
||||
self.assertTrue((system32 / "vulkan-1.dll").is_symlink())
|
||||
|
||||
def test_final_arm64ec_image_is_not_repaired_as_a_foreign_x64_dll(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PATCH = ROOT / "tools/gamescope/patches/0134-touch-click-press-once.patch"
|
||||
|
||||
|
||||
def added_source():
|
||||
return "\n".join(line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++"))
|
||||
|
||||
|
||||
def block(text, start):
|
||||
begin = text.index(start)
|
||||
return text[begin:text.index("\n}", begin) + 3]
|
||||
|
||||
|
||||
PREAMBLE = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#define WLSERVER_BUTTON_COUNT 7
|
||||
enum { HOVER = 0, LEFT = 1, RIGHT = 2, PASSTHROUGH = 4 };
|
||||
static const uint32_t BTN_L = 0x110, BTN_R = 0x111;
|
||||
'''
|
||||
|
||||
MAIN = r'''
|
||||
struct Seat {
|
||||
int pressed[2] = {0, 0};
|
||||
int sent[2] = {0, 0};
|
||||
int slot(uint32_t b) { return b == BTN_L ? 0 : 1; }
|
||||
void press(uint32_t b) { if (pressed[slot(b)]++ == 0) sent[slot(b)]++; }
|
||||
void release(uint32_t b) { if (pressed[slot(b)] > 0 && --pressed[slot(b)] == 0) sent[slot(b)]--; }
|
||||
};
|
||||
|
||||
static uint32_t button_of(int mode) { return mode == LEFT ? BTN_L : mode == RIGHT ? BTN_R : 0; }
|
||||
|
||||
struct Server {
|
||||
bool held[WLSERVER_BUTTON_COUNT] = {};
|
||||
Seat seat;
|
||||
void down(int mode) {
|
||||
uint32_t b = button_of(mode);
|
||||
if (touch_click_press(held, mode, b)) seat.press(b);
|
||||
}
|
||||
void up() {
|
||||
for (int i = 0; i < WLSERVER_BUTTON_COUNT; i++) {
|
||||
if (held[i] && button_of(i)) seat.release(button_of(i));
|
||||
held[i] = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
Server tap;
|
||||
tap.down(LEFT);
|
||||
assert(tap.seat.sent[0] == 1);
|
||||
tap.up();
|
||||
assert(tap.seat.sent[0] == 0 && tap.seat.pressed[0] == 0);
|
||||
|
||||
Server overlap;
|
||||
overlap.down(LEFT);
|
||||
overlap.down(LEFT);
|
||||
overlap.up();
|
||||
overlap.up();
|
||||
assert(overlap.seat.pressed[0] == 0 && overlap.seat.sent[0] == 0);
|
||||
overlap.down(LEFT);
|
||||
assert(overlap.seat.sent[0] == 1);
|
||||
overlap.up();
|
||||
assert(overlap.seat.sent[0] == 0);
|
||||
|
||||
Server three;
|
||||
for (int i = 0; i < 3; i++) three.down(LEFT);
|
||||
for (int i = 0; i < 3; i++) three.up();
|
||||
assert(three.seat.pressed[0] == 0);
|
||||
|
||||
Server modes;
|
||||
modes.down(LEFT);
|
||||
modes.down(RIGHT);
|
||||
modes.up();
|
||||
modes.up();
|
||||
assert(modes.seat.pressed[0] == 0 && modes.seat.pressed[1] == 0);
|
||||
|
||||
Server hover;
|
||||
hover.down(HOVER);
|
||||
hover.down(PASSTHROUGH);
|
||||
assert(hover.seat.pressed[0] == 0 && hover.seat.pressed[1] == 0);
|
||||
bool held[WLSERVER_BUTTON_COUNT] = {};
|
||||
assert(!touch_click_press(held, -1, BTN_L));
|
||||
assert(!touch_click_press(held, WLSERVER_BUTTON_COUNT, BTN_L));
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class GamescopeTouchClickTest(unittest.TestCase):
|
||||
def test_overlapping_touches_release_the_emulated_button(self):
|
||||
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("no C++ compiler")
|
||||
source = PREAMBLE + block(added_source(), "static bool touch_click_press") + MAIN
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp) / "touch_click.cpp"
|
||||
exe = Path(tmp) / "touch_click"
|
||||
src.write_text(source)
|
||||
subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,56 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
LAYER = ROOT / "tools/venus/layer"
|
||||
DEPS = ROOT / "build/layer-deps"
|
||||
|
||||
|
||||
def include(variable, default):
|
||||
return Path(os.environ.get(variable, str(default)))
|
||||
|
||||
|
||||
class MaliCompatLayerTest(unittest.TestCase):
|
||||
def test_dual_source_blending_against_a_mock_loader_and_driver(self):
|
||||
compiler = shutil.which(os.environ.get("CC", "cc"))
|
||||
if not compiler:
|
||||
self.fail("A C compiler is required for the Mali compatibility layer test")
|
||||
vulkan = include("MALI_COMPAT_VULKAN_INCLUDE", DEPS / "vulkan/include")
|
||||
spirv = include("MALI_COMPAT_SPIRV_INCLUDE", DEPS / "spirv/include")
|
||||
bcdec = include("MALI_COMPAT_BCDEC_INCLUDE", DEPS / "bcdec")
|
||||
missing = [str(path) for path in (vulkan / "vulkan/vk_layer.h", spirv / "spirv/unified1/spirv.h",
|
||||
bcdec / "bcdec.h") if not path.is_file()]
|
||||
if missing:
|
||||
message = "Vulkan 1.4, SPIR-V and bcdec headers are required: " + ", ".join(missing)
|
||||
if os.environ.get("CI"):
|
||||
self.fail(message)
|
||||
self.skipTest(message)
|
||||
with tempfile.TemporaryDirectory(prefix="droiddeck-mali-compat-") as tmp:
|
||||
program = Path(tmp) / "mali-compat-layer"
|
||||
built = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
|
||||
"-UNDEBUG", "-pthread", "-I", str(LAYER), "-I", str(vulkan), "-I", str(spirv),
|
||||
"-I", str(bcdec), str(Path(__file__).with_name("mali_compat_layer_test.c")),
|
||||
*sorted(str(source) for source in LAYER.glob("*.c")), "-o", str(program)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
ran = subprocess.run([str(program), tmp], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
self.assertIn("mali compat layer ok", ran.stdout)
|
||||
self.assertIn("emulating dualSrcBlend for mock", ran.stderr)
|
||||
validator = shutil.which("spirv-val")
|
||||
if not validator:
|
||||
return
|
||||
for name, environment in (("dual-1.0.spv", "vulkan1.0"), ("plain-1.0.spv", "vulkan1.0"),
|
||||
("stripped-1.0.spv", "vulkan1.0"), ("stripped-1.4.spv", "vulkan1.2")):
|
||||
checked = subprocess.run([validator, "--target-env", environment, str(Path(tmp) / name)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(checked.returncode, 0, name + ": " + checked.stdout + checked.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -160,15 +160,17 @@ class SessionPressureTest(unittest.TestCase):
|
||||
def run_policy(self, body):
|
||||
functions = '\n'.join(function_source(name) for name in (
|
||||
'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical',
|
||||
'bl_client_can_pageout', 'bl_client_pressure', 'bl_client_pressure_result',
|
||||
'bl_session_pressure', 'bl_zram_has_room', 'bl_watch_nap', 'bl_zram_pick', 'bl_tier_note', 'bl_tier_readback'))
|
||||
functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo'))
|
||||
functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure'))
|
||||
harness = '''
|
||||
set -u
|
||||
_bl_game=1 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_back=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() _bl_pids=(999)
|
||||
_bl_pressure_at=-1 _bl_packed=-1
|
||||
_bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_packed=-1
|
||||
rss=$((1536 * 1024)) swap=0 pushed=$((1024 * 1024)) alive="999 321 654" started=100 complete=1
|
||||
step() { :; }
|
||||
bl_game_focused() { [ "${focused:-1}" = 1 ]; }
|
||||
bl_proc_start() { _bl_start=; case " $alive " in *" $1 "*) _bl_start=$started; return 0 ;; esac; return 1; }
|
||||
nap() { echo "nap:$1"; }
|
||||
bl_session_others() { _bl_session=(321 654); }
|
||||
@@ -205,6 +207,53 @@ SECONDS=30; bl_session_pressure
|
||||
def test_no_game_does_not_compress_the_session(self):
|
||||
self.assertEqual([], self.run_policy('_bl_game=0; bl_session_pressure'))
|
||||
|
||||
def test_disabled_idle_compression_does_not_compress_the_session(self):
|
||||
self.assertEqual(['send:1:client'], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure'))
|
||||
|
||||
def test_disabled_idle_compression_signals_only_launcher_processes(self):
|
||||
sender = (function_source('bl_zram_send') + '\n' + function_source('bl_zram_finish')).replace('/tmp/.bl-zram', str(self.root / 'control'))
|
||||
self.assertEqual(['kill:-URG 999 998', 'mode:1'], self.run_policy('''
|
||||
_bl_pids=(999 998)
|
||||
kill() { echo "kill:$*"; }
|
||||
bl_zram_wait() { _bl_pageout_complete=1; }
|
||||
bl_zram_scan() { :; }
|
||||
''' + sender + '''
|
||||
BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure
|
||||
echo "mode:$(cat ''' + str(self.root / 'control') + ''')"
|
||||
'''))
|
||||
|
||||
def test_disabled_idle_compression_reclaims_only_the_launcher_before_focus(self):
|
||||
self.memory(available=1700)
|
||||
self.assertEqual(['send:1:client'], self.run_policy('''
|
||||
BL_ZRAM_IDLE=0 focused=0
|
||||
bl_client_pressure
|
||||
bl_session_pressure
|
||||
'''))
|
||||
|
||||
def test_disabled_idle_compression_respects_launcher_setting_and_threshold(self):
|
||||
self.memory(available=1700)
|
||||
self.assertEqual([], self.run_policy('BL_ZRAM_IDLE=0 BL_ZRAM_CLIENT=0; bl_client_pressure; bl_session_pressure'))
|
||||
self.memory(available=1900)
|
||||
self.assertEqual([], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure'))
|
||||
|
||||
def test_game_reclaim_requires_focus(self):
|
||||
self.assertEqual([], self.run_policy('focused=0; bl_session_pressure'))
|
||||
|
||||
def test_game_reclaim_runs_when_focus_is_unknown(self):
|
||||
launch = self.root / 'launch'
|
||||
(launch / 'agent').mkdir(parents=True)
|
||||
body = function_source('bl_game_focused') + f'\nBL_LAUNCH_DIR={launch} _bl_apps=7\n'
|
||||
self.assertEqual(['send:1:session'], self.run_policy(body + 'bl_session_pressure'))
|
||||
(launch / 'agent' / 'focus.json').write_text('{"focusedApp": 9}')
|
||||
self.assertEqual([], self.run_policy(body + 'bl_session_pressure'))
|
||||
self.assertEqual(['unfocused'], self.run_policy(body + 'bl_game_focused || echo unfocused'))
|
||||
(launch / 'agent' / 'focus.json').unlink()
|
||||
self.assertEqual(['unfocused'], self.run_policy(body + 'bl_game_focused || echo unfocused'))
|
||||
|
||||
def test_launcher_pressure_remains_available_on_larger_devices(self):
|
||||
self.memory(total=15360, available=1400)
|
||||
self.assertEqual(['send:1:client'], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure'))
|
||||
|
||||
def test_enough_available_memory_does_not_compress_even_with_stalls(self):
|
||||
self.memory(available=3072, psi='5.00')
|
||||
self.assertEqual([], self.run_policy('bl_session_pressure'))
|
||||
@@ -433,6 +482,7 @@ bl_zram_wait() {{
|
||||
[ "$1" != 123 ] || client_rss=$((client_rss - {reclaimed * 1024}))
|
||||
}}
|
||||
bl_tier_note() {{ :; }}
|
||||
bl_game_focused() {{ :; }}
|
||||
''' + source + f'''
|
||||
bl_memory_read
|
||||
_bl_fall={fall * 1024}
|
||||
|
||||
@@ -70,6 +70,7 @@ static void send_toplevel_configure(struct surface *s) { (void)s; resizes++; }
|
||||
#define stream_forget_all(...) ((void)0)
|
||||
#define pointer_delta(...) ((void)0)
|
||||
#define deliver_touch(m) ((void)0)
|
||||
#define deliver_pen(m) ((void)0)
|
||||
#define deliver_pointer(m) (pointers++)
|
||||
static void on_vsync(int64_t ns) { assert(ns > 0); ticks++; }
|
||||
static void vk_present_set_scale_mode(int mode, int alignment) {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
SOURCE = REPO / 'app/src/main/cpp/waylandcomp/src/compositor.c'
|
||||
PEN_STREAM = REPO / 'app/src/main/java/com/droiddeck/launcher/input/PenStream.kt'
|
||||
|
||||
|
||||
def function(source, signature):
|
||||
start = source.index(signature)
|
||||
return source[start:source.index('\n}\n', start) + 3]
|
||||
|
||||
|
||||
class PenEmulationTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = shutil.which(os.environ.get('CC', 'cc'))
|
||||
if compiler is None:
|
||||
raise unittest.SkipTest('A host C compiler is required')
|
||||
source = SOURCE.read_text()
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-pen-emulation-')
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
folder = Path(cls.temp.name)
|
||||
start = source.index('struct input_msg {')
|
||||
(folder / 'input_msg.inc').write_text(source[start:source.index('\n', start) + 1])
|
||||
start = source.index('#define PEN_IN ')
|
||||
end = source.index('static struct pen_state g_pen;\n', start)
|
||||
(folder / 'pen_state.inc').write_text(source[start:source.index('\n', end) + 1])
|
||||
(folder / 'pen.inc').write_text(''.join(function(source, signature) for signature in (
|
||||
'static int pointer_locked_for_cursor(void) {',
|
||||
'static void input_output_to_scene(double px, double py, double *x, double *y) {',
|
||||
'static int pen_buttons(int flags) {',
|
||||
'static void pen_release(int buttons) {',
|
||||
'static void deliver_pen(const struct input_msg *m) {')))
|
||||
start = source.index('#define for_each_pointer_of(client, sp)')
|
||||
(folder / 'pointer.inc').write_text(
|
||||
function(source, 'static struct seat_pointer *pointer_for(struct wl_client *client) {')
|
||||
+ source[start:source.index('#define for_each_keyboard_of', start)]
|
||||
+ ''.join(function(source, signature) for signature in (
|
||||
'static void pointer_focus(struct wl_resource *target, wl_fixed_t fx, wl_fixed_t fy) {',
|
||||
'static void pointer_input(double x, double y, int relative, uint32_t button, int pressed) {',
|
||||
'static void pointer_event(double x, double y, uint32_t button, int pressed) {',
|
||||
'static void pointer_button(uint32_t button, int pressed) {')))
|
||||
cls.binary = folder / 'pen-test'
|
||||
cls.pointer_binary = folder / 'pen-pointer-test'
|
||||
for harness, binary in (('pen_emulation_harness.c', cls.binary),
|
||||
('pen_pointer_harness.c', cls.pointer_binary)):
|
||||
subprocess.run([compiler, '-std=c11', '-Wall', '-Wextra', '-Werror', '-I', str(folder),
|
||||
str(REPO / 'tools/tests' / harness),
|
||||
'-o', str(binary)], check=True, capture_output=True, text=True)
|
||||
|
||||
def check_case(self, case, binary=None):
|
||||
result = subprocess.run([str(binary or self.binary), case], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
def test_flags_match_the_kotlin_pen_stream(self):
|
||||
native = dict(re.findall(r'^#define (PEN_[A-Z]+) \(1 << (\d+)\)$', SOURCE.read_text(), re.MULTILINE))
|
||||
kotlin = dict(re.findall(r'^\s*const val (PEN_[A-Z]+) = 1 shl (\d+)$', PEN_STREAM.read_text(), re.MULTILINE))
|
||||
self.assertEqual({'PEN_IN', 'PEN_TIP', 'PEN_RIGHT', 'PEN_MIDDLE'}, set(native))
|
||||
self.assertEqual(native, kotlin)
|
||||
|
||||
def test_hover_moves_the_pointer_in_scene_coordinates(self):
|
||||
self.check_case('hover')
|
||||
|
||||
def test_tip_presses_and_releases_the_left_button_once(self):
|
||||
self.check_case('tip')
|
||||
|
||||
def test_buttons_press_after_motion_and_before_releases(self):
|
||||
self.check_case('buttons')
|
||||
|
||||
def test_leaving_proximity_releases_every_button_without_motion(self):
|
||||
self.check_case('out')
|
||||
|
||||
def test_pointer_lock_blocks_motion_but_passes_buttons(self):
|
||||
self.check_case('lock')
|
||||
|
||||
def test_lost_records_still_release_held_buttons(self):
|
||||
self.check_case('lost')
|
||||
|
||||
def test_relative_origin_resets_when_proximity_starts_and_ends(self):
|
||||
self.check_case('raw')
|
||||
|
||||
def test_side_button_release_keeps_the_grab(self):
|
||||
self.check_case('side', self.pointer_binary)
|
||||
|
||||
def test_swapping_buttons_in_one_record_keeps_the_grab(self):
|
||||
self.check_case('swap', self.pointer_binary)
|
||||
|
||||
def test_a_button_release_from_another_pointer_keeps_the_grab(self):
|
||||
self.check_case('mouse', self.pointer_binary)
|
||||
|
||||
def test_a_window_closed_by_a_button_release_is_not_grabbed_again(self):
|
||||
self.check_case('gone', self.pointer_binary)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,39 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
RES = ROOT / "app/src/main/res"
|
||||
|
||||
|
||||
def strings(path):
|
||||
return {
|
||||
element.attrib["name"]: "".join(element.itertext())
|
||||
for element in ET.parse(path).getroot()
|
||||
if element.tag == "string" and element.get("translatable") != "false"
|
||||
}
|
||||
|
||||
|
||||
class PenLocalizationTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.required = [key for key in strings(RES / "values/strings.xml") if key.startswith("mode_pen")]
|
||||
language_source = (ROOT / "app/src/main/java/com/droiddeck/launcher/core/AppLanguage.kt").read_text(encoding="utf-8")
|
||||
tags = re.findall(r'"([a-zA-Z0-9-]+)"', re.search(r"val supported:.*?listOf\((.*?)\)", language_source, re.S).group(1))
|
||||
special = {"id": "in", "es-419": "b+es+419", "pt-BR": "pt"}
|
||||
cls.locales = {
|
||||
tag: strings(RES / f"values-{special.get(tag, tag.replace('-', '-r'))}/strings.xml")
|
||||
for tag in tags if tag != "en"
|
||||
}
|
||||
|
||||
def test_every_supported_language_translates_the_pen_settings(self):
|
||||
for locale, translated in self.locales.items():
|
||||
for key in self.required:
|
||||
with self.subTest(locale=locale, key=key):
|
||||
self.assertTrue(translated.get(key, "").strip(), "Missing translation would fall back to English")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,52 @@
|
||||
import unittest
|
||||
|
||||
from tools.release.update_catalog import ApiError, in_preview, iso_millis, keeps_test_build
|
||||
from tools.release.retire_test_builds import retired
|
||||
|
||||
MERGED = "2026-11-14T20:00:00Z"
|
||||
NOW = iso_millis(MERGED) + 3600_000
|
||||
|
||||
|
||||
class FakeSource:
|
||||
def __init__(self, status=None):
|
||||
self.status = status
|
||||
self.asked = []
|
||||
|
||||
def get(self, path):
|
||||
self.asked.append(path)
|
||||
if self.status is None:
|
||||
raise ApiError(404, "no")
|
||||
return {"status": self.status}
|
||||
|
||||
|
||||
def pull(state="closed", merged_at=MERGED, draft=False, base="main"):
|
||||
return {"state": state, "merged_at": merged_at, "merge_commit_sha": "a" * 40, "draft": draft, "base": {"ref": base}}
|
||||
|
||||
|
||||
class RetireTestBuildsTest(unittest.TestCase):
|
||||
def test_an_open_pr_keeps_its_build(self):
|
||||
self.assertFalse(retired(pull(state="open", merged_at=None), FakeSource("ahead"), "o/r", "b" * 40))
|
||||
|
||||
def test_a_closed_unmerged_pr_loses_it_at_once(self):
|
||||
self.assertTrue(retired(pull(merged_at=None), FakeSource(), "o/r", None))
|
||||
|
||||
def test_a_merged_pr_keeps_it_until_a_preview_carries_the_merge(self):
|
||||
self.assertFalse(in_preview(FakeSource("behind"), "o/r", pull(), "b" * 40, NOW))
|
||||
self.assertFalse(in_preview(FakeSource(), "o/r", pull(), "b" * 40, NOW))
|
||||
self.assertFalse(in_preview(FakeSource("ahead"), "o/r", pull(), None, NOW))
|
||||
self.assertTrue(in_preview(FakeSource("ahead"), "o/r", pull(), "b" * 40, NOW))
|
||||
self.assertTrue(in_preview(FakeSource("identical"), "o/r", pull(), "a" * 40, NOW))
|
||||
|
||||
def test_a_merge_no_preview_ever_carries_is_let_go_after_the_grace(self):
|
||||
self.assertTrue(in_preview(FakeSource(), "o/r", pull(), None, NOW + 4 * 86_400_000))
|
||||
|
||||
def test_the_catalog_lists_open_and_merged_main_prs(self):
|
||||
self.assertTrue(keeps_test_build(pull(state="open", merged_at=None)))
|
||||
self.assertTrue(keeps_test_build(pull()))
|
||||
self.assertFalse(keeps_test_build(pull(merged_at=None)))
|
||||
self.assertFalse(keeps_test_build(pull(draft=True)))
|
||||
self.assertFalse(keeps_test_build(pull(base="release")))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,8 +1,12 @@
|
||||
import base64
|
||||
import unittest
|
||||
|
||||
from tools.release.update_catalog import (
|
||||
Cache,
|
||||
asset_for_suffix,
|
||||
build_catalog,
|
||||
complete_apks,
|
||||
newest_complete,
|
||||
merged_pr,
|
||||
ci_description,
|
||||
parse_gradle,
|
||||
@@ -59,6 +63,64 @@ pubg com.tencent.ig -pubg
|
||||
self.assertEqual("DroidDeck-main-deadbee.apk", standard["name"])
|
||||
self.assertEqual("DroidDeck-main-deadbee-pubg.apk", pubg["name"])
|
||||
|
||||
def test_the_apk_named_for_the_build_commit_wins_over_a_previous_push(self):
|
||||
def apk(name, digit):
|
||||
return {"name": name, "size": 1, "digest": "sha256:" + digit * 64, "browser_download_url": "https://example/" + name}
|
||||
assets = [apk("DroidDeck-PR.7-1111111.apk", "a"), apk("DroidDeck-PR.7-2222222.apk", "b"),
|
||||
apk("DroidDeck-PR.7-1111111-pubg.apk", "c"), apk("DroidDeck-PR.7-2222222-pubg.apk", "d")]
|
||||
suffixes = ["", "-pubg"]
|
||||
self.assertEqual("DroidDeck-PR.7-2222222.apk", asset_for_suffix(assets, "", suffixes, "2222222abc")["name"])
|
||||
self.assertEqual("DroidDeck-PR.7-2222222-pubg.apk", asset_for_suffix(assets, "-pubg", suffixes, "2222222abc")["name"])
|
||||
self.assertEqual("DroidDeck-PR.7-1111111.apk", asset_for_suffix(assets, "", suffixes)["name"])
|
||||
|
||||
def test_a_preview_counts_only_with_every_package_and_digest(self):
|
||||
variants = [("com.droiddeck.launcher", ""), ("com.tencent.ig", "-pubg")]
|
||||
good = {"sha256": "a" * 64, "signerSha256": "b" * 64}
|
||||
self.assertTrue(complete_apks({"apks": {"com.droiddeck.launcher": good, "com.tencent.ig": good}}, variants))
|
||||
self.assertFalse(complete_apks({"apks": {"com.droiddeck.launcher": good}}, variants))
|
||||
self.assertFalse(complete_apks({"apks": {}}, variants))
|
||||
self.assertFalse(complete_apks({"apks": {"com.droiddeck.launcher": good, "com.tencent.ig": {"sha256": "x"}}}, variants))
|
||||
|
||||
def test_no_preview_is_offered_until_one_has_every_apk(self):
|
||||
variants = [("com.droiddeck.launcher", "")]
|
||||
good = {"com.droiddeck.launcher": {"sha256": "a" * 64, "signerSha256": "b" * 64}}
|
||||
uploading = {"commit": "2" * 40, "apks": {}}
|
||||
done = {"commit": "1" * 40, "apks": good}
|
||||
self.assertIsNone(newest_complete([uploading], variants))
|
||||
self.assertIsNone(newest_complete([], variants))
|
||||
self.assertIs(done, newest_complete([uploading, done], variants))
|
||||
|
||||
def test_the_catalog_publishes_no_preview_while_its_apks_are_uploading(self):
|
||||
commit = "c" * 40
|
||||
files = {
|
||||
"app/build.gradle": " versionCode 19\n versionName \"0.7.1\"\n",
|
||||
"tools/release/variants.txt": "standard com.droiddeck.launcher -\n",
|
||||
"keystore/release-signer.sha256": "b" * 64 + "\n",
|
||||
}
|
||||
|
||||
class FakeGitHub:
|
||||
def get_all(self, path, limit=1000):
|
||||
if "DroidDeck-CI/releases" in path:
|
||||
return [{
|
||||
"tag_name": f"main-{commit[:7]}", "prerelease": True, "assets": [],
|
||||
"published_at": "2026-11-14T10:00:00Z",
|
||||
"body": f"**Merged to main** - [PR #5](u): fix: x\n\nCommit: {commit}\nVersionCode: 19\n",
|
||||
}]
|
||||
return []
|
||||
|
||||
def get(self, path):
|
||||
for name, text in files.items():
|
||||
if f"/contents/{name.replace('/', '%2F')}?" in path:
|
||||
return {"encoding": "base64", "content": base64.b64encode(text.encode()).decode()}
|
||||
if "/commits/" in path:
|
||||
return {"author": {"login": "dev"}, "commit": {"committer": {"date": "2026-11-14T09:59:00Z"}}}
|
||||
raise AssertionError(path)
|
||||
|
||||
gh = FakeGitHub()
|
||||
catalog = build_catalog(gh, gh, "Droid-Deck/DroidDeck", "Droid-Deck/DroidDeck-CI")
|
||||
self.assertIsNone(catalog["preview"])
|
||||
self.assertEqual([commit], [p["commit"] for p in catalog["previews"]])
|
||||
|
||||
def test_ci_description(self):
|
||||
title, summary = ci_description(
|
||||
{
|
||||
|
||||
@@ -41,8 +41,37 @@ class WinComponentsTest(unittest.TestCase):
|
||||
def proton(self, arm=True):
|
||||
root = Path(self.tmp.name) / ("arm-proton" if arm else "x64-proton")
|
||||
(root / "files/lib/wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True)
|
||||
builtins = root / "files/lib/wine/aarch64-windows"
|
||||
builtins.mkdir(parents=True)
|
||||
(builtins / "wineboot.exe").write_bytes(self.program_image(0xAA64, ["ucrtbase.dll"]))
|
||||
(builtins / "steam.exe").write_bytes(self.program_image(0x8664, ["vulkan-1.dll"]))
|
||||
(builtins / "d3dx9_43.dll").write_bytes(self.program_image(0xAA64, ["d3dcompiler_43.dll"]))
|
||||
return root / "proton"
|
||||
|
||||
def program_image(self, machine, imports):
|
||||
image = bytearray(0x400)
|
||||
image[:2] = b"MZ"
|
||||
image[60:64] = (64).to_bytes(4, "little")
|
||||
image[64:68] = b"PE\0\0"
|
||||
image[68:70] = machine.to_bytes(2, "little")
|
||||
image[70:72] = (1).to_bytes(2, "little")
|
||||
image[84:86] = (240).to_bytes(2, "little")
|
||||
image[88:90] = (0x20B).to_bytes(2, "little")
|
||||
image[196:200] = (16).to_bytes(4, "little")
|
||||
image[208:212] = (0x1000).to_bytes(4, "little")
|
||||
image[212:216] = (20 * (len(imports) + 1)).to_bytes(4, "little")
|
||||
section = 88 + 240
|
||||
image[section + 8:section + 12] = (0x200).to_bytes(4, "little")
|
||||
image[section + 12:section + 16] = (0x1000).to_bytes(4, "little")
|
||||
image[section + 16:section + 20] = (0x200).to_bytes(4, "little")
|
||||
image[section + 20:section + 24] = (0x200).to_bytes(4, "little")
|
||||
name = 20 * (len(imports) + 1)
|
||||
for index, dll in enumerate(imports):
|
||||
image[0x200 + index * 20 + 12:0x200 + index * 20 + 16] = (0x1000 + name).to_bytes(4, "little")
|
||||
image[0x200 + name:0x200 + name + len(dll)] = dll.encode()
|
||||
name += len(dll) + 1
|
||||
return bytes(image)
|
||||
|
||||
def pe_image(self, machine):
|
||||
head = bytearray(64)
|
||||
head[:2] = b"MZ"
|
||||
@@ -92,17 +121,65 @@ class WinComponentsTest(unittest.TestCase):
|
||||
self.assertEqual(names, ["ucrtbase"])
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/ucrtbase.dll"), 0x8664)
|
||||
|
||||
def test_x64_visual_cpp_runtime_is_placed_in_arm64_system32(self):
|
||||
def test_x64_dlls_proton_programs_do_not_import_are_placed_in_arm64_system32(self):
|
||||
proton = self.proton()
|
||||
self.component("vc", ["msvcp140", "vcruntime140_1"], {
|
||||
"system32/msvcp140.dll": self.pe_image(0x8664),
|
||||
"system32/vcruntime140_1.dll": self.pe_image(0x8664),
|
||||
})
|
||||
names = ["concrt140", "d3dcompiler_43", "msvcp140", "vcruntime140_1", "vulkan-1"]
|
||||
self.component("vc", names, {"system32/%s.dll" % name: self.pe_image(0x8664) for name in names})
|
||||
self.pick("vc")
|
||||
names, _ = self.apply(proton)
|
||||
self.assertEqual(names, ["msvcp140", "vcruntime140_1"])
|
||||
placed, _ = self.apply(proton)
|
||||
self.assertEqual(placed, names)
|
||||
for name in names:
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / ("system32/%s.dll" % name)), 0x8664)
|
||||
|
||||
def test_x64_d3dx9_and_its_compiler_stay_placed_on_every_launch(self):
|
||||
proton = self.proton()
|
||||
self.component("d3dx9", ["d3dx9_43"], {"system32/d3dx9_43.dll": self.pe_image(0x8664)})
|
||||
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
|
||||
self.pick("d3dx9", "d3dcompiler")
|
||||
for _ in range(2):
|
||||
placed, _ = self.apply(proton)
|
||||
self.assertEqual(placed, ["d3dx9_43", "d3dcompiler_43"])
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0x8664)
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
|
||||
|
||||
def test_x64_compiler_alone_is_placed_although_a_builtin_dll_imports_it(self):
|
||||
proton = self.proton()
|
||||
self.component("d3dcompiler", ["d3dcompiler_43"], {"system32/d3dcompiler_43.dll": self.pe_image(0x8664)})
|
||||
self.pick("d3dcompiler")
|
||||
placed, _ = self.apply(proton)
|
||||
self.assertEqual(placed, ["d3dcompiler_43"])
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dcompiler_43.dll"), 0x8664)
|
||||
|
||||
def test_x64_proton_program_imports_do_not_make_a_dll_foreign(self):
|
||||
proton = self.proton()
|
||||
self.component("vk", ["vulkan-1"], {"system32/vulkan-1.dll": self.pe_image(0x8664)})
|
||||
self.pick("vk")
|
||||
placed, _ = self.apply(proton)
|
||||
self.assertEqual(placed, ["vulkan-1"])
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/vulkan-1.dll"), 0x8664)
|
||||
|
||||
def test_partly_installed_x64_visual_cpp_runtime_stays_x64(self):
|
||||
proton = self.proton()
|
||||
self.pfx.joinpath("system32").mkdir(parents=True)
|
||||
self.pfx.joinpath("system32/vcruntime140.dll").write_bytes(self.pe_image(0x8664))
|
||||
self.component("vc", ["msvcp140"], {"system32/msvcp140.dll": self.pe_image(0x8664)})
|
||||
self.pick("vc")
|
||||
placed, _ = self.apply(proton)
|
||||
self.assertEqual(placed, ["msvcp140"])
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/msvcp140.dll"), 0x8664)
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/vcruntime140_1.dll"), 0x8664)
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/vcruntime140.dll"), 0x8664)
|
||||
|
||||
def test_deselected_component_restores_the_saved_x64_dll(self):
|
||||
proton = self.proton()
|
||||
self.pfx.joinpath("system32").mkdir(parents=True)
|
||||
self.pfx.joinpath("system32/d3dx9_43.dll").write_bytes(self.pe_image(0x8664))
|
||||
self.component("d3dx9", ["d3dx9_43"], {"system32/d3dx9_43.dll": self.program_image(0xAA64, [])})
|
||||
self.pick("d3dx9")
|
||||
self.apply(proton)
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0xAA64)
|
||||
self.pick()
|
||||
self.apply(proton)
|
||||
self.assertEqual(MODULE["pe_machine"](self.pfx / "system32/d3dx9_43.dll"), 0x8664)
|
||||
|
||||
def test_compatible_copy_keeps_override_when_other_architecture_copy_is_skipped(self):
|
||||
proton = self.proton()
|
||||
|
||||
@@ -211,3 +211,184 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
with patch('subprocess.run', **outcome), patch('sys.stderr', new_callable=io.StringIO) as err:
|
||||
self.assertIsNone(xbox['register_classes']('/selected/proton', prefix, {}))
|
||||
self.assertIn('registration failed', err.getvalue())
|
||||
|
||||
|
||||
def pe_with_exports(names, forward=None, machine=0x8664, unnamed=0):
|
||||
"""A minimal x64 PE image whose export table names `names`; with `forward`, every export is forwarded there.
|
||||
`unnamed` adds that many ordinal-only exports after the named ones."""
|
||||
rva, raw = 0x1000, 0x200
|
||||
functions = rva + 40
|
||||
name_pointers = functions + 4 * (len(names) + unnamed)
|
||||
ordinals = name_pointers + 4 * len(names)
|
||||
strings = ordinals + 2 * len(names)
|
||||
blob = bytearray()
|
||||
name_rvas, forward_rvas = [], []
|
||||
for name in names:
|
||||
name_rvas.append(strings + len(blob))
|
||||
blob += name.encode() + b'\0'
|
||||
for name in names:
|
||||
forward_rvas.append(strings + len(blob))
|
||||
if forward:
|
||||
blob += ('%s.%s' % (forward, name)).encode() + b'\0'
|
||||
size = strings + len(blob) - rva
|
||||
directory = bytearray(40)
|
||||
directory[16:20] = (1).to_bytes(4, 'little')
|
||||
directory[20:24] = (len(names) + unnamed).to_bytes(4, 'little')
|
||||
directory[24:28] = len(names).to_bytes(4, 'little')
|
||||
directory[28:32] = functions.to_bytes(4, 'little')
|
||||
directory[32:36] = name_pointers.to_bytes(4, 'little')
|
||||
directory[36:40] = ordinals.to_bytes(4, 'little')
|
||||
section = bytearray(directory)
|
||||
for index in range(len(names)):
|
||||
section += (forward_rvas[index] if forward else 0x3000 + index).to_bytes(4, 'little')
|
||||
for index in range(unnamed):
|
||||
section += (0x4000 + index).to_bytes(4, 'little')
|
||||
for value in name_rvas:
|
||||
section += value.to_bytes(4, 'little')
|
||||
for index in range(len(names)):
|
||||
section += index.to_bytes(2, 'little')
|
||||
section += blob
|
||||
image = bytearray(raw)
|
||||
image[:2] = b'MZ'
|
||||
image[60:64] = (0x40).to_bytes(4, 'little')
|
||||
image[0x40:0x44] = b'PE\0\0'
|
||||
image[0x44:0x46] = machine.to_bytes(2, 'little')
|
||||
image[0x46:0x48] = (1).to_bytes(2, 'little')
|
||||
image[0x54:0x56] = (240).to_bytes(2, 'little')
|
||||
optional = 0x58
|
||||
image[optional:optional + 2] = (0x20B).to_bytes(2, 'little')
|
||||
image[optional + 108:optional + 112] = (16).to_bytes(4, 'little')
|
||||
image[optional + 112:optional + 116] = rva.to_bytes(4, 'little')
|
||||
image[optional + 116:optional + 120] = size.to_bytes(4, 'little')
|
||||
header = optional + 240
|
||||
image[header + 8:header + 12] = len(section).to_bytes(4, 'little')
|
||||
image[header + 12:header + 16] = rva.to_bytes(4, 'little')
|
||||
image[header + 16:header + 20] = len(section).to_bytes(4, 'little')
|
||||
image[header + 20:header + 24] = raw.to_bytes(4, 'little')
|
||||
return bytes(image + section)
|
||||
|
||||
|
||||
class PlayFabProxyTest(unittest.TestCase):
|
||||
SDK = pe_with_exports(xbox['PGS_EXPORTS'])
|
||||
NEWER_SDK = SDK + b'\0update'
|
||||
PROXY = pe_with_exports(xbox['PGS_EXPORTS'], forward='nexus_pgs_native')
|
||||
|
||||
def stage(self, root, proxy=PROXY):
|
||||
runtime = Path(root) / 'runtime'
|
||||
if proxy is not None:
|
||||
(runtime / 'compat').mkdir(parents=True, exist_ok=True)
|
||||
(runtime / 'compat/PlayFabGameSave.dll').write_bytes(proxy)
|
||||
with patch.dict(xbox['stage_playfab_proxy'].__globals__, PGS_PROXY=runtime / 'compat/PlayFabGameSave.dll'), \
|
||||
patch('sys.stderr', new_callable=io.StringIO):
|
||||
return xbox['stage_playfab_proxy'](Path(root) / 'game')
|
||||
|
||||
def game(self, root, data, sub='Bin'):
|
||||
folder = Path(root) / 'game' / sub
|
||||
folder.mkdir(parents=True)
|
||||
(folder / 'PlayFabGameSave.dll').write_bytes(data)
|
||||
return folder
|
||||
|
||||
def test_sdk_and_proxy_are_told_apart_by_their_exports(self):
|
||||
self.assertTrue(xbox['playfab_sdk'](self.SDK))
|
||||
self.assertFalse(xbox['playfab_proxy'](self.SDK))
|
||||
self.assertTrue(xbox['playfab_proxy'](self.PROXY))
|
||||
self.assertFalse(xbox['playfab_sdk'](self.PROXY))
|
||||
other = pe_with_exports(list(xbox['PGS_EXPORTS'][:-1]) + ['PFGameSaveFilesSomethingNew'])
|
||||
self.assertFalse(xbox['playfab_sdk'](other))
|
||||
self.assertFalse(xbox['playfab_sdk'](pe_with_exports(xbox['PGS_EXPORTS'], machine=0xAA64)))
|
||||
self.assertIsNone(xbox['pe_exports'](b'not a pe image'))
|
||||
self.assertEqual(xbox['pe_exports'](pe_with_exports(['A', 'B'], unnamed=1))[0], 3)
|
||||
self.assertFalse(xbox['playfab_sdk'](pe_with_exports(xbox['PGS_EXPORTS'], unnamed=1)))
|
||||
self.assertFalse(xbox['playfab_proxy'](pe_with_exports(xbox['PGS_EXPORTS'], forward='nexus_pgs_native', unnamed=1)))
|
||||
|
||||
def test_first_launch_keeps_the_sdk_and_puts_the_proxy_in_front(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = self.game(root, self.SDK)
|
||||
self.assertEqual(self.stage(root), 1)
|
||||
self.assertEqual((folder / 'nexus_pgs_native.dll').read_bytes(), self.SDK)
|
||||
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.PROXY)
|
||||
self.assertEqual(self.stage(root), 1)
|
||||
self.assertEqual((folder / 'nexus_pgs_native.dll').read_bytes(), self.SDK)
|
||||
self.assertEqual(sorted(path.name for path in folder.iterdir()), ['PlayFabGameSave.dll', 'nexus_pgs_native.dll'])
|
||||
|
||||
def test_a_game_update_replaces_the_kept_sdk(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = self.game(root, self.SDK)
|
||||
self.stage(root)
|
||||
(folder / 'PlayFabGameSave.dll').write_bytes(self.NEWER_SDK)
|
||||
self.assertEqual(self.stage(root), 1)
|
||||
self.assertEqual((folder / 'nexus_pgs_native.dll').read_bytes(), self.NEWER_SDK)
|
||||
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.PROXY)
|
||||
|
||||
def test_an_older_proxy_is_refreshed_only_while_its_sdk_is_there(self):
|
||||
older = self.PROXY + b'\0older'
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = self.game(root, older)
|
||||
(folder / 'nexus_pgs_native.dll').write_bytes(self.SDK)
|
||||
self.assertEqual(self.stage(root), 1)
|
||||
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.PROXY)
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = self.game(root, older)
|
||||
self.assertEqual(self.stage(root), 0)
|
||||
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), older)
|
||||
|
||||
def test_an_unknown_file_or_link_in_place_of_the_kept_sdk_is_never_overwritten(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = self.game(root, self.SDK)
|
||||
(folder / 'nexus_pgs_native.dll').write_bytes(b'MZ someone else')
|
||||
self.assertEqual(self.stage(root), 0)
|
||||
self.assertEqual((folder / 'nexus_pgs_native.dll').read_bytes(), b'MZ someone else')
|
||||
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.SDK)
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = self.game(root, self.SDK)
|
||||
target = Path(root) / 'elsewhere.dll'
|
||||
target.write_bytes(self.SDK)
|
||||
(folder / 'nexus_pgs_native.dll').symlink_to(target)
|
||||
self.assertEqual(self.stage(root), 0)
|
||||
self.assertTrue((folder / 'nexus_pgs_native.dll').is_symlink())
|
||||
self.assertEqual(target.read_bytes(), self.SDK)
|
||||
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.SDK)
|
||||
|
||||
def test_unknown_sdk_symlinks_and_a_runtime_without_the_proxy_are_left_alone(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
unknown = pe_with_exports(['PFGameSaveFilesInitialize'])
|
||||
folder = self.game(root, unknown)
|
||||
self.assertEqual(self.stage(root), 0)
|
||||
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), unknown)
|
||||
self.assertFalse((folder / 'nexus_pgs_native.dll').exists())
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = self.game(root, self.SDK)
|
||||
self.assertEqual(self.stage(root, proxy=None), 0)
|
||||
self.assertEqual((folder / 'PlayFabGameSave.dll').read_bytes(), self.SDK)
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
target = Path(root) / 'elsewhere.dll'
|
||||
target.write_bytes(self.SDK)
|
||||
folder = Path(root) / 'game'
|
||||
folder.mkdir()
|
||||
(folder / 'PlayFabGameSave.dll').symlink_to(target)
|
||||
self.assertEqual(self.stage(root), 0)
|
||||
self.assertEqual(target.read_bytes(), self.SDK)
|
||||
|
||||
def test_launch_stages_the_proxy_without_dll_overrides_and_survives_a_failure(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
root = Path(root)
|
||||
runtime = root / 'windows'
|
||||
runtime.mkdir()
|
||||
for name in xbox['DLLS']:
|
||||
(runtime / name).touch()
|
||||
store = {'find_store_game': lambda argv: (root, {'store': 'xbox', 'id': 'GAME'}),
|
||||
'ask': unittest.mock.Mock(return_value={'ok': True, 'socket': '/service', 'lease': 'lease-1',
|
||||
'exe': '/Game.exe'})}
|
||||
wine = unittest.mock.Mock(return_value=0)
|
||||
staged = []
|
||||
def failing(folder):
|
||||
raise RuntimeError('unreadable game folder')
|
||||
for stage in (lambda folder: staged.append(folder) or 1, failing):
|
||||
wine.reset_mock()
|
||||
with patch('runpy.run_path', return_value=store), patch('sys.stderr', new_callable=io.StringIO), \
|
||||
patch.dict(xbox['launch'].__globals__, RUNTIME=root, bridge=lambda path: (1, 'key', lambda: None),
|
||||
wine=wine, stage_playfab_proxy=stage):
|
||||
self.assertEqual(xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'],
|
||||
{'BL_LAUNCH_DIR': '/launch', 'WINEDLLOVERRIDES': 'd3d11=n'}), 0)
|
||||
self.assertEqual(wine.call_args.args[1]['WINEDLLOVERRIDES'], 'd3d11=n')
|
||||
self.assertEqual(staged, [root])
|
||||
@@ -65,6 +65,7 @@ int vkp_cardboard_active(void) { return 0; }
|
||||
void vkp_cardboard_begin_frame(void) {}
|
||||
VkImage vkp_cardboard_run(VkCommandBuffer c, VkImage s, int sw, int sh, int ow, int oh) { return s; }
|
||||
int vk_loader_open(const char *a, const char *b, const char *c) { assert(0); return -1; }
|
||||
void vk_loader_close(void) { assert(0); }
|
||||
void vk_loader_load_instance(VkInstance i) { assert(0); }
|
||||
void vk_loader_load_device(VkDevice d) { assert(0); }
|
||||
PFN_vkGetInstanceProcAddr vk_loader_gipa(void) { return NULL; }
|
||||
|
||||
+16
-2
@@ -17,6 +17,11 @@ helper (Chromium on ANGLE on Zink) hit this within seconds of fast Home
|
||||
shelf scrolling on a Pixel 10 Pro Fold and segfaulted in the driver's
|
||||
vkUpdateDescriptorSetWithTemplate. Rebuild all of the view's surfaces with
|
||||
init_sampler_view() instead. Still present in Mesa main.
|
||||
|
||||
zink_rebind_all_images() rebuilds a view once, through the rebind_count
|
||||
guard, so a second slot bound to the same view used to skip its descriptor
|
||||
refresh and keep the old VkImageView. Refresh every slot whose cached view
|
||||
no longer matches.
|
||||
---
|
||||
diff --git a/src/gallium/drivers/zink/zink_context.c b/src/gallium/drivers/zink/zink_context.c
|
||||
--- a/src/gallium/drivers/zink/zink_context.c
|
||||
@@ -32,13 +37,22 @@ diff --git a/src/gallium/drivers/zink/zink_context.c b/src/gallium/drivers/zink/
|
||||
ctx->invalidate_descriptor_state(ctx, i, ZINK_DESCRIPTOR_TYPE_SAMPLER_VIEW, j, 1);
|
||||
update_descriptor_state_sampler(ctx, i, j, res);
|
||||
}
|
||||
@@ -5457,8 +5457,7 @@ zink_rebind_all_images(struct zink_context *ctx)
|
||||
@@ -5455,10 +5455,15 @@ zink_rebind_all_images(struct zink_context *ctx)
|
||||
if (!sv || !sv->image_view || sv->base.texture->target == PIPE_BUFFER)
|
||||
continue;
|
||||
struct zink_resource *res = zink_resource(sv->base.texture);
|
||||
if (res->rebind_count != sv->rebind_count) {
|
||||
- if (res->rebind_count != sv->rebind_count) {
|
||||
+ bool rebuilt = res->rebind_count != sv->rebind_count;
|
||||
+ if (rebuilt) {
|
||||
sv->rebind_count = res->rebind_count;
|
||||
- struct pipe_surface tmpl = pipe_surface_templ_from_sampler_view(&sv->base, &res->base.b, sv->base.target);
|
||||
- sv->image_view = zink_get_surface(ctx, &tmpl, &sv->ivci);
|
||||
+ init_sampler_view(ctx, sv);
|
||||
+ }
|
||||
+ /* a view bound in several slots is rebuilt once; every slot still needs the new VkImageView */
|
||||
+ enum pipe_format format;
|
||||
+ struct zink_surface *surface = get_imageview_for_binding(ctx, i, ZINK_DESCRIPTOR_TYPE_SAMPLER_VIEW, j, &format);
|
||||
+ if (rebuilt || ctx->di.textures[i][j].imageView != surface->image_view) {
|
||||
ctx->invalidate_descriptor_state(ctx, i, ZINK_DESCRIPTOR_TYPE_SAMPLER_VIEW, j, 1);
|
||||
update_descriptor_state_sampler(ctx, i, j, res);
|
||||
}
|
||||
@@ -212,6 +212,8 @@ uint32_t physical_device_gaps(struct instance *inst, VkPhysicalDevice physical_d
|
||||
gaps |= GAP_ROBUSTNESS2;
|
||||
if (!features.features.multiDrawIndirect)
|
||||
gaps |= GAP_MULTI_DRAW;
|
||||
if (!features.features.dualSrcBlend)
|
||||
gaps |= GAP_DUAL_SRC_BLEND;
|
||||
if (!has_extension(inst, physical_device, VK_EXT_DEPTH_CLIP_ENABLE_EXTENSION_NAME))
|
||||
gaps |= GAP_DEPTH_CLIP;
|
||||
/* No robustness2 at all: the extension is offered with robustBufferAccess2 (as robustBufferAccess)
|
||||
@@ -284,6 +286,8 @@ static void report_features(VkPhysicalDeviceFeatures *features, uint32_t gaps)
|
||||
features->textureCompressionBC = VK_TRUE;
|
||||
if (gaps & GAP_MULTI_DRAW)
|
||||
features->multiDrawIndirect = VK_TRUE;
|
||||
if (gaps & GAP_DUAL_SRC_BLEND)
|
||||
features->dualSrcBlend = VK_TRUE;
|
||||
}
|
||||
|
||||
/* Which made-up features the application asked for, and off with them before the driver sees them. */
|
||||
@@ -314,6 +318,10 @@ static uint32_t take_features(VkPhysicalDeviceFeatures *features, uint32_t gaps)
|
||||
requested |= GAP_MULTI_DRAW;
|
||||
features->multiDrawIndirect = VK_FALSE;
|
||||
}
|
||||
if ((gaps & GAP_DUAL_SRC_BLEND) && features->dualSrcBlend) {
|
||||
requested |= GAP_DUAL_SRC_BLEND;
|
||||
features->dualSrcBlend = VK_FALSE;
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
|
||||
@@ -323,6 +331,8 @@ static void report_limits(VkPhysicalDeviceLimits *limits, uint32_t gaps)
|
||||
limits->maxViewports = 16;
|
||||
if ((gaps & GAP_MULTI_DRAW) && limits->maxDrawIndirectCount < (1u << 30))
|
||||
limits->maxDrawIndirectCount = 1u << 30;
|
||||
if ((gaps & GAP_DUAL_SRC_BLEND) && !limits->maxFragmentDualSrcAttachments)
|
||||
limits->maxFragmentDualSrcAttachments = 1;
|
||||
if (gaps & GAPS_SHADER) {
|
||||
limits->maxClipDistances = 8;
|
||||
limits->maxCullDistances = 8;
|
||||
@@ -616,7 +626,7 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev
|
||||
pthread_mutex_unlock(&global_lock);
|
||||
|
||||
if (requested) {
|
||||
layer_log("emulating%s%s%s%s%s%s%s%s%s for %s", (requested & GAP_FILL_MODE) ? " fillModeNonSolid" : "",
|
||||
layer_log("emulating%s%s%s%s%s%s%s%s%s%s for %s", (requested & GAP_FILL_MODE) ? " fillModeNonSolid" : "",
|
||||
(requested & GAP_MULTI_VIEWPORT) ? " multiViewport" : "",
|
||||
(requested & GAP_CLIP_DISTANCE) ? " shaderClipDistance" : "",
|
||||
(requested & GAP_CULL_DISTANCE) ? " shaderCullDistance" : "",
|
||||
@@ -624,7 +634,8 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev
|
||||
(requested & GAP_BC) ? " textureCompressionBC" : "",
|
||||
(requested & GAP_MULTI_DRAW) ? " multiDrawIndirect" : "",
|
||||
(requested & GAP_DEPTH_CLIP) ? " depthClipEnable" : "",
|
||||
(requested & GAP_NULL_DESCRIPTOR) ? " nullDescriptor" : "", properties.deviceName);
|
||||
(requested & GAP_NULL_DESCRIPTOR) ? " nullDescriptor" : "",
|
||||
(requested & GAP_DUAL_SRC_BLEND) ? " dualSrcBlend" : "", properties.deviceName);
|
||||
}
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
@@ -667,8 +678,8 @@ struct hook {
|
||||
#define HOOK_ALIAS(name, alias, gaps) {"vk" #alias, (PFN_vkVoidFunction)name, gaps}
|
||||
|
||||
static const struct hook device_hooks[] = {
|
||||
HOOK(CreateShaderModule, GAPS_SHADER),
|
||||
HOOK(DestroyShaderModule, GAPS_SHADER),
|
||||
HOOK(CreateShaderModule, GAPS_SHADER | GAP_DUAL_SRC_BLEND),
|
||||
HOOK(DestroyShaderModule, GAPS_SHADER | GAP_DUAL_SRC_BLEND),
|
||||
HOOK(CreateGraphicsPipelines, GAPS_PIPELINE),
|
||||
HOOK(CmdSetViewport, GAP_MULTI_VIEWPORT),
|
||||
HOOK(CmdSetScissor, GAP_MULTI_VIEWPORT),
|
||||
@@ -676,6 +687,7 @@ static const struct hook device_hooks[] = {
|
||||
HOOK_ALIAS(CmdSetViewportWithCount, CmdSetViewportWithCountEXT, GAP_MULTI_VIEWPORT),
|
||||
HOOK(CmdSetScissorWithCount, GAP_MULTI_VIEWPORT),
|
||||
HOOK_ALIAS(CmdSetScissorWithCount, CmdSetScissorWithCountEXT, GAP_MULTI_VIEWPORT),
|
||||
HOOK(CmdSetColorBlendEquationEXT, GAP_DUAL_SRC_BLEND),
|
||||
HOOK(CreateImage, GAP_BC),
|
||||
HOOK(DestroyImage, GAP_BC),
|
||||
HOOK(CreateImageView, GAP_BC),
|
||||
|
||||
@@ -29,10 +29,11 @@ enum gap {
|
||||
GAP_MULTI_DRAW = 1u << 6, /* multiDrawIndirect: indirect draws looped one by one */
|
||||
GAP_DEPTH_CLIP = 1u << 7, /* VK_EXT_depth_clip_enable: depthClipEnable off becomes depth clamp */
|
||||
GAP_NULL_DESCRIPTOR = 1u << 8, /* VK_EXT_robustness2 missing entirely: nullDescriptor stand-ins */
|
||||
GAP_DUAL_SRC_BLEND = 1u << 9,
|
||||
};
|
||||
|
||||
#define GAPS_SHADER (GAP_CLIP_DISTANCE | GAP_CULL_DISTANCE)
|
||||
#define GAPS_PIPELINE (GAP_FILL_MODE | GAP_MULTI_VIEWPORT | GAPS_SHADER | GAP_DEPTH_CLIP)
|
||||
#define GAPS_PIPELINE (GAP_FILL_MODE | GAP_MULTI_VIEWPORT | GAPS_SHADER | GAP_DEPTH_CLIP | GAP_DUAL_SRC_BLEND)
|
||||
|
||||
void layer_log(const char *format, ...) __attribute__((format(printf, 1, 2)));
|
||||
|
||||
@@ -135,7 +136,8 @@ struct instance {
|
||||
X(UpdateDescriptorSetWithTemplate) \
|
||||
X(CmdPushDescriptorSetWithTemplate) \
|
||||
X(CmdBindVertexBuffers) \
|
||||
X(CmdBindVertexBuffers2)
|
||||
X(CmdBindVertexBuffers2) \
|
||||
X(CmdSetColorBlendEquationEXT)
|
||||
|
||||
struct staging_block;
|
||||
|
||||
@@ -183,6 +185,8 @@ struct spirv_code {
|
||||
bool spirv_uses_distances(const uint32_t *words, size_t count);
|
||||
/* The module with clip and cull distances taken out; false when it cannot be rewritten. */
|
||||
bool spirv_strip_distances(const uint32_t *words, size_t count, struct spirv_code *out);
|
||||
bool spirv_uses_dual_source(const uint32_t *words, size_t count);
|
||||
bool spirv_strip_dual_source(const uint32_t *words, size_t count, struct spirv_code *out);
|
||||
|
||||
enum clip_role { CLIP_STRIP, CLIP_PRODUCER, CLIP_CONSUMER };
|
||||
|
||||
@@ -216,6 +220,8 @@ VKAPI_ATTR void VKAPI_CALL CmdSetScissor(VkCommandBuffer cmd, uint32_t first, ui
|
||||
VKAPI_ATTR void VKAPI_CALL CmdSetViewportWithCount(VkCommandBuffer cmd, uint32_t count,
|
||||
const VkViewport *viewports);
|
||||
VKAPI_ATTR void VKAPI_CALL CmdSetScissorWithCount(VkCommandBuffer cmd, uint32_t count, const VkRect2D *scissors);
|
||||
VKAPI_ATTR void VKAPI_CALL CmdSetColorBlendEquationEXT(VkCommandBuffer cmd, uint32_t first, uint32_t count,
|
||||
const VkColorBlendEquationEXT *equations);
|
||||
|
||||
/* bc.c */
|
||||
VkFormat bc_substitute(VkFormat format);
|
||||
|
||||
+115
-13
@@ -12,27 +12,46 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateShaderModule(VkDevice device, const VkShade
|
||||
const VkAllocationCallbacks *allocator, VkShaderModule *module)
|
||||
{
|
||||
struct device *dev = device_from_handle(device);
|
||||
VkShaderModuleCreateInfo copy = *info;
|
||||
size_t count = info->codeSize / sizeof(uint32_t);
|
||||
if (!spirv_uses_distances(info->pCode, count))
|
||||
return dev->CreateShaderModule(device, info, allocator, module);
|
||||
struct spirv_code single = {0};
|
||||
if ((dev->emulated & GAP_DUAL_SRC_BLEND) && spirv_uses_dual_source(info->pCode, count)) {
|
||||
if (spirv_strip_dual_source(info->pCode, count, &single)) {
|
||||
copy.pCode = single.words;
|
||||
copy.codeSize = single.count * sizeof(uint32_t);
|
||||
count = single.count;
|
||||
} else {
|
||||
layer_log("could not take the second blend source out of a shader module");
|
||||
}
|
||||
}
|
||||
if (!(dev->emulated & GAPS_SHADER) || !spirv_uses_distances(copy.pCode, count)) {
|
||||
VkResult result = dev->CreateShaderModule(device, ©, allocator, module);
|
||||
free(single.words);
|
||||
return result;
|
||||
}
|
||||
|
||||
struct spirv_code stripped;
|
||||
if (!spirv_strip_distances(info->pCode, count, &stripped)) {
|
||||
if (!spirv_strip_distances(copy.pCode, count, &stripped)) {
|
||||
layer_log("could not take the clip and cull distances out of a shader module");
|
||||
return dev->CreateShaderModule(device, info, allocator, module);
|
||||
VkResult result = dev->CreateShaderModule(device, ©, allocator, module);
|
||||
free(single.words);
|
||||
return result;
|
||||
}
|
||||
VkShaderModuleCreateInfo copy = *info;
|
||||
struct spirv_code *original = malloc(sizeof(*original));
|
||||
original->count = count;
|
||||
original->words = malloc(copy.codeSize);
|
||||
memcpy(original->words, copy.pCode, copy.codeSize);
|
||||
free(single.words);
|
||||
copy.pCode = stripped.words;
|
||||
copy.codeSize = stripped.count * sizeof(uint32_t);
|
||||
VkResult result = dev->CreateShaderModule(device, ©, allocator, module);
|
||||
free(stripped.words);
|
||||
if (result != VK_SUCCESS)
|
||||
if (result != VK_SUCCESS) {
|
||||
free(original->words);
|
||||
free(original);
|
||||
return result;
|
||||
}
|
||||
|
||||
struct spirv_code *original = malloc(sizeof(*original));
|
||||
original->count = count;
|
||||
original->words = malloc(info->codeSize);
|
||||
memcpy(original->words, info->pCode, info->codeSize);
|
||||
pthread_mutex_lock(&dev->lock);
|
||||
map_put(&dev->shader_modules, HANDLE(*module), original);
|
||||
pthread_mutex_unlock(&dev->lock);
|
||||
@@ -87,12 +106,15 @@ static void find_stage_code(struct device *dev, const VkPipelineShaderStageCreat
|
||||
|
||||
struct pipeline_rewrite {
|
||||
VkPipelineRasterizationStateCreateInfo rasterization;
|
||||
VkPipelineColorBlendStateCreateInfo blend;
|
||||
VkPipelineColorBlendAttachmentState *attachments;
|
||||
/* VK_EXT_depth_clip_enable's state, taken out of the application's chain for the call. */
|
||||
VkBaseOutStructure *clip_prev, *clip_node;
|
||||
VkPipelineViewportStateCreateInfo viewport;
|
||||
VkPipelineShaderStageCreateInfo stages[MAX_STAGES];
|
||||
VkShaderModuleCreateInfo modules[MAX_STAGES];
|
||||
struct spirv_code code[MAX_STAGES];
|
||||
struct spirv_code single[MAX_STAGES];
|
||||
VkShaderModule temporary[MAX_STAGES];
|
||||
/* Rewritten where they are, when they are not first in their stage's chain. */
|
||||
VkShaderModuleCreateInfo *in_place[MAX_STAGES];
|
||||
@@ -154,8 +176,17 @@ static void rewrite_shaders(struct device *dev, VkGraphicsPipelineCreateInfo *in
|
||||
bool any = false;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
find_stage_code(dev, &info->pStages[i], &code[i]);
|
||||
uses[i] = code[i].words && spirv_uses_distances(code[i].words, code[i].count);
|
||||
any |= uses[i];
|
||||
if ((dev->emulated & GAP_DUAL_SRC_BLEND) && code[i].inline_info &&
|
||||
spirv_uses_dual_source(code[i].words, code[i].count)) {
|
||||
if (spirv_strip_dual_source(code[i].words, code[i].count, &rw->single[i])) {
|
||||
code[i].words = rw->single[i].words;
|
||||
code[i].count = rw->single[i].count;
|
||||
} else {
|
||||
layer_log("could not take the second blend source out of a pipeline's shader");
|
||||
}
|
||||
}
|
||||
uses[i] = (dev->emulated & GAPS_SHADER) && code[i].words && spirv_uses_distances(code[i].words, code[i].count);
|
||||
any |= uses[i] || rw->single[i].words;
|
||||
}
|
||||
if (!any)
|
||||
return;
|
||||
@@ -196,11 +227,63 @@ static void rewrite_shaders(struct device *dev, VkGraphicsPipelineCreateInfo *in
|
||||
!spirv_strip_distances(code[i].words, code[i].count, &rw->code[i])) {
|
||||
layer_log("could not take the clip and cull distances out of a pipeline's shader");
|
||||
}
|
||||
if (!rw->code[i].words && rw->single[i].words) {
|
||||
rw->code[i] = rw->single[i];
|
||||
rw->single[i] = (struct spirv_code){0};
|
||||
}
|
||||
if (rw->code[i].words)
|
||||
use_code(dev, info, rw, &code[i], i);
|
||||
}
|
||||
}
|
||||
|
||||
static bool single_source(VkBlendFactor *factor)
|
||||
{
|
||||
switch (*factor) {
|
||||
case VK_BLEND_FACTOR_SRC1_COLOR:
|
||||
case VK_BLEND_FACTOR_SRC1_ALPHA:
|
||||
*factor = VK_BLEND_FACTOR_SRC_ALPHA;
|
||||
return true;
|
||||
case VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR:
|
||||
case VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA:
|
||||
*factor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static bool single_source_equation(VkBlendFactor *src_color, VkBlendFactor *dst_color, VkBlendFactor *src_alpha,
|
||||
VkBlendFactor *dst_alpha)
|
||||
{
|
||||
bool changed = single_source(src_color);
|
||||
changed |= single_source(dst_color);
|
||||
changed |= single_source(src_alpha);
|
||||
changed |= single_source(dst_alpha);
|
||||
return changed;
|
||||
}
|
||||
|
||||
static void rewrite_blend(const VkGraphicsPipelineCreateInfo *info, struct pipeline_rewrite *rw)
|
||||
{
|
||||
const VkPipelineColorBlendStateCreateInfo *blend = info->pColorBlendState;
|
||||
if (!blend || !blend->pAttachments || !blend->attachmentCount)
|
||||
return;
|
||||
rw->attachments = malloc(blend->attachmentCount * sizeof(*rw->attachments));
|
||||
memcpy(rw->attachments, blend->pAttachments, blend->attachmentCount * sizeof(*rw->attachments));
|
||||
bool changed = false;
|
||||
for (uint32_t i = 0; i < blend->attachmentCount; i++) {
|
||||
VkPipelineColorBlendAttachmentState *a = &rw->attachments[i];
|
||||
changed |= single_source_equation(&a->srcColorBlendFactor, &a->dstColorBlendFactor, &a->srcAlphaBlendFactor,
|
||||
&a->dstAlphaBlendFactor);
|
||||
}
|
||||
if (!changed) {
|
||||
free(rw->attachments);
|
||||
rw->attachments = NULL;
|
||||
return;
|
||||
}
|
||||
rw->blend = *blend;
|
||||
rw->blend.pAttachments = rw->attachments;
|
||||
}
|
||||
|
||||
static void rewrite_pipeline(struct device *dev, VkGraphicsPipelineCreateInfo *info, struct pipeline_rewrite *rw)
|
||||
{
|
||||
if ((dev->emulated & GAP_FILL_MODE) && info->pRasterizationState &&
|
||||
@@ -241,7 +324,12 @@ static void rewrite_pipeline(struct device *dev, VkGraphicsPipelineCreateInfo *i
|
||||
rw->viewport.scissorCount = 1;
|
||||
info->pViewportState = &rw->viewport;
|
||||
}
|
||||
if (dev->emulated & GAPS_SHADER)
|
||||
if (dev->emulated & GAP_DUAL_SRC_BLEND) {
|
||||
rewrite_blend(info, rw);
|
||||
if (rw->attachments)
|
||||
info->pColorBlendState = &rw->blend;
|
||||
}
|
||||
if (dev->emulated & (GAPS_SHADER | GAP_DUAL_SRC_BLEND))
|
||||
rewrite_shaders(dev, info, rw);
|
||||
}
|
||||
|
||||
@@ -257,7 +345,9 @@ static void undo_rewrite(struct device *dev, struct pipeline_rewrite *rw)
|
||||
if (rw->temporary[i] != VK_NULL_HANDLE)
|
||||
dev->DestroyShaderModule(dev->handle, rw->temporary[i], NULL);
|
||||
free(rw->code[i].words);
|
||||
free(rw->single[i].words);
|
||||
}
|
||||
free(rw->attachments);
|
||||
}
|
||||
|
||||
VKAPI_ATTR VkResult VKAPI_CALL CreateGraphicsPipelines(VkDevice device, VkPipelineCache cache, uint32_t count,
|
||||
@@ -306,3 +396,15 @@ VKAPI_ATTR void VKAPI_CALL CmdSetScissorWithCount(VkCommandBuffer cmd, uint32_t
|
||||
struct device *dev = device_from_handle(cmd);
|
||||
dev->CmdSetScissorWithCount(cmd, count > 1 ? 1 : count, scissors);
|
||||
}
|
||||
|
||||
VKAPI_ATTR void VKAPI_CALL CmdSetColorBlendEquationEXT(VkCommandBuffer cmd, uint32_t first, uint32_t count,
|
||||
const VkColorBlendEquationEXT *equations)
|
||||
{
|
||||
struct device *dev = device_from_handle(cmd);
|
||||
for (uint32_t i = 0; i < count; i++) {
|
||||
VkColorBlendEquationEXT equation = equations[i];
|
||||
single_source_equation(&equation.srcColorBlendFactor, &equation.dstColorBlendFactor,
|
||||
&equation.srcAlphaBlendFactor, &equation.dstAlphaBlendFactor);
|
||||
dev->CmdSetColorBlendEquationEXT(cmd, first + i, 1, &equation);
|
||||
}
|
||||
}
|
||||
@@ -416,19 +416,19 @@ static void add_to_interface(struct module *m, uint32_t id)
|
||||
}
|
||||
|
||||
/* A standalone distance variable becomes Private, and its decorations go. */
|
||||
static void privatize(struct module *m, const struct distance_var *var)
|
||||
static void privatize(struct module *m, uint32_t id)
|
||||
{
|
||||
size_t d = definition(m, var->id);
|
||||
size_t d = definition(m, id);
|
||||
uint32_t storage, pointee;
|
||||
pointer_parts(m, m->w[d + 1], &storage, &pointee);
|
||||
m->w[d + 1] = pointer_type(m, SpvStorageClassPrivate, pointee);
|
||||
m->w[d + 3] = SpvStorageClassPrivate;
|
||||
mark_private(m, var->id);
|
||||
mark_private(m, id);
|
||||
/* Before SPIR-V 1.4 an entry point lists only its inputs and outputs. */
|
||||
if (m->version < VERSION_1_4)
|
||||
m->interface_remove[var->id] = 1;
|
||||
m->interface_remove[id] = 1;
|
||||
for (size_t i = 5; i < m->first_declaration; i += LENGTH(m->w[i])) {
|
||||
if (OPCODE(m->w[i]) == SpvOpDecorate && m->w[i + 1] == var->id)
|
||||
if (OPCODE(m->w[i]) == SpvOpDecorate && m->w[i + 1] == id)
|
||||
edit(m, i, INSTEAD);
|
||||
}
|
||||
}
|
||||
@@ -667,7 +667,7 @@ static void strip(struct module *m, const struct analysis *a, uint32_t keep)
|
||||
{
|
||||
for (uint32_t i = 0; i < a->var_count; i++) {
|
||||
if (a->vars[i].id != keep)
|
||||
privatize(m, &a->vars[i]);
|
||||
privatize(m, a->vars[i].id);
|
||||
}
|
||||
struct stand_in stand_ins[16];
|
||||
uint32_t count = make_stand_ins(m, a, stand_ins, 16);
|
||||
@@ -688,6 +688,50 @@ bool spirv_strip_distances(const uint32_t *words, size_t count, struct spirv_cod
|
||||
return done;
|
||||
}
|
||||
|
||||
static bool is_second_source(const uint32_t *w)
|
||||
{
|
||||
return OPCODE(w[0]) == SpvOpDecorate && LENGTH(w[0]) == 4 && w[2] == SpvDecorationIndex && w[3] == 1;
|
||||
}
|
||||
|
||||
bool spirv_uses_dual_source(const uint32_t *words, size_t count)
|
||||
{
|
||||
if (count <= 5 || words[0] != SpvMagicNumber)
|
||||
return false;
|
||||
for (size_t i = 5; i < count && LENGTH(words[i]) && i + LENGTH(words[i]) <= count; i += LENGTH(words[i])) {
|
||||
if (is_declaration(OPCODE(words[i])))
|
||||
break;
|
||||
if (is_second_source(&words[i]))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool spirv_strip_dual_source(const uint32_t *words, size_t count, struct spirv_code *out)
|
||||
{
|
||||
struct module m;
|
||||
if (!load(&m, words, count))
|
||||
return false;
|
||||
uint32_t outputs[8];
|
||||
uint32_t output_count = 0;
|
||||
for (size_t i = 5; i < m.first_declaration; i += LENGTH(m.w[i])) {
|
||||
if (!is_second_source(&m.w[i]))
|
||||
continue;
|
||||
size_t d = definition(&m, m.w[i + 1]);
|
||||
uint32_t storage, pointee;
|
||||
if (output_count == 8 || !d || OPCODE(m.w[d]) != SpvOpVariable ||
|
||||
!pointer_parts(&m, m.w[d + 1], &storage, &pointee) || storage != SpvStorageClassOutput)
|
||||
m.failed = true;
|
||||
else
|
||||
outputs[output_count++] = m.w[i + 1];
|
||||
}
|
||||
for (uint32_t i = 0; i < output_count && !m.failed; i++)
|
||||
privatize(&m, outputs[i]);
|
||||
retarget_accesses(&m, NULL, 0);
|
||||
bool done = finish(&m, out);
|
||||
unload(&m);
|
||||
return done;
|
||||
}
|
||||
|
||||
static const struct distance_var *clip_output(const struct module *m, const struct analysis *a, uint32_t *length)
|
||||
{
|
||||
for (uint32_t i = 0; i < a->var_count; i++) {
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
VENUS_REPO=The412Banner/droiddeck-nonadreno-drivers
|
||||
VENUS_TAG=venus-proto13-e24ed8ab
|
||||
VENUS_SHA256=25f236bbc32c8490fc61c20a6016b0bea4a8c3267a69de6b91496da2afe6bc04
|
||||
VENUS_REPO=Droid-Deck/DroidDeck-Components
|
||||
VENUS_TAG=venus-dualsrc-463ba9ef
|
||||
VENUS_SHA256=ace6f4c3e62db0c7487859d8cebdcdd83656272951f84c00471fafc364ae30af
|
||||
@@ -41,6 +41,12 @@ app's credential socket (`NEXUS_CREDENTIAL_ERROR_V1 socket-refused`, `-denied`,
|
||||
uses a keyed loopback port the app also listens on; some devices refuse the abstract socket
|
||||
from inside PRoot. The key is passed in the backend's environment only.
|
||||
|
||||
`droiddeck-licensing-device-ticket.patch` sends a delegation-compact device ticket to content
|
||||
licensing and Store license tokens in the licensing wire form (`t=` or a bare compact JWE), as
|
||||
user tickets already are. A plain compact device ticket is sent unchanged. The rule follows
|
||||
[@domsvoboda](https://github.com/domsvoboda)'s nexus-backend commit `27c335e` and
|
||||
xodus-gaming/xodus#238.
|
||||
|
||||
`droiddeck-credential-diagnostics.patch` names the step behind a `credential-io` failure: the
|
||||
session lock (`lock-dir-owner`, `lock-file-mode`, `lock-flock-<reason>`, ...), a socket or loopback
|
||||
exchange that broke after connecting (`socket-exchange-<reason>`), a malformed host reply, or a
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
diff --git a/crates/xodus-cli/src/license.rs b/crates/xodus-cli/src/license.rs
|
||||
index 4518c22..5a12753 100644
|
||||
--- a/crates/xodus-cli/src/license.rs
|
||||
+++ b/crates/xodus-cli/src/license.rs
|
||||
@@ -58,6 +58,7 @@ pub async fn get_license(
|
||||
let Token::Compact(ms_device_token) = ms_device_token else {
|
||||
return Err("Unsupported token".to_string());
|
||||
};
|
||||
+ let ms_device_token = xodus::models::secrets::licensing_device_ticket(ms_device_token);
|
||||
|
||||
let user_token: Token = match user_token {
|
||||
ExchangeUserTokenOutcome::Fault(_) => {
|
||||
diff --git a/crates/xodus-service/src/store_license.rs b/crates/xodus-service/src/store_license.rs
|
||||
index e6b4c58..abede2e 100644
|
||||
--- a/crates/xodus-service/src/store_license.rs
|
||||
+++ b/crates/xodus-service/src/store_license.rs
|
||||
@@ -63,8 +63,7 @@ async fn issue(context: &SimpleContext, request: StoreLicenseTokenRequest) -> Re
|
||||
let device_response = xodus::api::live::exchange_device_token(&context.client, device.clone(),
|
||||
client_id.into(), "www.microsoft.com".into(), Some(soap::PolicyReference::mbi_ssl()))
|
||||
.await.map_err(|_| FAIL)?;
|
||||
- if device_response.token_type != "urn:passport:compact" { return Err(FAIL) }
|
||||
- let Token::Compact(device_token) = Token::try_from(device_response).map_err(|_| FAIL)? else { return Err(FAIL) };
|
||||
+ let device_token = device_license_ticket(device_response)?;
|
||||
let user_response = xodus::api::live::exchange_user_token(&context.client, user_sts,
|
||||
account.username, device, None, Some("Silent".into()), client_id.into(),
|
||||
&[("www.microsoft.com".into(), Some(soap::PolicyReference::mbi_ssl()))])
|
||||
@@ -98,6 +97,13 @@ async fn issue(context: &SimpleContext, request: StoreLicenseTokenRequest) -> Re
|
||||
Ok(response.license_token)
|
||||
}
|
||||
|
||||
+fn device_license_ticket(response: soap::RequestSecurityTokenResponse) -> Result<String, u32> {
|
||||
+ if !user_ticket_type(&response.token_type) { return Err(FAIL) }
|
||||
+ let Token::Compact(ticket) = Token::try_from(response).map_err(|_| FAIL)? else { return Err(FAIL) };
|
||||
+ if ticket.is_empty() || ticket == "d=" { return Err(FAIL) }
|
||||
+ Ok(xodus::models::secrets::licensing_device_ticket(ticket))
|
||||
+}
|
||||
+
|
||||
fn user_ticket_type(token_type: &str) -> bool {
|
||||
matches!(token_type, "urn:passport:compact" | "urn:passport:delegationcompact")
|
||||
}
|
||||
@@ -134,6 +140,45 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
+ fn device_response(kind: &str, value: Option<&str>) -> soap::RequestSecurityTokenResponse {
|
||||
+ soap::RequestSecurityTokenResponse {
|
||||
+ token_type: kind.into(),
|
||||
+ applies_to: soap::AppliesTo { endpoint_reference: soap::EndpointReference { address: "synthetic.invalid".into() } },
|
||||
+ lifetime: soap::Timestamp { id: None, created: "2000-01-01T00:00:00Z".into(), expires: "2099-01-01T00:00:00Z".into() },
|
||||
+ requested_security_token: soap::RequestedSecurityToken { encrypted_data: None,
|
||||
+ binary_security_token: value.map(|value| soap::BinarySecurityTokenRes {
|
||||
+ id: "synthetic".into(), value: value.into(), value_type: None }) },
|
||||
+ requested_proof_token: None,
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn store_license_device_compact_tickets_are_sent_unchanged() {
|
||||
+ let raw = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..aXY.Y2lwaGVy_dGV4dA.dGFn";
|
||||
+ for value in ["t=opaque-device&p=", "opaque-device", raw] {
|
||||
+ assert_eq!(device_license_ticket(device_response("urn:passport:compact", Some(value))), Ok(value.to_string()));
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn store_license_device_delegation_tickets_use_the_licensing_wire_form() {
|
||||
+ let raw = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..aXY.Y2lwaGVy_dGV4dA.dGFn";
|
||||
+ assert_eq!(device_license_ticket(device_response("urn:passport:delegationcompact", Some(raw))), Ok(raw.to_string()));
|
||||
+ assert_eq!(device_license_ticket(device_response("urn:passport:delegationcompact", Some("opaque-device"))),
|
||||
+ Ok("t=opaque-device".to_string()));
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn store_license_device_unknown_missing_and_empty_tickets_fail_closed() {
|
||||
+ for kind in ["urn:passport:legacy", "urn:passport:unknown"] {
|
||||
+ assert_eq!(device_license_ticket(device_response(kind, Some("opaque-device"))), Err(FAIL));
|
||||
+ }
|
||||
+ for kind in ["urn:passport:compact", "urn:passport:delegationcompact"] {
|
||||
+ assert_eq!(device_license_ticket(device_response(kind, None)), Err(FAIL));
|
||||
+ assert_eq!(device_license_ticket(device_response(kind, Some(""))), Err(FAIL));
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
fn request(ids: &[&str]) -> StoreLicenseTokenRequest {
|
||||
StoreLicenseTokenRequest { parent_product_id: "9N4PT8HGCDHQ".into(),
|
||||
product_ids: ids.iter().map(|s| s.to_string()).collect(), custom_developer_string: "nonce<&>".into() }
|
||||
diff --git a/crates/xodus/src/models/licensing_ticket_tests.rs b/crates/xodus/src/models/licensing_ticket_tests.rs
|
||||
index 10ff57e..6db9ff1 100644
|
||||
--- a/crates/xodus/src/models/licensing_ticket_tests.rs
|
||||
+++ b/crates/xodus/src/models/licensing_ticket_tests.rs
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Public synthetic data only, no account, keyring or network access.
|
||||
-use super::{Token, licensing_ticket, store_ticket, xbox_ticket};
|
||||
+use super::{Token, licensing_device_ticket, licensing_ticket, store_ticket, xbox_ticket};
|
||||
use crate::models::soap;
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use serde_json::json;
|
||||
@@ -109,3 +109,23 @@ fn credential_xbox_ticket_opaque_and_malformed_tokens_are_preserved() {
|
||||
}
|
||||
for ticket in cases { assert_eq!(xbox_ticket(ticket.clone()), ticket); }
|
||||
}
|
||||
+
|
||||
+#[test]
|
||||
+fn credential_licensing_device_ticket_delegation_forms_use_the_licensing_wire_form() {
|
||||
+ for raw in [
|
||||
+ jwe(json!({"alg":"dir","enc":"A128CBC-HS256"}), ""),
|
||||
+ jwe(json!({"alg":"RSA-OAEP-256","enc":"A256GCM"}), "a2V5"),
|
||||
+ ] {
|
||||
+ let Token::Compact(original) = delegation(&raw) else { panic!("fixture"); };
|
||||
+ assert_eq!(licensing_device_ticket(original), raw);
|
||||
+ }
|
||||
+ assert_eq!(licensing_device_ticket("d=opaque-device".into()), "t=opaque-device");
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn credential_licensing_device_ticket_plain_compact_forms_stay_byte_exact() {
|
||||
+ let raw = jwe(json!({"alg":"dir","enc":"A256GCM"}), "");
|
||||
+ for ticket in ["t=opaque-device&p=".to_string(), "opaque-device".into(), "".into(), raw.clone(), format!("t={raw}")] {
|
||||
+ assert_eq!(licensing_device_ticket(ticket.clone()), ticket);
|
||||
+ }
|
||||
+}
|
||||
diff --git a/crates/xodus/src/models/secrets.rs b/crates/xodus/src/models/secrets.rs
|
||||
index 1ad97be..9de6eea 100644
|
||||
--- a/crates/xodus/src/models/secrets.rs
|
||||
+++ b/crates/xodus/src/models/secrets.rs
|
||||
@@ -102,6 +102,10 @@ pub fn licensing_ticket(ticket: String) -> String {
|
||||
if is_compact_jwe(bare) { bare.to_string() } else { store_ticket(ticket) }
|
||||
}
|
||||
|
||||
+pub fn licensing_device_ticket(ticket: String) -> String {
|
||||
+ if ticket.starts_with("d=") { licensing_ticket(ticket) } else { ticket }
|
||||
+}
|
||||
+
|
||||
// This recognizes wire encoding, not authenticity or entitlement. Microsoft
|
||||
// still validates the entire ticket. Never decrypt, log or rewrite its payload.
|
||||
fn is_compact_jwe(value: &str) -> bool {
|
||||
@@ -9,7 +9,8 @@ recipe = Path(__file__).resolve().parent
|
||||
cache = Path(sys.argv[1]).resolve()
|
||||
lock = json.loads((recipe / 'backend.lock.json').read_text())
|
||||
local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', 'droiddeck-library-subscriptions.patch',
|
||||
'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch', 'droiddeck-cloud-token.patch', 'droiddeck-xbox-ticket.patch']
|
||||
'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch', 'droiddeck-cloud-token.patch', 'droiddeck-xbox-ticket.patch',
|
||||
'droiddeck-licensing-device-ticket.patch']
|
||||
identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest()
|
||||
source = cache / ('source-' + identity[:16])
|
||||
if not (source / '.prepared').is_file():
|
||||
|
||||
@@ -14,5 +14,15 @@
|
||||
"xgameruntime.dll": "060120e0ec6bccfbab516128315a0658b11d3e316f62a917c653daf1a1dd3e05",
|
||||
"winhttp.dll": "81e1da7a731d83fbd24dbe2fa2ecb8f155bd477a9f9b6f4cc3932063cc326c27",
|
||||
"wintypes.dll": "7d06083e3d8b3a7e11555a91e7918f11c7d444a74755d41c8d1990db3697c895"
|
||||
},
|
||||
"compat": {
|
||||
"files/share/xodus-nexus/compat/PlayFabGameSave.dll": [
|
||||
"compat/PlayFabGameSave.dll",
|
||||
"29b1ab5e54b35e40ee5b376237f4ab642e1d0f3d7614e3e46208e9ad8a6e0a79"
|
||||
],
|
||||
"files/share/doc/xodus-nexus-runtime/runtime-compat-LICENSE": [
|
||||
"LICENSE.runtime-compat",
|
||||
"639b735fd2f65779b82c4aab471f1fcdf927e10e1c21250911f75d44d136ff11"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -37,8 +37,22 @@ archive = download(lock['archive'], lock['sha512'], 'sha512')
|
||||
source = lock['source']
|
||||
download(source['name'], source['sha256'], 'sha256')
|
||||
remaining = set(lock['dlls'])
|
||||
# Prebuilt runtime-compat files from the same archive (MIT), placed next to windows/ in the pack: the
|
||||
# PlayFab Game Saves save-folder proxy that droiddeck-xbox stages in front of a title's SDK, and its license.
|
||||
compat = dict(lock.get('compat', {}))
|
||||
with tarfile.open(archive) as tar:
|
||||
for member in tar:
|
||||
relative = member.name.partition('/')[2]
|
||||
if relative in compat:
|
||||
target, expected = compat.pop(relative)
|
||||
if not member.isfile() or member.size > 32 * 1024 * 1024:
|
||||
raise RuntimeError('Invalid Xbox runtime compatibility file')
|
||||
data = tar.extractfile(member).read()
|
||||
if hashlib.sha256(data).hexdigest() != expected:
|
||||
raise RuntimeError('Xbox runtime compatibility file checksum mismatch')
|
||||
(output.parent / target).parent.mkdir(parents=True, exist_ok=True)
|
||||
(output.parent / target).write_bytes(data)
|
||||
continue
|
||||
name = Path(member.name).name
|
||||
if '/files/lib/wine/x86_64-windows/' not in member.name or name not in remaining:
|
||||
continue
|
||||
@@ -53,3 +67,5 @@ with tarfile.open(archive) as tar:
|
||||
remaining.remove(name)
|
||||
if remaining:
|
||||
raise RuntimeError('Missing Xbox runtime modules')
|
||||
if compat:
|
||||
raise RuntimeError('Missing Xbox runtime compatibility files')
|
||||
Reference in new issue
Block a user