Compare commits

..
Author SHA1 Message Date
xXJsonDeruloXx 7a8efce905 fix(battlenet): use reconciliation context for deletion guards 2026-11-30 16:38:58 -05:00
xXJsonDeruloXx c10369ed99 fix(battlenet): guard stale removal and preserve registry-only installs 2026-11-30 15:08:38 -05:00
xXJsonDeruloXx 39d8149a16 fix(battlenet): validate folder registrations before launch and deletion 2026-11-30 09:41:10 -05:00
visail 9ddb52c5fc fix(battlenet): retry a cancelled install's cleanup across restarts
The ownership rules from the previous change stop a cancel from deleting
someone else's registration, but a process killed mid-cleanup left the
registration behind with nothing to retry it, and a registration the client
writes just after the cancel looked at the folder was never seen.

A cancelled cleanup now records a marker per folder (SHA-256 of its path,
written atomically): ACTIVE while the install runs, PENDING when the cleanup
must still happen, WATCHING while the client may still be writing its
registration. reconcile() runs on the next refresh, checks the marker against
the registrations that are actually there, retries with backoff, and clears
the marker once the registration is gone and the folder it created is
deleted. uninstall() verifies the registration really disappeared before it
reports success.

The design document moves to docs/development/battlenet-china.md: it describes
the merged state, so the -final suffix and the #2150 reference no longer
belong in it.
2026-11-30 09:39:18 -05:00
visail b0904cc65b fix(battlenet): a cancelled install never removes a pre-existing registration
Cancelling an install uninstalled whatever registration lived in the folder,
so cancelling a reinstall of a game the user had installed from the Battle.net
client deleted that client's registration.

An install now decides ownership once, before it starts: the registrations that
were already in the folder belong to someone else and are never touched,
including the unfinished registration an earlier cancelled install left behind.
The decision is snapshotted into SavedQueue when the queue accepts the task, so
a resumed or restored install keeps it instead of re-reading a folder that may
already hold this task's own registration. The cancellation also holds the
folder against a concurrent uninstall, only removes the uids it saw, and only
deletes a folder it created itself. The queue publishes the cleanup key so a
second cancellation of the same game cannot start a parallel cleanup.
2026-11-30 09:39:18 -05:00
visail e309280b65 fix(battlenet): re-check an update when the build changes during the request
A version request that raced a client update read .build.info before asking and
after answering. When the build changed in between the check only cleared its
throttle and the badge, but nothing ever asked again, so an available update
stayed invisible until some unrelated trigger.

The repairable case (a newer local build than the one queried) now schedules a
force re-check after 30 s and at most twice; a failed read or a failed version
request still only clears the throttle and is not retried on a timer, so an
offline device does not spin on the network.
2026-11-30 09:38:37 -05:00
visail 4283fd810e fix(battlenet): check updates per install folder on the China version line
The update state was keyed by title, so two copies of the same game in
different folders shared one badge, and a China install was compared against
the global version line, which it never follows.

The badge is now keyed by id and folder. A China build asks the China
repository for the product it is actually served from (osic, s2c, d3cn), and
the check re-reads .build.info after the request so a build that changed
meanwhile is retried instead of reported against a stale key. refresh() checks
every installed Battle.net game, the library badge reads the same key, and the
detail screen re-checks once the running session ends.
2026-11-30 09:38:37 -05:00
visail 296b4586a4 fix(battlenet): match installs by store identity and resolve the launch code in its folder
Three lookups assumed one uid per store title, which breaks as soon as a title
has more than one identity or more than one copy:

- installUid() compared the store id to the discovered uid, so an alias such as
  fen/fenris could not be managed; it also read a failed registration load as
  'no install'. It now matches through sameTitle() and returns null when the
  sources cannot be read.
- launchCode() served a folder from BattleNet.games(), which keeps one copy per
  launch code, so a second copy of the same game in another folder had no code.
  It now resolves the registrations of that folder directly (registrationsIn).
- StoresState kept a folder only when games() listed it; an unreadable
  registration file made games() empty and the folder was deleted. It now also
  keeps the folder when registrationsReadable() is false.

sameTitle() folds the China aliases into the store uid and accepts two uids that
share a code and product, so a China D3 copy still launches as D3CN.
2026-11-30 09:38:01 -05:00
visail 60b22a826a fix(battlenet): keep China copies on the store card and target the installed folder
Diablo III installed by the China client was a separate d3cn card with its own
identity, so a China copy and an international one could not coexist. It now
resolves to the diablo3 card through a Cnv alias that carries only the launch
code and the China product, the same way osic/s2_cn already did.

An install is also matched by its folder instead of by title, so two copies of
Diablo III in different folders each update, uninstall and launch with their own
recorded code. A shortcut whose copy is gone now says so instead of failing
with a Steam error.
2026-11-30 09:38:01 -05:00
visail 3512eb942d fix(battlenet): cancel a China install by the uid the driver registered
The driver rewrites the uid for a Chinese client install (osi -> osic,
s2 -> s2_cn, diablo3 -> d3cn) inside the Windows agent script, so the Kotlin
side never learned which uid was actually installed. Cancelling a fresh
install then fell back to the store uid (diablo3), and when the same prefix
also held an international copy the Agent was asked to uninstall that copy
instead.

The driver now records the effective uid in .uid, emits it as BNET_UID as
soon as it is known and repeats it in the DONE payload; the installer keeps
it for the task. Cancel no longer guesses a uid: it uninstalls the recorded
one, or leaves the registration to Battle.net and only removes the folder
when it is empty or the recorded install is gone.

Parts 5 and 6 still read the registrations on disk before removing anything;
this part makes the earlier stacked PRs safe to merge on their own.
2026-11-30 09:38:00 -05:00
visail 2ae51a1e6a fix(battlenet): install China products under their own uids
The China client installs Diablo II, StarCraft II and Diablo III under the
CN uids and products of its own repository instead of the global ones. Only
an install request is remapped: an update or uninstall keeps using the uid
the Agent already recorded.
2026-11-30 09:38:00 -05:00
MaxsTechReview 72c8b8426d fix(input): Windows games see the gamepad again when the pad is not read through SDL (#3469)
Since each pad was described to Wine's udev backend with the identity its
SDL backend sees, the udev backend left every pad to SDL. Where SDL does
not open the pad, such as a session without proot, Windows games lost both
the gamepad and the on-screen controls.

The udev backend owns the pads again with the Steam Input identity it had
before. SDL inside Wine's bus driver now reads the same identity for those
pads and skips them as it skips any Steam Input pad, so each pad is still
listed once and both triggers keep reading together.
2026-11-30 08:53:12 -05:00
xlulx 6dc3d01674 fix(display): apply a client's commit only after its GPU has finished writing the buffer (#3004) 2026-11-30 04:23:04 -05:00
MaxsTechReview df2cfa40b3 test(xbox): cover device-limit diagnostic routing (#3458) 2026-11-30 01:38:08 -05:00
MaxsTechReview e101a78791 fix(stores): the front end no longer crashes on start when the Steam engine starts on the refresh thread (#3457)
Keep the Steam install picker state out of the Steam engine object

The picker state lived on SteamStore, which is first touched from the
background stores refresh thread. On the Compose runtime in use, a state
object created outside a snapshot while the composition holds an open
snapshot is unreadable inside it, so the front end crashed on startup
with "Reading a state that was created after the snapshot was taken".
The state now lives on StoresState next to the other UI-facing store
state, and SteamStore holds no Compose state.
2026-11-30 00:02:07 -05:00
The412Banner aaa9fb129c fix(nativeguest): programs on a mount kept at its host path start as guest programs (#3211) 2026-11-29 23:58:32 -05:00
MaxsTechReview 23d7e639ca fix(steam): mark ARM64-uninstallable tool dependencies installed (#3443)
* fix(steam): mark ARM64-uninstallable tool dependencies installed

The ARM64 client cannot install Proton EasyAntiCheat Runtime (1826330),
which it refuses as an invalid platform, or that tool's Steam Linux
Runtime 1.0 (scout) dependency (1070560), which has no ARM64 depot. After
the EULA hand-off the client starts the dependency install and aborts in
glibc's smallbin check.

Write the bare installed manifest DroidDeck already uses for adopted games
for those two tools before the client starts: only on the ARM64 client,
only when appinfo shows no ARM64 depot, and never over a fully installed
manifest.

Refs: ValveSoftware/steam-for-linux#13937, DroidDeck #2313

* fix(steam): seed a tool only when no library has it installed, and write manifests atomically

A partial manifest in the first library no longer hides a full install in
another one, and a failed write leaves no truncated or stray manifest.

* fix(steam): publish tool manifests without replacing concurrent installs
2026-11-29 23:38:39 -05:00
MaxsTechReview 4ef23ed0e9 Return to the DroidDeck UI when logging out of the desktop (#3374)
* fix(desktop): Log Out returns to DroidDeck, Return to Gaming Mode opens Steam

Both ended Plasma through the same logout call and the desktop script always
started Steam afterwards. Return to Gaming Mode now leaves a request that the
script reads; a plain Log Out ends the desktop. The app ships the shortcut
with the script so both always change together.

* Wait for the logout reply so a cold Shutdown service still gets the request

* Forget the return to gaming mode when the logout request fails
2026-11-29 23:04:31 -05:00
ff35cce127 fix(steam): GTA III on Steam starts a new game (full x87 precision for app 12100) (#3197)
The Steam copy (AppID 12100) died on "Start new game" at 0042A703: FEX's reduced x87 precision turns a float into a bad pointer. GameEnvironment.knownGames sets FEX_X87REDUCEDPRECISION=0 for it, above the shared settings and below the game's own, and picking a FEX preset for the game keeps the fix.

Co-authored-by: Unixcision <14082251+Unixcision@users.noreply.github.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-29 22:51:35 -05:00
Tamim KabirandKurt Himebauch 0951b602b7 fix(input): programs built with _FORTIFY_SOURCE read the virtual pads (#2916)
* fix(input): programs built with _FORTIFY_SOURCE read the virtual pads

Fortified builds, Flatpak runtimes among them, call __read_chk, __poll_chk
and __ppoll_chk in place of read, poll and ppoll, and glibc's versions go
straight to the kernel. Such programs opened a pad through the shim but read
its backing ring file instead of events, so they never saw input: Marathon
Recompiled's SDL reads the pad through __read_chk.

The shim now provides all three, with glibc's bounds checks, on the same
paths as read, poll and ppoll.

* fix(input): keep glibc's __read_chk for descriptors that are not pads

Only pad descriptors take the shim's read path; the rest go to the next
__read_chk, so fortified reads keep libc's cancellation point. The test
also polls the empty ring with a zero timeout, which a __poll_chk that
bypasses the shim would report as ready.

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-29 22:51:30 -05:00
LarzVaderandKurt Himebauch 57055be6fb fix(ci): Robolectric's jar cache is saved again, and a Maven 429 runs the unit tests again (#3418)
* fix(ci): Robolectric's jar cache is saved again, and a Maven 429 runs the unit tests again

* fix(ci): retry Gradle artifact download rate limits too

* fix(ci): restrict Maven retry to dependency download exceptions

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-29 21:13:54 -05:00
MaxsTechReview c6743730aa Keep a signed-in store's Library tab when its game list is empty or failed to load (#3449) 2026-11-29 20:24:34 -05:00
MaxsTechReview 780c5658d0 fix(input): each pad is listed once in Windows games so both triggers read together (#3436)
* fix(input): each pad is listed once in Windows games so both triggers read together

A pad that Wine's SDL backend also reads was described to Wine's udev
backend as a Steam Input virtual pad, so Wine built two devices for one
pad. SDL RawInput games could not match the two and read held triggers as
released. The pad now keeps the identity the SDL backend sees unless that
backend is told to skip it.

Rumble that Wine starts through SDL is now held until the next update,
matching the udev path, instead of stopping after one second.

* fix(input): hold only the rumble Wine starts through SDL, not later SDL rumble in the same process

* fix(input): read @file SDL ignore lists when choosing the pad identity

SDL reads the ignore and except lists from a file when the value starts
with @. Match the ring pad ID against that file's contents too.

* fix(input): parse SDL controller ID lists the way SDL does when choosing the pad identity
2026-11-29 20:24:20 -05:00
MaxsTechReview a9e8a01bb6 fix(native): prepare the rootfs before a helper starts outside a session (#3447)
Prepare the rootfs before a native program starts outside a session

The linker and libc are patched for Android's seccomp filter only when a
session starts. A helper started between sessions, after a runtime
update and before the first session, ran the unpatched linker and died
of SIGSYS (exit code 159). The shared native process builder now
prepares the rootfs itself when no session is running.
2026-11-29 19:44:11 -05:00
MaxsTechReview 861121144c fix(xbox): try the next listed executable when one is missing (#3446)
A package can list several PC executables while shipping only some of them. Try each listed executable in order and fail only when none of them exist.
2026-11-29 19:33:55 -05:00
d7fcea74b4 fix(mali): Auto respects Venus turned off and picks the bridge on Mali-G2-Ultra (#3198)
* fix(mali): Auto respects Venus turned off and picks the bridge on Mali-G2-Ultra

With GPU drivers on Auto, Mali (Venus) was turned back on after the user turned it off. Auto now respects that choice, and picks the bridge on Mali-G2-Ultra, where Steam's web helper dies on its first window through Venus (#2879). When Auto itself turns Venus off it clears the stored key, so its own decision does not read as the user's later.

* fix(mali): clear Auto-owned Venus preference when fallback ends

---------

Co-authored-by: Unixcision <14082251+Unixcision@users.noreply.github.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-29 17:17:51 -05:00
sergeymetallicandsergeymetallic 44b429ca20 fix(game-env): resolve store launcher executable from sidecar (#3288)
* fix(game-env): resolve store launcher executable from sidecar

Store titles launched through .droiddeck-launch.bat passed the wrapper
path directly into engine_fixes and other exe-based checks, so stem
checks saw .droiddeck-launch and game_files scanned from the install
root rather than the executable's folder. For Epic's Batman: Arkham
City, Binaries/Win32/BatmanAC.exe sat one level deeper than game_files
scans, so arkham_city_x87 never set FEX_X87REDUCEDPRECISION=0.

Resolve .droiddeck-launch.bat to the validated exe entry from
.droiddeck-store.json when inspecting the game, while keeping the
launcher path in the Proton command.

* fix(game-env): reject parent segments before normpath in store_game_exe

os.path.normpath lexically collapses symlink/../file before the
filesystem is consulted, which could validate a different file than a
symlinked subdirectory path denotes. Reject any ".." path component
after separator normalization before calling os.path.normpath.

---------

Co-authored-by: sergeymetallic <6938136+sergeymetallic@users.noreply.github.com>
2026-11-29 16:18:43 -05:00
Dhiman SealandKurt Himebauch c91b100bc1 fix(game-env): run Inno Setup installers with the FEX Stability settings (#3069)
* fix(game-env): run Inno Setup installers with the FEX Stability settings

An Inno Setup installer added as a game stops with Wine's "Path not
fpund." dialog under the default FEX preset. The 32-bit setup stub
corrupts its own paths before it opens its archive (#1277, #3067). #1174
avoids the stub only for GOG installs, by extracting them natively.

droiddeck-game-env now finds the stub by the setup loader's offset-table
ID in its resources, or the "Inno" marker older loaders keep at 0x30, and
launches it with the Stability preset's FEX settings. A FEX preset chosen
for the game itself still wins.

Fixes #3067

* fix(game-env): name only the preset seen to corrupt Inno Setup paths

The launch note and the docs said the faster presets corrupt the setup
stub. Only the default Performance + TSO preset was seen doing it.

* fix(game-env): give Inno Setup installers started with run the Stability settings

The run verb skips engine_fixes and gets only the sync settings, so an installer started that way kept the inherited Performance + TSO preset. Apply the Stability values on that path too; explicit game settings still win in apply_config.

* fix(game-env): keep the game's own FEX settings for installers started with run

The run path filtered the game entry down to sync keys, so a FEX preset
chosen for the game was replaced by the installer's Stability settings,
and a null could not unset a preset key. Copy the game's Stability FEX
keys into the synced config before applying it, so the game's own
settings still win on every launch path.

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-29 16:18:35 -05:00
LarzVader 90df30f4d7 fix(venus): OpenGL quads no longer crash Mali's shader compiler through Zink (#3283)
* fix(venus): OpenGL quads no longer crash Mali's shader compiler through Zink

The Mali-G610's driver crashes compiling Zink's geometry shaders
(SIGSEGV at 0x40 in cmpbe_v2_compile_multiple_shaders), and the render
server and the application die with it. A plain geometry shader that
only passes triangles on does not crash it, but draws nothing. Zink
draws GL_QUADS through a geometry shader when the device has the
feature, so OpenGL programs died on their first quad.

The Mali layer now reports no geometryShader to Zink on ARM GPUs.
Mesa then splits quads into triangles itself. DXVK keeps the feature,
which it needs for D3D10 and 11. DROIDDECK_MALI_COMPAT_NO_GS=0 keeps
it for Zink, =1 hides it from every application.

* test(venus): clear DROIDDECK_MALI_COMPAT_NO_GS before the layer tests

The geometry shader test checks the default first. With the variable
exported in the shell, it failed before it reached its own settings.

* test(venus): check that other ARM applications keep the geometry shader
2026-11-29 16:18:27 -05:00
devu92 2b6ded9fd4 Fix persistent black video after delayed GPU fences (#3400)
fix(vulkan): keep presenting after delayed GPU fence completion
2026-11-29 16:18:19 -05:00
btns29andbtns29 38c2c00c86 Keep safe webhelper layout on Mali bridge (#3420)
* Keep safe webhelper layout on Mali bridge

* Name the zygote regression in the layout test

---------

Co-authored-by: btns29 <btns29@users.noreply.github.com>
2026-11-29 15:53:48 -05:00
Kurt Himebauch 678057d727 Prompt for shared folders named Android/data, and reload after any regrant (#3435)
Prompt for shared folders named Android/data, and reload the folder after any regrant
2026-11-29 15:06:47 -05:00
Kurt Himebauch ae94009382 Ask for all-files access when a shared drive is opened, not on first launch (#3429) 2026-11-29 15:02:25 -05:00
Kurt Himebauch fd93a35b72 Start Steam by itself when first-run setup finishes (#3430) 2026-11-29 15:02:11 -05:00
MaxsTechReview 12fa3ac343 fix(input): a trigger key sent before its axis no longer counts as two presses (#3431)
A trigger key that fires before its axis no longer reads as two presses
2026-11-29 14:20:14 -05:00
87 changed files with 4352 additions and 354 deletions

No files matched your search

+17 -5
View File
@@ -740,7 +740,8 @@ jobs:
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
# The cache path sits beside the workspace because runner homes are at different depths from it, and
# actions/cache stores paths relative to the workspace. Runners that keep their own ~/.m2 skip the cache.
# actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects
# "..". Runners that keep their own ~/.m2 skip the cache.
- name: Place Robolectric's Android jars beside the workspace
id: robolectric-jars
run: |
@@ -751,7 +752,9 @@ jobs:
echo "cache=false" >> "$GITHUB_OUTPUT"
else
mkdir -p "$jars" "$(dirname "$m2")"
ln -sfn "$(cd "$jars" && pwd)" "$m2"
jars=$(cd "$jars" && pwd)
ln -sfn "$jars" "$m2"
echo "path=$jars" >> "$GITHUB_OUTPUT"
echo "cache=true" >> "$GITHUB_OUTPUT"
fi
- name: Restore Robolectric's Android jars
@@ -759,7 +762,7 @@ jobs:
if: steps.robolectric-jars.outputs.cache == 'true'
uses: actions/cache/restore@v4
with:
path: ../robolectric-jars
path: ${{ steps.robolectric-jars.outputs.path }}
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
- name: Count the restored Robolectric jars
@@ -773,7 +776,16 @@ jobs:
run: |
set -o pipefail
mkdir -p app/build
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
# A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next.
for wait in 60 180 0; do
status=0
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$?
if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://repo\.maven\.apache\.org/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://repo\.maven\.apache\.org/)' app/build/unit-tests.log; then
exit "$status"
fi
echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s"
sleep "$wait"
done
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
@@ -800,7 +812,7 @@ jobs:
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
uses: actions/cache/save@v4
with:
path: ../robolectric-jars
path: ${{ steps.robolectric-jars.outputs.path }}
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
- name: Upload unit test diagnostics
+22
View File
@@ -4130,6 +4130,17 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) {
return read_input(fd, buf, count);
}
extern "C" [[noreturn]] void __chk_fail(void);
/* Programs built with _FORTIFY_SOURCE (Flatpak runtimes among them) call these instead of read, poll
* and ppoll, and glibc's versions go straight to the kernel. */
EXPORT ssize_t __read_chk(int fd, void *buf, size_t count, size_t buflen) {
static auto next_read_chk = reinterpret_cast<ssize_t (*)(int, void *, size_t, size_t)>(dlsym(RTLD_NEXT, "__read_chk"));
if (count > buflen) __chk_fail();
if (next_read_chk && !is_fake_input_fd(fd)) return next_read_chk(fd, buf, count, buflen);
return read_input(fd, buf, count);
}
EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) {
if (!is_fake_input_fd(fd)) return syscall(SYS_readv, fd, iov, iovcnt);
if (iovcnt < 0 || iovcnt > IOV_MAX) {
@@ -4378,6 +4389,17 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
return my_ppoll(fds, nfds, timeout, sigmask);
}
EXPORT int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
return poll(fds, nfds, timeout);
}
EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout,
const sigset_t *sigmask, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
return ppoll(fds, nfds, timeout, sigmask);
}
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout) {
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
+286 -39
View File
@@ -242,6 +242,10 @@ struct surface {
enum surface_role role;
struct wl_resource *idle_buffer;
struct wl_listener idle_buffer_destroy;
struct surface_state *waiting;
struct wl_event_source *waiting_source, *waiting_timer;
int waiting_fd;
int64_t waiting_since_ns;
uint32_t *idle_px;
int idle_w, idle_h;
struct wl_resource *xdg_surface, *xdg_toplevel;
@@ -373,6 +377,8 @@ static struct {
unsigned copy_scenes;
unsigned releases, releases_held;
int64_t release_ns, release_max_ns;
unsigned commit_waits, commit_wait_limits;
int64_t commit_wait_ns, commit_wait_max_ns;
} g_perf;
static void schedule_render(void);
@@ -846,6 +852,55 @@ static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) {
s->pending_buffer = NULL;
}
struct surface_state {
struct wl_resource *buffer;
struct wl_listener buffer_destroy;
int attach;
int src_set, dst_set, opaque_set;
float src[4];
int dst[2], opaque[4];
struct damage_list damage_buf, damage_local;
struct wl_list frames, feedback;
};
static void on_state_buffer_destroyed(struct wl_listener *l, void *data) {
struct surface_state *st = wl_container_of(l, st, buffer_destroy);
wl_list_remove(&st->buffer_destroy.link);
wl_list_init(&st->buffer_destroy.link);
st->buffer = NULL;
st->attach = 0;
}
static void surface_state_take(struct surface *s, struct surface_state *st) {
st->attach = s->pending_attach;
st->buffer = s->pending_buffer;
wl_list_init(&st->buffer_destroy.link);
if (st->buffer) {
wl_list_remove(&s->pending_buffer_destroy.link);
wl_list_init(&s->pending_buffer_destroy.link);
st->buffer_destroy.notify = on_state_buffer_destroyed;
wl_resource_add_destroy_listener(st->buffer, &st->buffer_destroy);
}
s->pending_buffer = NULL;
s->pending_attach = 0;
st->src_set = s->pending_src_set;
memcpy(st->src, s->pending_src, sizeof(st->src));
st->dst_set = s->pending_dst_set;
memcpy(st->dst, s->pending_dst, sizeof(st->dst));
st->opaque_set = s->pending_opaque_set;
memcpy(st->opaque, s->pending_opaque, sizeof(st->opaque));
s->pending_src_set = s->pending_dst_set = s->pending_opaque_set = 0;
st->damage_buf = s->pending_damage_buf;
st->damage_local = s->pending_damage_local;
s->pending_damage_buf.n = s->pending_damage_local.n = 0;
wl_list_init(&st->frames);
wl_list_insert_list(&st->frames, &s->pending_frames);
wl_list_init(&s->pending_frames);
wl_list_init(&st->feedback);
wl_list_insert_list(&st->feedback, &s->pending_feedback);
wl_list_init(&s->pending_feedback);
}
static void fire_frames(struct wl_list *frames) {
struct wl_resource *cb, *tmp;
uint32_t t;
@@ -1363,35 +1418,23 @@ static void surface_drop_idle(struct surface *s) {
if (buffer) send_buffer_release(buffer);
}
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
static void surface_state_apply(struct surface *s, struct surface_state *st) {
struct surface *child;
if (s->xdg_toplevel && !s->toplevel_committed) {
s->toplevel_committed = 1;
send_toplevel_configure(s);
if (st->src_set) {
s->src_set = st->src[2] > 0;
memcpy(s->src, st->src, sizeof(s->src));
}
if (st->dst_set) {
s->dst_set = st->dst[0] > 0;
memcpy(s->dst, st->dst, sizeof(s->dst));
}
if (st->opaque_set) memcpy(s->opaque, st->opaque, sizeof(s->opaque));
if (s->pending_src_set) {
s->src_set = s->pending_src[2] > 0;
memcpy(s->src, s->pending_src, sizeof(s->src));
s->pending_src_set = 0;
}
if (s->pending_dst_set) {
s->dst_set = s->pending_dst[0] > 0;
memcpy(s->dst, s->pending_dst, sizeof(s->dst));
s->pending_dst_set = 0;
}
if (s->pending_opaque_set) {
memcpy(s->opaque, s->pending_opaque, sizeof(s->opaque));
s->pending_opaque_set = 0;
}
s->damage_buf = s->pending_damage_buf;
s->damage_local = s->pending_damage_local;
s->pending_damage_buf.n = s->pending_damage_local.n = 0;
if (s->pending_attach) {
struct wl_resource *buffer = s->pending_buffer;
s->damage_buf = st->damage_buf;
s->damage_local = st->damage_local;
if (st->attach) {
struct wl_resource *buffer = st->buffer;
struct dmabuf_buffer *db = get_dmabuf(buffer);
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
uint8_t pixel[4];
@@ -1400,12 +1443,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
if (!buffer) g_pace.null_attaches++;
else if (!db) s->last_dmabuf = NULL;
if (buffer) {
wl_list_remove(&s->pending_buffer_destroy.link);
wl_list_init(&s->pending_buffer_destroy.link);
}
s->pending_buffer = NULL;
s->pending_attach = 0;
wl_list_remove(&st->buffer_destroy.link);
wl_list_init(&st->buffer_destroy.link);
st->buffer = NULL;
st->attach = 0;
surface_drop_idle(s);
buf_trace_attach(buffer);
@@ -1442,10 +1483,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
}
}
wl_list_insert_list(s->frames.prev, &s->pending_frames);
wl_list_init(&s->pending_frames);
wl_list_insert_list(s->feedback.prev, &s->pending_feedback);
wl_list_init(&s->pending_feedback);
wl_list_insert_list(s->frames.prev, &st->frames);
wl_list_init(&st->frames);
wl_list_insert_list(s->feedback.prev, &st->feedback);
wl_list_init(&st->feedback);
constraints_surface_commit(s);
droiddeck_color_commit(s->resource);
@@ -1455,6 +1496,186 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
}
schedule_render();
}
#define COMMIT_WAIT_LIMIT_MS 1000
static struct surface *g_zero_copy_shown, *g_unwaited;
static int state_unfinished_fd(const struct surface *s, const struct surface_state *st, int *unwaited) {
struct dmabuf_buffer *db = st->attach ? get_dmabuf(st->buffer) : NULL;
int fd = -1;
*unwaited = 0;
for (int i = 0; db && fd < 0 && i < db->n_planes; i++) {
if (db->fd[i] < 0) continue;
struct pollfd p = {.fd = db->fd[i], .events = POLLIN};
int r;
do { r = poll(&p, 1, 0); } while (r < 0 && errno == EINTR);
if (r == 0) fd = db->fd[i];
}
if (fd >= 0 && s == g_zero_copy_shown && ahb_swapchain_has_ahb(db)) {
*unwaited = 1;
return -1;
}
return fd;
}
static void settle_unwaited(void) {
struct surface *s = g_unwaited;
if (!s) return;
g_unwaited = NULL;
struct dmabuf_buffer *db = s->dmabuf_buf;
const int64_t deadline = now_ns() + 100000000LL;
for (int i = 0; db && i < db->n_planes; i++) {
if (db->fd[i] < 0) continue;
struct pollfd p = {.fd = db->fd[i], .events = POLLIN};
for (;;) {
const int64_t left = deadline - now_ns();
const int r = poll(&p, 1, left > 0 ? (int)((left + 999999) / 1000000) : 0);
if (r >= 0 || errno != EINTR || left <= 0) break;
}
}
}
static void surface_state_discard(struct surface_state *st) {
struct wl_resource *cb, *tmp;
wl_list_remove(&st->buffer_destroy.link);
wl_resource_for_each_safe(cb, tmp, &st->frames) wl_resource_destroy(cb);
feedback_discard_all(&st->feedback);
free(st);
}
static void surface_state_merge(struct surface_state *older, struct surface_state *newer) {
if (older->attach && !newer->attach) {
newer->attach = 1;
newer->buffer = older->buffer;
wl_list_remove(&older->buffer_destroy.link);
wl_list_init(&older->buffer_destroy.link);
if (newer->buffer) {
newer->buffer_destroy.notify = on_state_buffer_destroyed;
wl_resource_add_destroy_listener(newer->buffer, &newer->buffer_destroy);
}
wl_list_insert_list(&newer->feedback, &older->feedback);
wl_list_init(&older->feedback);
} else if (older->attach) {
if (older->buffer && older->buffer != newer->buffer) send_buffer_release(older->buffer);
g_pace.replaced += feedback_discard_all(&older->feedback);
}
if (older->src_set && !newer->src_set) {
newer->src_set = 1;
memcpy(newer->src, older->src, sizeof(newer->src));
}
if (older->dst_set && !newer->dst_set) {
newer->dst_set = 1;
memcpy(newer->dst, older->dst, sizeof(newer->dst));
}
if (older->opaque_set && !newer->opaque_set) {
newer->opaque_set = 1;
memcpy(newer->opaque, older->opaque, sizeof(newer->opaque));
}
for (int i = 0; i < older->damage_buf.n; i++)
note_damage(&newer->damage_buf, older->damage_buf.r[i][0], older->damage_buf.r[i][1],
older->damage_buf.r[i][2], older->damage_buf.r[i][3]);
for (int i = 0; i < older->damage_local.n; i++)
note_damage(&newer->damage_local, older->damage_local.r[i][0], older->damage_local.r[i][1],
older->damage_local.r[i][2], older->damage_local.r[i][3]);
wl_list_insert_list(&newer->frames, &older->frames);
wl_list_init(&older->frames);
surface_state_discard(older);
}
static void surface_wait_stop(struct surface *s) {
if (s->waiting_source) wl_event_source_remove(s->waiting_source);
if (s->waiting_timer) wl_event_source_remove(s->waiting_timer);
if (s->waiting_fd >= 0) close(s->waiting_fd);
s->waiting_source = s->waiting_timer = NULL;
s->waiting_fd = -1;
}
static void surface_wait_end(struct surface *s, int over_limit) {
struct surface_state *st = s->waiting;
if (!st) return;
surface_wait_stop(s);
s->waiting = NULL;
const int64_t waited = now_ns() - s->waiting_since_ns;
g_perf.commit_waits++;
g_perf.commit_wait_ns += waited;
if (waited > g_perf.commit_wait_max_ns) g_perf.commit_wait_max_ns = waited;
if (over_limit) g_perf.commit_wait_limits++;
if (st->attach && g_unwaited == s) g_unwaited = NULL;
surface_state_apply(s, st);
free(st);
}
static int on_commit_ready(int fd, uint32_t mask, void *data) {
surface_wait_end(data, 0);
return 0;
}
static int on_commit_wait_limit(void *data) {
static int said;
if (!said) {
said = 1;
droiddeck_log("compositor", "a client's GPU writes ran past %d ms; its frame is shown as it is", COMMIT_WAIT_LIMIT_MS);
}
surface_wait_end(data, 1);
return 0;
}
static int surface_wait_start(struct surface *s, int fd, int timeout_ms) {
struct wl_event_loop *loop = wl_display_get_event_loop(g_display);
s->waiting_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
if (s->waiting_fd >= 0) {
s->waiting_source = wl_event_loop_add_fd(loop, s->waiting_fd, WL_EVENT_READABLE, on_commit_ready, s);
s->waiting_timer = wl_event_loop_add_timer(loop, on_commit_wait_limit, s);
}
if (!s->waiting_source || !s->waiting_timer ||
wl_event_source_timer_update(s->waiting_timer, timeout_ms) != 0) {
surface_wait_stop(s);
return -1;
}
return 0;
}
static void surface_commit(struct wl_client *c, struct wl_resource *r) {
struct surface *s = wl_resource_get_user_data(r);
if (s->xdg_toplevel && !s->toplevel_committed) {
s->toplevel_committed = 1;
send_toplevel_configure(s);
}
struct surface_state *st = calloc(1, sizeof(*st));
if (!st) {
struct surface_state now;
surface_state_take(s, &now);
surface_state_apply(s, &now);
return;
}
surface_state_take(s, st);
const int was_waiting = s->waiting != NULL;
if (was_waiting) {
surface_wait_stop(s);
surface_state_merge(s->waiting, st);
s->waiting = NULL;
}
int unwaited;
const int fd = state_unfinished_fd(s, st, &unwaited);
if (!was_waiting) s->waiting_since_ns = now_ns();
const int64_t left_ms = COMMIT_WAIT_LIMIT_MS - (now_ns() - s->waiting_since_ns) / 1000000;
if (fd >= 0 && left_ms > 0 && surface_wait_start(s, fd, (int)left_ms) == 0) {
s->waiting = st;
return;
}
const int attaches = st->attach;
if (was_waiting) {
s->waiting = st;
surface_wait_end(s, fd >= 0 && left_ms <= 0);
} else {
surface_state_apply(s, st);
free(st);
}
if (unwaited) g_unwaited = s;
else if (attaches && g_unwaited == s) g_unwaited = NULL;
}
static void surface_set_buffer_transform(struct wl_client *c, struct wl_resource *r, int32_t t) {}
static void surface_set_buffer_scale(struct wl_client *c, struct wl_resource *r, int32_t s) {}
static void surface_damage_buffer(struct wl_client *c, struct wl_resource *r,
@@ -1516,6 +1737,13 @@ static void surface_resource_destroy(struct wl_resource *r) {
child->parent = NULL;
}
if (s->pending_buffer) wl_list_remove(&s->pending_buffer_destroy.link);
if (s->waiting) {
surface_wait_stop(s);
surface_state_discard(s->waiting);
s->waiting = NULL;
}
if (g_zero_copy_shown == s) g_zero_copy_shown = NULL;
if (g_unwaited == s) g_unwaited = NULL;
pending_releases_forget_surface(s);
drop_dmabuf(s, 0);
ahb_swapchain_surface_gone(s);
@@ -1579,6 +1807,7 @@ static void compositor_create_surface(struct wl_client *c, struct wl_resource *r
wl_list_init(&s->child_link);
wl_list_init(&s->toplevel_link);
wl_list_init(&s->pending_buffer_destroy.link);
s->waiting_fd = -1;
wl_list_init(&s->idle_buffer_destroy.link);
wl_list_insert(&g_surfaces, &s->link);
wl_resource_set_implementation(s->resource, &surface_impl, s, surface_resource_destroy);
@@ -2502,7 +2731,13 @@ static int64_t scene_next_due(int64_t now, int64_t due, int limit) {
static void render_scene(void) {
g_scene_due_ns = scene_next_due(now_ns(), g_scene_due_ns, g_fps_limit);
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
if (atomic_load(&g_stream_on)) {
g_dirty_since_ns = 0;
g_zero_copy_shown = NULL;
settle_unwaited();
render_stream();
return;
}
struct draw_list dl = {0};
struct surface *s;
int w, h;
@@ -2576,6 +2811,8 @@ static void render_scene(void) {
} else {
cursor_hdr_said = 0;
}
g_zero_copy_shown = NULL;
if (hdr_route == 1 || hdr_route == 2) settle_unwaited();
if (hdr_route == 1) {
static int fell_back;
vkp_apply_window_request();
@@ -2609,6 +2846,7 @@ static void render_scene(void) {
}
if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
!ahb_only) {
settle_unwaited();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
} else if (hdr_route == 0 || hdr_route == 3) {
const int pass_on = fx_on || framegen;
@@ -2658,6 +2896,7 @@ static void render_scene(void) {
vkp_apply_window_request();
int r = -1;
const int fg_pass = framegen && fx_on && li >= 0;
if (framegen && li >= 0) settle_unwaited();
const int generated = (framegen && li >= 0)
? sc_layer_present_generated(&dl.d[li], 1, NULL, w, h, fg_pass,
ls ? droiddeck_surface_color(ls) : NULL) : 0;
@@ -2671,6 +2910,8 @@ static void render_scene(void) {
r = generated >= 0 ? 0 : -1;
else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf))
r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld);
if (r == 0 && !fg_pass) g_zero_copy_shown = ls;
else settle_unwaited();
if (!fg_pass && generated >= 0 && r != 0 && li >= 0)
r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h)
: sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL);
@@ -2681,6 +2922,7 @@ static void render_scene(void) {
ov = sc_layer_present_overlay(dl.d[li + 1].img, go, dl.d[li + 1].blend) == 0 ? 1 : -1;
if (ov <= 0) sc_layer_hide_overlay();
if (ov < 0) {
settle_unwaited();
sc_layer_hide();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
copy = 1;
@@ -2690,12 +2932,14 @@ static void render_scene(void) {
g_scene_queues = sc_layer_queues();
}
} else {
settle_unwaited();
sc_layer_hide();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
copy = 1;
hdr_copy = "its display layer was unavailable this frame";
}
} else {
settle_unwaited();
sc_layer_hide();
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
copy = 1;
@@ -4344,11 +4588,12 @@ static int on_stats_timer(void *data) {
unsigned aimed_next, aimed_later, aimed_even;
sc_layer_aim_take(&aimed_next, &aimed_later, &aimed_even);
#define PERF_MS(sum, n) ((n) ? (double)(sum) / 1e6 / (double)(n) : 0.0)
if (g_perf.scenes || vp.presents || g_perf.releases || drops)
if (g_perf.scenes || vp.presents || g_perf.releases || drops || g_perf.commit_waits)
droiddeck_log("perf", "last 10 s: %u ticks, %u scenes, %u on screen (copy %u, zero-copy %u, layer copy %u) | "
"render_scene %.2f/%.2f ms | base %u black kept, %u presented | acquire %.2f/%.2f ms | "
"present %.2f/%.2f ms (%u) | fence wait %.2f/%.2f ms (%u, %u GPU release waits) | "
"release %.2f/%.2f ms (%u, %u held) | %u pool drops | layer frames timed for the next refresh %u, "
"release %.2f/%.2f ms (%u, %u held) | commits held for client writes %.2f/%.2f ms (%u, %u past the limit) | "
"%u pool drops | layer frames timed for the next refresh %u, "
"the one after %u, held to an even step %u",
g_perf.ticks, g_perf.scenes, g_stat_frames, g_perf.copy_scenes, zero_copy, layer_frames,
PERF_MS(g_perf.scene_ns, g_perf.scenes), (double)g_perf.scene_max_ns / 1e6,
@@ -4357,7 +4602,9 @@ static int on_stats_timer(void *data) {
PERF_MS(vp.present_ns, vp.presents), (double)vp.present_max_ns / 1e6, vp.presents,
PERF_MS(vp.wait_ns, vp.waits), (double)vp.wait_max_ns / 1e6, vp.waits, vp.gpu_release_waits,
PERF_MS(g_perf.release_ns, g_perf.releases), (double)g_perf.release_max_ns / 1e6,
g_perf.releases, g_perf.releases_held, drops, aimed_next, aimed_later, aimed_even);
g_perf.releases, g_perf.releases_held,
PERF_MS(g_perf.commit_wait_ns, g_perf.commit_waits), (double)g_perf.commit_wait_max_ns / 1e6,
g_perf.commit_waits, g_perf.commit_wait_limits, drops, aimed_next, aimed_later, aimed_even);
#undef PERF_MS
memset(&g_perf, 0, sizeof(g_perf));
}
@@ -232,6 +232,16 @@ static VkResult timed_wait(VkFence fence, uint64_t timeout) {
return g_dev_state == -2 ? VK_ERROR_DEVICE_LOST : VK_ERROR_UNKNOWN;
int64_t t0 = perf_now();
VkResult r = g_vk.WaitForFences(g_dev, 1, &fence, VK_TRUE, timeout);
if (r == VK_TIMEOUT) {
droiddeck_log("gpu", "GPU fence delayed: retaining frame resources until completion");
/* A scheduling delay does not invalidate the device. Keep this submission's
* resources and call stack alive, as the main render path already does. */
do {
r = g_vk.WaitForFences(g_dev, 1, &fence, VK_TRUE, UINT64_MAX);
} while (r == VK_TIMEOUT);
if (r == VK_SUCCESS)
droiddeck_log("gpu", "GPU fence completed: continuing presentation");
}
perf_add(&g_perf.wait_ns, &g_perf.wait_max_ns, &g_perf.waits, perf_now() - t0);
if (r != VK_SUCCESS && r != VK_ERROR_DEVICE_LOST)
quarantine_pending_work(r, "fence wait");
@@ -430,21 +430,28 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
*/
private fun useMaliFallback(missing: String?): String {
val oldVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(activity)
val venus = oldVulkan == null && com.droiddeck.launcher.session.VenusComponent.available(activity)
val venusByUser = venusExplicit()
val venus = MaliAutoRoute.venusStandsIn(
com.droiddeck.launcher.session.VenusComponent.available(activity), oldVulkan == null,
SessionPrefs.venus(activity), venusByUser, gpu.name,
)
if (oldVulkan != null) Log.i(TAG, "auto: Mali driver reports Vulkan $oldVulkan; Venus needs 1.2, the bridge stands in")
val ownership = MaliAutoRoute.fallbackOwnership(
venus,
SessionPrefs.vkBridge(activity), bridgeExplicit(),
SessionPrefs.venus(activity), venusExplicit(),
SessionPrefs.venus(activity), venusByUser,
)
if (venus && !SessionPrefs.venus(activity)) {
SessionPrefs.setVenus(activity, true)
if (SessionPrefs.vkBridge(activity) && !bridgeExplicit())
SessionPrefs.setVkBridge(activity, false)
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
} else if (!venus && !SessionPrefs.vkBridge(activity)) {
SessionPrefs.setVkBridge(activity, true)
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
} else if (!venus) {
val venusOff = SessionPrefs.venus(activity) && !venusByUser
val bridgeOn = !SessionPrefs.vkBridge(activity)
if (venusOff) SessionPrefs.clearVenus(activity)
if (bridgeOn) SessionPrefs.setVkBridge(activity, true)
if (venusOff || bridgeOn || ownership != MaliAutoRoute.NONE) SessionPrefs.setMaliFallbackByAuto(activity, ownership)
} else if (ownership != MaliAutoRoute.NONE) {
SessionPrefs.setMaliFallbackByAuto(activity, ownership)
}
@@ -467,7 +474,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
/** A pair is installed for this Mali: the route Auto switched on in its place goes off again. */
private fun endMaliFallback() {
when (SessionPrefs.maliFallbackByAuto(activity)) {
"venus" -> SessionPrefs.setVenus(activity, false)
"venus" -> SessionPrefs.clearVenus(activity)
"bridge" -> SessionPrefs.setVkBridge(activity, false)
else -> return
}
@@ -1129,7 +1129,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
Thread({
val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added)
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(app, game, added)
ui.post {
onHandled()
if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) {
@@ -1138,7 +1138,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
if (command == null) {
launchCoordinator.releaseHandling(request)
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
val message = if (game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) {
R.string.game_link_battlenet_missing
} else {
R.string.game_link_failed
}
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
return@post
}
com.droiddeck.launcher.session.NoSteamLaunch.remember(command)
@@ -1993,11 +1998,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
val askAllFiles = Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.files.AllFilesAccess.missing() &&
!SessionPrefs.allFilesAsked(this)
if (savedInstanceState == null) {
if (!askAllFiles) ui.post { startSteamAtStartupIfEnabled(cold = true) }
}
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled(cold = true) }
saved?.let { state ->
restoreCompatLaunch(state)
pendingSwitch = savedIntent(state, KEY_PENDING_SWITCH)
@@ -2005,13 +2006,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
val wanted = ArrayList<String>()
if (Build.VERSION.SDK_INT >= 30) {
// From targetSdk 30, shared storage outside the app's own folders is all-files access or nothing.
if (askAllFiles) {
SessionPrefs.setAllFilesAsked(this)
com.droiddeck.launcher.files.AllFilesAccess.open(this)
}
} else if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// From Android 11, shared storage outside the app's own folders is all-files access, which the file picker asks for when a shared drive is opened.
if (Build.VERSION.SDK_INT < 30 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
wanted.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
if (SessionPrefs.micEnabled(this) && !SessionPrefs.micAsked(this)
@@ -2020,6 +2016,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.setMicAsked(this)
}
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
com.droiddeck.launcher.session.Onboarding.onFirstRunReady = firstRunReady
Thread({ com.droiddeck.launcher.stores.StoreAccounts.encryptAll(this) }, "store-credentials").start()
if (!SessionState.running) Thread({
com.droiddeck.launcher.session.LogMigration.run(this)
@@ -2299,7 +2296,22 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
return super.dispatchGenericMotionEvent(event)
}
@Volatile private var inFront = false
private var autoSteamPending = false
/** Runs on the worker thread that finishes setup, so the foreground state is read as setup completes, not when the UI thread gets to it. */
private val firstRunReady: () -> Unit = {
val front = inFront
runOnUiThread { if (front) autoStartSteam() }
}
private fun autoStartSteam() {
if (isFinishing || isDestroyed || SessionState.running || !inFront) return
if (busy) autoSteamPending = true else playSteam()
}
override fun onPause() {
inFront = false
stopRightStickScroll()
compatLaunchVisible = false
if (android.os.Build.VERSION.SDK_INT >= 29) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, true)
@@ -2308,6 +2320,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onResume() {
super.onResume()
inFront = true
if (!homeChoiceOpen) {
HomeApp.releaseUnusedHomeEntry(this)
refreshHomeAppState()
@@ -2443,6 +2456,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onDestroy() {
// The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too.
if (com.droiddeck.launcher.session.Onboarding.onFirstRunReady === firstRunReady) com.droiddeck.launcher.session.Onboarding.onFirstRunReady = null
queuedLaunchRunner.destroy()
triggerKeys.cancel()
launchCoordinator.cancelAll()
@@ -3742,6 +3756,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
refresh()
com.droiddeck.launcher.agent.AgentHost.refresh(this)
if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() }
if (autoSteamPending) { autoSteamPending = false; autoStartSteam() }
}
}, "runtime-operation").start()
}
@@ -26,6 +26,12 @@ internal object MaliAutoRoute {
fun userChoice(keyStored: Boolean, owner: String, route: String): Boolean = keyStored && owner != route
fun venusStandsIn(available: Boolean, hostVulkanOk: Boolean, venusOn: Boolean, venusExplicit: Boolean, gpuName: String): Boolean =
available && hostVulkanOk && if (venusExplicit) venusOn else !venusStallsOn(gpuName)
// Steam's web helper dies on its first window through Venus on these (#2879), so the bridge stands in.
fun venusStallsOn(gpuName: String): Boolean = gpuName.contains("G2-Ultra", ignoreCase = true)
fun shouldEnd(ownsRoute: String, mali: Boolean, installedPair: Boolean): Boolean =
mali && installedPair && ownsRoute != NONE
}
@@ -3888,7 +3888,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
else -> return super.dispatchGenericMotionEvent(event)
}
if (com.droiddeck.launcher.input.PointerCapture.isMouse(event) && !drawerOpen) {
if ((event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) ||
event.isFromSource(android.view.InputDevice.SOURCE_TOUCHPAD)) && !drawerOpen) {
if (appUiOwnsPointer()) {
if (super.dispatchGenericMotionEvent(event)) return true
if (touchEditorOpen) return false
@@ -5400,7 +5401,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun handleTouch(event: MotionEvent): Boolean {
val pen = PenStream.penIndex(event)
val penRouted = if (pen >= 0) routePen(event, pen).takeIf { it != PenRouter.Route.TOUCH } else null
if (penRouted == null && com.droiddeck.launcher.input.PointerCapture.isMouse(event)) return onMouse(event)
if (penRouted == null && (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) ||
event.isFromSource(android.view.InputDevice.SOURCE_TOUCHPAD))) return onMouse(event)
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
sessionTouchDown = true
@@ -6832,8 +6834,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun onBottomGameHover(event: MotionEvent): Boolean {
val pen = PenStream.penIndex(event)
if (pipUi) return false
if (pen < 0) return onBottomGameMouse(event)
if (pipUi || pen < 0) return false
return when (routePen(event, pen)) {
PenRouter.Route.TOUCH -> false
PenRouter.Route.PEN -> {
@@ -6845,16 +6846,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
private fun onBottomGameMouse(event: MotionEvent): Boolean {
if (PenStream.penIndex(event) >= 0 || !com.droiddeck.launcher.input.PointerCapture.isMouse(event)) return false
notePress(event)
onMouse(event)
return true
}
private fun onBottomGameTouch(event: MotionEvent): Boolean {
if (pipUi) return true
if (onBottomGameMouse(event)) return true
if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN) && PenStream.penIndex(event) < 0) return false
notePress(event)
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
@@ -61,7 +61,19 @@ object GameEnvironment {
}
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else knownGames[scope].orEmpty() + config.games[scope].orEmpty()
/**
* What some Steam games need here whatever the shared settings say; the game's own settings still win.
* GTA III dies at 0042A703 when a new game starts with FEX's reduced x87 precision, as the Rockstar store copy does.
*/
val knownGames: Map<String, Map<String, String?>> = mapOf(
"12100" to mapOf("FEX_X87REDUCEDPRECISION" to "0"),
)
/** [config] with [knownGames] folded under each game's own settings, for the guest to read. */
fun withKnownGames(config: Config): Config =
config.copy(games = config.games + knownGames.mapValues { (scope, known) -> known + config.games[scope].orEmpty() })
fun hasOverride(config: Config, scope: String, name: String): Boolean =
scope.isNotEmpty() && config.entries(scope).containsKey(name)
@@ -78,7 +90,7 @@ object GameEnvironment {
val entries = config.games[scope].orEmpty()
if (FexPreset.environmentKeys.none(entries::containsKey)) return null
return FexPreset.all.firstOrNull { preset ->
val expected = FexPreset.environment(preset.id)
val expected = presetFor(scope, preset.id)
FexPreset.environmentKeys.all { key -> entries.containsKey(key) && entries[key] == expected[key] }
}?.id ?: CUSTOM_FEX_PRESET
}
@@ -88,12 +100,16 @@ object GameEnvironment {
require(preset == null || FexPreset.all.any { it.id == preset })
val entries = config.entries(scope).filterKeys { it !in FexPreset.environmentKeys }.toMutableMap()
if (preset != null) {
val values = FexPreset.environment(preset)
val values = presetFor(scope, preset)
FexPreset.environmentKeys.forEach { key -> entries[key] = values[key] }
}
return config.withEntries(scope, entries)
}
/** A FEX preset as a game gets it: picking one never undoes a fix the game is known to need. */
private fun presetFor(scope: String, preset: String): Map<String, String?> =
FexPreset.environment(preset) + knownGames[scope].orEmpty().filterKeys { it in FexPreset.environmentKeys }
const val CUSTOM_FEX_PRESET = "__custom__"
val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER)
@@ -8,9 +8,18 @@ import android.os.Environment
import android.provider.Settings
object AllFilesAccess {
private val VOLUME = Regex("^(/storage/emulated/\\d+|/storage/[^/]+|/sdcard)(/.*)?$")
private val APP_FOLDERS = listOf("/Android/data", "/Android/obb")
fun missing(sdk: Int = Build.VERSION.SDK_INT, granted: () -> Boolean = { Environment.isExternalStorageManager() }): Boolean =
sdk >= Build.VERSION_CODES.R && !granted()
/** Whether reading [path] takes all-files access: shared storage, outside the per-app folders directly under a volume's root, which Android always lets the app use. */
fun covers(path: String): Boolean {
val inside = VOLUME.matchEntire(path)?.groupValues?.get(2) ?: return false
return APP_FOLDERS.none { inside == it || inside.startsWith("$it/") }
}
fun open(context: Context) {
val app = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + context.packageName))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -504,13 +504,15 @@ fun FileManagerScreen(
}
val drives = remember(storageTick) { StorageRoots.list(context) }
var accessDrive by remember { mutableStateOf<String?>(null) }
var accessWasMissing by remember { mutableStateOf(AllFilesAccess.missing()) }
var accessDeclined by remember { mutableStateOf(false) }
fun unreadable(drive: StorageRoot) {
if (AllFilesAccess.missing()) accessDrive = drive.label
else Toast.makeText(context, context.getString(R.string.fm_drive_not_readable, drive.label), Toast.LENGTH_SHORT).show()
}
accessDrive?.let { label ->
OutlinedAlertDialog(
onDismissRequest = { accessDrive = null },
onDismissRequest = { accessDrive = null; accessDeclined = true },
title = { Text(stringResource(R.string.fm_drive_access_title, label)) },
text = { Text(stringResource(R.string.fm_drive_access_text)) },
confirmButton = {
@@ -519,9 +521,17 @@ fun FileManagerScreen(
AllFilesAccess.open(context)
}, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.upd_open_settings)) }
},
dismissButton = { TextButton(onClick = { accessDrive = null }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
dismissButton = { TextButton(onClick = { accessDrive = null; accessDeclined = true }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } },
)
}
LaunchedEffect(currentDir, storageTick) {
if (!AllFilesAccess.missing()) {
if (accessWasMissing) { accessWasMissing = false; loadDirectory(currentDir, resetScroll = false, record = false) }
} else {
accessWasMissing = true
if (!accessDeclined && accessDrive == null && AllFilesAccess.covers(currentDir.path)) accessDrive = drives.firstOrNull { currentDir.path.startsWith(it.dir.path) }?.label ?: context.getString(R.string.fm_drive_internal)
}
}
val linuxRoot = remember(storageTick) {
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
}
@@ -42,8 +42,8 @@ object GameRemoval {
val folder = game.gameFiles ?: return null
val store = Store.byId(game.source)
val id = game.storeId
if (store != null && id != null) StoresState.installedGame(store, id)?.let { return it }
val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.isInstalled } ?: return null
if (store != null && id != null) StoresState.installedGame(store, id, folder)?.let { return it }
val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.isInstalled && it.store == store && it.id == id } ?: return null
return InstalledStoreGame(sidecar, folder)
}
@@ -59,7 +59,7 @@ public final class PadBridge {
private final PadState[] playerStates = new PadState[SLOTS];
private final float[][] rawSticks = new float[SLOTS][4];
private final Map<Integer, Boolean> rightStickLayouts = new HashMap<>();
private final boolean[][] keyTriggers = new boolean[SLOTS][2];
private final TriggerKey[][] keyTriggers = TriggerKey.slots(SLOTS);
private final int[] retainedSticks = new int[SLOTS];
private final PadState effectiveState = new PadState();
private final PadState homeGuideReport = new PadState();
@@ -484,7 +484,7 @@ public final class PadBridge {
stateFor(slot).clear();
retainedSticks[slot] = 0;
Arrays.fill(rawSticks[slot], 0f);
Arrays.fill(keyTriggers[slot], false);
for (TriggerKey key : keyTriggers[slot]) key.reset();
}
private void mutateState(java.util.function.Consumer<PadState> mutation) {
@@ -570,26 +570,76 @@ public final class PadBridge {
return true;
}
static float keyTrigger(float current, boolean pressed, int repeatCount, boolean analog, boolean[] held, int side) {
static final class TriggerKey {
static final float RELEASE_FROM_PEAK = 0.05f;
boolean held;
boolean handoff;
boolean axisLive;
boolean axisMovedWhilePressed;
float peak;
float axis;
static TriggerKey[][] slots(int count) {
TriggerKey[][] keys = new TriggerKey[count][2];
for (TriggerKey[] pair : keys) {
pair[0] = new TriggerKey();
pair[1] = new TriggerKey();
}
return keys;
}
void reset() {
held = false;
handoff = false;
axisLive = false;
axisMovedWhilePressed = false;
peak = 0f;
axis = 0f;
}
}
static float keyTrigger(float current, boolean pressed, int repeatCount, boolean analog, TriggerKey[] keys, int side) {
TriggerKey key = keys[side];
if (repeatCount > 0) return current;
if (!analog) {
held[side] = pressed;
key.held = pressed;
return pressed ? 1f : 0f;
}
if (pressed) {
if (current != 0f) return current;
held[side] = true;
key.axisMovedWhilePressed = false;
if (key.axisLive || current != 0f) return current;
key.held = true;
return 1f;
}
if (!held[side]) return current;
held[side] = false;
if (!key.axisMovedWhilePressed) key.axisLive = false;
if (key.handoff) {
key.handoff = false;
return key.axis;
}
if (!key.held) return current;
key.held = false;
return 0f;
}
static float axisTrigger(float value, boolean[] held, int side) {
if (!held[side]) return value;
if (value == 0f) return 1f;
held[side] = false;
static float axisTrigger(float value, TriggerKey[] keys, int side) {
TriggerKey key = keys[side];
key.axis = value;
if (value != 0f) {
key.axisLive = true;
key.axisMovedWhilePressed = true;
}
if (key.held) {
if (value == 0f) return 1f;
key.held = false;
key.handoff = true;
key.peak = value;
return 1f;
}
if (key.handoff) {
key.peak = Math.max(key.peak, value);
if (value > key.peak - TriggerKey.RELEASE_FROM_PEAK) return 1f;
key.handoff = false;
}
return value;
}
@@ -10,9 +10,6 @@ object PointerCapture {
fun isTouchpad(event: MotionEvent): Boolean = event.isFromSource(InputDevice.SOURCE_TOUCHPAD)
fun isMouse(event: MotionEvent): Boolean =
event.isFromSource(InputDevice.SOURCE_MOUSE) || event.isFromSource(InputDevice.SOURCE_TOUCHPAD)
fun delta(event: MotionEvent): FloatArray {
var dx = event.x
var dy = event.y
@@ -23,7 +23,6 @@ object BattleNet {
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC", product = "wow_anniversary", flavor = "_anniversary_"),
Title("wow_forever", "World of Warcraft: Forever", "WoWF", shop = "world-of-warcraft-forever", product = "wowf", flavor = "_forever_"),
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii", product = "d3"),
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii", product = "s2"),
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered", product = "s1"),
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone", product = "hsb"),
@@ -56,10 +55,26 @@ object BattleNet {
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
)
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
// d3cn is not a store card of its own any more; it resolves to the Diablo III title through CN_UIDS.
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.code != "WoWC" }
// Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity.
private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs")
/**
* Blizzard's China client installs some products under a CN uid; they are the same games and keep their store
* identity. Only the launch code and the product served by the China repository can differ.
*/
private class Cnv(val uid: String, val code: String? = null, val product: String? = null)
private val CN_UIDS = mapOf(
"s2_cn" to Cnv("s2", product = "s2c"),
"osic" to Cnv("osi", product = "osic"),
"anbs_cn" to Cnv("anbs"),
"d3cn" to Cnv("diablo3", "D3CN", "d3cn"),
)
private fun cn(alias: Cnv): Title? = TITLES.firstOrNull { it.uid == alias.uid }?.let { title ->
if (alias.code == null && alias.product == null) title
else Title(title.uid, title.name, alias.code ?: title.code, title.steam, title.shop, alias.product ?: title.product, title.flavor)
}
fun notInstalled(title: Title, installedIds: Collection<String?>) =
installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code }
@@ -75,7 +90,7 @@ object BattleNet {
private val coverLock = Any()
fun fetchCovers(context: Context, titles: List<Title> = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" }): Boolean = synchronized(coverLock) {
fun fetchCovers(context: Context, titles: List<Title> = TITLES.distinctBy { it.code }): Boolean = synchronized(coverLock) {
val art = com.droiddeck.launcher.frontend.AddedGameArt
val key = com.droiddeck.launcher.frontend.SteamGridDb.key(context)
var got = false
@@ -162,10 +177,10 @@ object BattleNet {
internal fun title(uid: String): Title? {
val id = uid.lowercase()
TITLES.firstOrNull { it.uid == id }?.let { return it }
CN_UIDS[id]?.let { alias -> TITLES.firstOrNull { it.uid == alias }?.let { return it } }
CN_UIDS[id]?.let { return cn(it) }
val base = id.substringBeforeLast('_', "")
if (base.isEmpty() || id.substringAfterLast('_') !in LOCALES) return null
return TITLES.firstOrNull { it.uid == base } ?: CN_UIDS[base]?.let { alias -> TITLES.firstOrNull { it.uid == alias } }
return TITLES.firstOrNull { it.uid == base } ?: CN_UIDS[base]?.let { cn(it) }
}
internal fun titleForProduct(product: String): Title? {
@@ -202,6 +217,114 @@ object BattleNet {
}
}
/**
* The launch code of the copy installed in [folder]. The store card's code is not enough:
* a China client installs Diablo III under `D3CN` while the store title is `D3`.
*/
fun launchCode(context: Context, uid: String, folder: File?): String? {
if (folder == null) return runCatching { games(context) }.getOrNull()?.let { launchCode(it, uid, null) }
if (!folder.isDirectory) return null
return runCatching { installedRegistrationAt(context, uid, folder) }.getOrNull()?.second?.code
}
/**
* Two uids name the same store title: the China aliases fold into the store uid, and fen/fenris
* share one product under uids of their own.
*/
internal fun sameTitle(left: String, right: String): Boolean {
val a = title(left)
val b = title(right)
if (a == null || b == null) return left.equals(right, ignoreCase = true)
return a.uid == b.uid || (a.code == b.code && a.product != null && a.product == b.product)
}
/** False when a registration source exists but cannot be read: "no game here" is not a fact then. */
internal fun registrationsReadable(context: Context): Boolean {
val pfx = File(prefix(context), "pfx")
val agent = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
val registry = File(pfx, "system.reg")
if (agent.exists() && runCatching { productDbRegistrations(agent.readBytes()) }.getOrNull() == null) return false
if (registry.isFile && runCatching { registry.useLines { uninstallEntries(it) } }.isFailure) return false
return true
}
internal fun launchCode(games: List<Game>, uid: String, folder: File?): String? {
val canonical = title(uid)?.uid ?: uid
val same = games.filter { it.uid == canonical }
if (folder != null) return same.firstOrNull { it.folder.absolutePath == folder.absolutePath }?.code
return same.singleOrNull()?.code ?: title(uid)?.code
}
internal fun installedRegistrationAt(context: Context, id: String, folder: File): Pair<String, Title>? {
if (!folder.isDirectory) return null
val pfx = File(prefix(context), "pfx")
val agentFile = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
val registryFile = File(pfx, "system.reg")
val bytes = if (agentFile.exists()) agentFile.readBytes() else null
val registrations = if (bytes != null) productDbRegistrations(bytes) ?: return null else emptyList()
val agent = bytes?.let(::productDbInstalls).orEmpty()
val registry = if (registryFile.exists()) registryFile.useLines { uninstallEntries(it) } else emptyList()
// Agent rows take precedence for a UID, including unfinished installs.
// Registry-only titles remain valid when Agent has no corresponding row.
val registeredUids = registrations.map { it.uid.lowercase() }.toSet()
val candidates = agent + registry.filter { (uid, _) ->
uid.lowercase() !in registeredUids
}.map { AgentInstall(it.first, it.second, "") }
return candidates.firstNotNullOfOrNull { row ->
val found = title(row.uid) ?: titleForProduct(row.product) ?: return@firstNotNullOfOrNull null
if (!sameTitle(found.uid, id)) return@firstNotNullOfOrNull null
val registered = hostFolder(context, row.path) ?: return@firstNotNullOfOrNull null
if (registered.absolutePath != folder.absolutePath &&
(found.flavor != folder.name || registered.absolutePath != folder.parentFile?.absolutePath)
) return@firstNotNullOfOrNull null
row.uid to found
}
}
/** A registration for any title in this tree makes recursive deletion unsafe. */
internal fun folderHasRegistrations(context: Context, folder: File): Boolean? = runCatching {
val pfx = File(prefix(context), "pfx")
val agentFile = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
val registryFile = File(pfx, "system.reg")
val agent = if (agentFile.exists()) productDbRegistrations(agentFile.readBytes()) ?: return null else emptyList()
val registry = if (registryFile.exists()) registryFile.useLines { uninstallEntries(it) } else emptyList()
val target = folder.canonicalFile.toPath()
(agent.map { it.path } + registry.map { it.second }).any { path ->
val registered = hostFolder(context, path)?.canonicalFile?.toPath() ?: return null
registered.startsWith(target)
}
}.getOrNull()
internal fun registrationsAt(context: Context, id: String, folder: File): List<String>? {
val pfx = File(prefix(context), "pfx")
val agentFile = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
val registryFile = File(pfx, "system.reg")
val agent = if (!agentFile.exists()) emptyList()
else runCatching { productDbRegistrations(agentFile.readBytes()) }.getOrNull() ?: return null
val registry = if (!registryFile.exists()) emptyList()
else runCatching { registryFile.useLines { uninstallEntries(it) } }.getOrNull() ?: return null
val products = agent.filter { it.product.isNotEmpty() }.associate { it.uid.lowercase() to it.product }
val requested = title(id)
val flavor = requested?.flavor
val folders = buildSet {
add(folder.absolutePath)
if (flavor != null && folder.name == flavor) folder.parentFile?.let { add(it.absolutePath) }
}
if (agent.any { it.uid.isEmpty() && hostFolder(context, it.path)?.absolutePath in folders }) return null
val agentFolders = agent.filter { it.uid.isNotEmpty() }.groupBy { it.uid.lowercase() }.mapValues { (_, rows) ->
rows.mapNotNull { hostFolder(context, it.path)?.absolutePath }.toSet()
}
val registryRows = registry.filter { (uid, _) ->
val recorded = agentFolders[uid.lowercase()] ?: return@filter true
recorded.any { it in folders }
}
return (registryRows + agent.map { it.uid to it.path }).mapNotNull { (uid, path) ->
if (hostFolder(context, path)?.absolutePath !in folders) return@mapNotNull null
val title = title(uid) ?: products[uid.lowercase()]?.let(::titleForProduct)
if (title != null && sameTitle(title.uid, id)) uid else null
}.distinct()
}
internal fun ownFolders(games: Map<String, Pair<Title, File>>, saved: Map<String, String?>): Map<String, File> {
val out = HashMap<String, File>()
val taken = HashSet<File>()
@@ -317,6 +440,25 @@ object BattleNet {
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>>? = productDbInstalls(bytes)?.map { it.uid to it.path }
/**
* Every registration, including the one an unfinished install or update leaves behind:
* `productDbInstalls()` drops entries whose installed flag is 0, which is the state a
* cancelled download is in while its folder already holds data.
*/
internal fun productDbRegistrations(bytes: ByteArray): List<AgentInstall>? {
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 } ?: return null
return installs.mapNotNull { (_, start, end) ->
runCatching {
val install = fields(bytes, start, end)
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
val product = install.firstOrNull { it.first == 2 }?.let { String(bytes, it.second, it.third - it.second) }.orEmpty()
val path = install.firstOrNull { it.first == 3 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
?.let { String(bytes, it.second, it.third - it.second) }
if (path.isNullOrEmpty()) null else AgentInstall(uid.orEmpty(), path, product)
}.getOrElse { return null }
}
}
internal fun productDbInstalls(bytes: ByteArray): List<AgentInstall>? {
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrNull()?.filter { it.first == 1 }?.takeIf { it.isNotEmpty() } ?: return null
return installs.map { (_, start, end) ->
@@ -112,8 +112,9 @@ object NativeGuest {
File(BwrapSpawner.hostPath(binds.map { BwrapSpawner.Bind.parse(it) }, root.path, cwd)).takeIf { it.isDirectory } ?: root
/** A process for [guest] (argv) started as proot would with [binds], in guest directory [cwd]. */
fun processBuilder(context: Context, root: File, binds: List<String>, guest: List<String>, cwd: String = "/root"): ProcessBuilder =
ProcessBuilder(command(root, guest.first(), guest.drop(1)))
fun processBuilder(context: Context, root: File, binds: List<String>, guest: List<String>, cwd: String = "/root"): ProcessBuilder {
if (sessionMode == null) prepare(context, root)
return ProcessBuilder(command(root, guest.first(), guest.drop(1)))
.directory(workingDirectory(root, binds, cwd))
.also { builder ->
builder.environment().apply {
@@ -121,6 +122,7 @@ object NativeGuest {
putAll(sessionEnvironment(root, binds, guest.first(), SessionPrefs.guestHostname(context)))
}
}
}
private const val RUNPATH_CONF = "etc/ld.so.conf.d/zz-droiddeck-native.conf"
private val SCAN_DIRS = listOf("usr/lib", "usr/local/lib", "opt")
@@ -149,6 +151,7 @@ object NativeGuest {
}
/** What a rootfs needs before anything runs in it natively; cheap once done. */
@Synchronized
fun prepare(context: Context, root: File) {
val relinked = relinkAbsoluteSymlinks(context, root)
if (relinked > 0) android.util.Log.i(TAG, "native userland: $relinked absolute symlinks made relative")
@@ -114,7 +114,7 @@ object GameEnvironmentStore {
) {
publishGameCores(context)
val stored = config ?: read(context)
val resolved = stored.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
val resolved = GameEnvironment.withKnownGames(stored).copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
val json = encode(resolved)
val dxvk = TextureFiltering.dxvkOptions(
SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context),
@@ -38,11 +38,13 @@ object NoSteamLaunch {
else -> null
}?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) }
fun battleNetTitleScope(context: Context, code: String): String? =
AddedGames.scan(context).firstOrNull { game ->
fun battleNetTitleScope(context: Context, code: String): String? {
val games = runCatching { com.droiddeck.launcher.runtime.BattleNet.games(context) }.getOrDefault(emptyList())
return AddedGames.scan(context).firstOrNull { game ->
game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id &&
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.code == code
game.storeId?.let { com.droiddeck.launcher.runtime.BattleNet.launchCode(games, it, game.folder) } == code
}?.let { settingsId(it).toString() }
}
fun resolution(config: GameEnvironment.Config, scope: String?, output: Pair<Int, Int>): Pair<Int, Int>? {
val choice = scope?.let { GameEnvironment.gameResolution(config, it) } ?: return null
@@ -54,10 +56,11 @@ object NoSteamLaunch {
private fun viaBattleNet(game: Library.SteamGame): Boolean =
game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id
fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
fun command(context: Context, game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name)
viaBattleNet(game) ->
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.let { Command(BATTLENET, listOf("launch", it.code), game.name) }
game.storeId?.let { com.droiddeck.launcher.runtime.BattleNet.launchCode(context, it, game.gameFiles) }
?.let { Command(BATTLENET, listOf("launch", it), game.name) }
game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) }
game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name)
else -> null
@@ -29,6 +29,10 @@ object Onboarding {
/** The setup screens belong to the first run; later runtime, Proton and Steam client updates keep the usual Play button. */
val firstRun = MutableStateFlow(true)
/** Called once, when this process finishes the first-run downloads itself; not when everything was already in place. */
@Volatile var onFirstRunReady: (() -> Unit)? = null
@Volatile private var worked = false
fun attach(context: Context) {
appContext = context.applicationContext
val prefs = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
@@ -52,8 +56,10 @@ object Onboarding {
private fun markFirstRunDone() {
val context = appContext ?: return
val live = firstRun.value && worked
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply()
firstRun.value = false
if (live) onFirstRunReady?.invoke()
}
/** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */
@@ -90,6 +96,7 @@ object Onboarding {
}
fun report(step: Step, label: String, percent: Int) {
worked = true
failed.value = failed.value - step
active.value = active.value + (step to Progress(label, percent))
keepAlive()
@@ -35,6 +35,7 @@ object SessionFiles {
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
"usr/share/applications/droiddeck-return-gaming.desktop" to "usr/share/applications/droiddeck-return-gaming.desktop",
"etc/xdg/fastfetch/config.jsonc" to "etc/xdg/fastfetch/config.jsonc",
)
@@ -960,12 +960,6 @@ object SessionPrefs {
fun micAsked(context: Context): Boolean = prefs(context).getBoolean("micAsked", false)
fun allFilesAsked(context: Context): Boolean = prefs(context).getBoolean("allFilesAsked", false)
fun setAllFilesAsked(context: Context) {
prefs(context).edit().putBoolean("allFilesAsked", true).apply()
}
fun bluetoothAsked(context: Context): Boolean = prefs(context).getBoolean("bluetoothAsked", false)
fun setBluetoothAsked(context: Context) {
@@ -1235,6 +1229,11 @@ object SessionPrefs {
prefs(context).edit().putBoolean("venus", on).apply()
}
/** Venus off with no choice stored, so that Auto turning it off does not read as the user's own choice. */
fun clearVenus(context: Context) {
prefs(context).edit().remove("venus").apply()
}
fun setVkBridge(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("vkBridge", on).putBoolean("bridgeFellBack", false).apply()
}
@@ -79,6 +79,7 @@ object StoresState {
fun refresh(context: Context) {
val app = context.applicationContext
com.droiddeck.launcher.stores.download.SavedQueue.restore(app)
com.droiddeck.launcher.stores.battlenet.BattleNetInstall.reconcile(app)
if (refreshRequests.getAndIncrement() > 0) return
var seen = 0
background("stores-refresh", onFailure = { if (refreshRequests.getAndSet(0) > seen) main.post { refresh(app) } }) {
@@ -103,6 +104,8 @@ object StoresState {
accountsLoaded = true
}
com.droiddeck.launcher.stores.gog.GogMaintenance.checkInstalled(app, onDisk)
onDisk.filter { it.sidecar.store == Store.BATTLENET }
.forEach { com.droiddeck.launcher.stores.battlenet.BattleNetInstall.checkUpdate(app, it) }
}
} while (!refreshRequests.compareAndSet(seen, 0))
}
@@ -121,6 +124,8 @@ object StoresState {
var unfinished by mutableStateOf<List<StoreInstallRoot.Unfinished>>(emptyList())
internal set
var steamPicking by mutableStateOf<CatalogItem?>(null)
fun isUnfinished(item: CatalogItem): Boolean = unfinished.any {
it.store == item.store && (it.id == item.id || (it.id == null && it.folder.name == StoreInstallRoot.folderName(item.title, item.id)))
}
@@ -135,7 +140,16 @@ object StoresState {
StoreInstalls.discard(app, folder, listOf(java.io.File(folder, ".chunks"), java.io.File(folder, ".gog_chunks"), StoreInstallRoot.scratchDir(app, item.store, item.id)))
}
fun installedGame(store: Store, id: String): InstalledStoreGame? = installed.firstOrNull { it.sidecar.store == store && it.sidecar.id == id }
fun installedGame(store: Store, id: String, folder: java.io.File? = null): InstalledStoreGame? =
pickInstalled(store, id, folder, installed)
internal fun pickInstalled(
store: Store, id: String, folder: java.io.File?, candidates: List<InstalledStoreGame>,
): InstalledStoreGame? {
val matches = candidates.filter { it.sidecar.store == store && it.sidecar.id == id }
if (folder != null) return matches.firstOrNull { it.folder.absolutePath == folder.absolutePath }
return matches.firstOrNull()
}
fun detailItem(store: Store, id: String): CatalogItem? = detailCatalogItem(
store, id, library[store].orEmpty(),
@@ -334,9 +348,13 @@ object StoresState {
private fun uninstallHeld(app: Context, game: InstalledStoreGame, key: String, onDone: () -> Unit) {
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
main.post { uninstalling.remove(key); onDone() }
return
if (game.sidecar.store == Store.BATTLENET) {
val listed = com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }
// A registration we could not read is not the same as no registration: keep the folder.
if (listed || com.droiddeck.launcher.runtime.BattleNet.folderHasRegistrations(app, game.folder) != false) {
main.post { uninstalling.remove(key); onDone() }
return
}
}
StoreInstalls.uninstall(app, game, progress = { f -> main.post { if (key in uninstalling) uninstalling[key] = f } }, removed = {
main.post {
@@ -0,0 +1,129 @@
package com.droiddeck.launcher.stores.battlenet
import android.content.Context
import android.util.Log
import org.json.JSONObject
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
/**
* A cancelled Battle.net install that could not be cleaned up yet. The marker is written before
* the cleanup starts and removed only after the registration and the folder are both gone, so a
* restart can reconcile a registration that the client writes late.
*/
internal object BattleNetCleanup {
private const val TAG = "BattleNetCleanup"
private const val DIR = "battlenet-cleanup"
internal const val ACTIVE = "active"
internal const val PENDING = "pending"
internal const val WATCHING = "watching"
internal data class Pending(
val folder: File,
val id: String,
val createdFolder: Boolean,
val state: String,
val attempts: Int,
val nextAt: Long,
val stamp: Long,
)
internal fun dir(context: Context): File = File(context.filesDir, DIR)
@Synchronized
internal fun mark(context: Context, folder: File, id: String, createdFolder: Boolean, state: String = ACTIVE) {
val current = get(context, folder)
write(
context,
Pending(folder, id, createdFolder || current?.createdFolder == true, state, current?.attempts ?: 0, current?.nextAt ?: 0L, System.nanoTime()),
)
}
@Synchronized
internal fun markActive(context: Context, folder: File, id: String, createdFolder: Boolean) {
val current = get(context, folder)
write(
context,
Pending(
folder, id, createdFolder || current?.createdFolder == true,
current?.state?.takeIf { it != ACTIVE } ?: ACTIVE,
current?.attempts ?: 0, current?.nextAt ?: 0L, System.nanoTime(),
),
)
}
@Synchronized
internal fun update(context: Context, folder: File, state: String, attempts: Int, nextAt: Long) {
val current = get(context, folder) ?: return
write(context, current.copy(state = state, attempts = attempts, nextAt = nextAt))
}
@Synchronized
internal fun get(context: Context, folder: File): Pending? {
val file = file(context, folder)
val json = runCatching { JSONObject(file.readText()) }.getOrNull() ?: return null
return runCatching {
Pending(
folder = File(json.getString("folder")),
id = json.getString("id"),
createdFolder = json.optBoolean("createdFolder"),
state = json.optString("state", PENDING),
attempts = json.optInt("attempts"),
nextAt = json.optLong("nextAt"),
stamp = json.optLong("stamp"),
)
}.getOrNull()
}
internal fun pending(context: Context): List<Pending> = dir(context).listFiles()
?.filter { it.isFile && it.name.endsWith(".json") }
?.mapNotNull { file -> runCatching { JSONObject(file.readText()) }.getOrNull() }
?.mapNotNull { json ->
runCatching {
Pending(
folder = File(json.getString("folder")),
id = json.getString("id"),
createdFolder = json.optBoolean("createdFolder"),
state = json.optString("state", PENDING),
attempts = json.optInt("attempts"),
nextAt = json.optLong("nextAt"),
stamp = json.optLong("stamp"),
)
}.getOrNull()
}
?.filter { it.state != ACTIVE }
?.sortedBy { it.nextAt }
.orEmpty()
@Synchronized
internal fun clear(context: Context, folder: File) {
file(context, folder).delete()
}
private fun file(context: Context, folder: File) =
File(dir(context), MessageDigest.getInstance("SHA-256").run {
update(folder.absolutePath.toByteArray())
digest().joinToString("") { "%02x".format(it.toInt() and 0xff) }
} + ".json")
private fun write(context: Context, pending: Pending) {
val target = file(context, pending.folder)
target.parentFile?.mkdirs()
val json = JSONObject().apply {
put("folder", pending.folder.absolutePath)
put("id", pending.id)
put("createdFolder", pending.createdFolder)
put("state", pending.state)
put("attempts", pending.attempts)
put("nextAt", pending.nextAt)
put("stamp", pending.stamp)
}
val tmp = File(target.parentFile, "${target.name}.tmp")
runCatching {
tmp.writeText(json.toString())
Files.move(tmp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING)
}.onFailure { Log.w(TAG, "could not write ${target.path}", it) }
}
}
@@ -12,11 +12,13 @@ import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.SavedQueue
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
@@ -35,7 +37,10 @@ object BattleNetInstall {
private const val CN = "cn"
private const val BUILD_INFO = ".build.info"
private const val CHECK_AGAIN_MS = 30 * 60_000L
private const val CHECK_RETRY_MS = 30_000L
private const val CHECK_RETRY_MAX = 2
private const val START_WAIT_MS = 60_000L
private val reconciling = AtomicBoolean(false)
/** Blizzard serves China from battlenet.com.cn; its global version hostnames do not answer for that region. */
internal fun versionsUrl(region: String, product: String): String =
@@ -49,11 +54,32 @@ object BattleNetInstall {
internal val checks = Executors.newSingleThreadExecutor { r -> Thread(r, "battlenet-updates") }
internal val checkedAt = HashMap<String, Long>()
private val checkAttempts = java.util.concurrent.ConcurrentHashMap<String, Int>()
private val checkRetry = Executors.newSingleThreadScheduledExecutor { r ->
Thread(r, "battlenet-update-retry").apply { isDaemon = true }
}
/** Test seams: the version service and the delayed re-check. */
internal var fetchVersions: (String) -> String = ::fetch
internal var scheduleRecheck: (() -> Unit, Long) -> Unit = { body, delay ->
checkRetry.schedule(Runnable { body() }, delay, TimeUnit.MILLISECONDS)
}
val updates = mutableStateMapOf<String, Boolean>()
fun updateKey(id: String, folder: File?): String = "$id@${folder?.absolutePath ?: ""}"
fun product(id: String): String? = BattleNet.title(id)?.product
/** The China client serves StarCraft II, Diablo II and Diablo III from products of their own; anbs_cn shares anbs. */
private val CN_PRODUCTS = mapOf(
"osi" to "osic",
"s2" to "s2c",
"diablo3" to "d3cn",
)
internal fun chinaProduct(id: String): String? = CN_PRODUCTS[id]
fun headless(item: CatalogItem): Boolean = item.store == Store.BATTLENET && product(item.id) != null
internal fun locale(locale: Locale): String {
@@ -87,19 +113,31 @@ object BattleNetInstall {
fun enqueue(context: Context, item: CatalogItem, folder: File, update: Boolean = false) {
val app = context.applicationContext
val recorded = item.extra[PREEXISTING]
val tagged = if (recorded == "0" || recorded == "1") item
else item.copy(extra = item.extra + (PREEXISTING to "pending"))
val entry = DownloadEntry(
Store.BATTLENET, item.id, item.title, cover = item.tallImageUrl ?: item.imageUrl,
Store.BATTLENET, tagged.id, tagged.title, cover = tagged.tallImageUrl ?: tagged.imageUrl,
location = StoreInstallRoot.labelFor(app, folder),
cleanupKey = "${Store.BATTLENET.id}:${tagged.id}",
)
DownloadQueue.enqueue(app, entry) { BattleNetInstaller(app, item, folder, update) }
val ownership = Ownership(tagged)
DownloadQueue.enqueue(app, entry, onAccepted = {
SavedQueue.remember(app, tagged, folder.parentFile?.parentFile)
}) { BattleNetInstaller(app, tagged, folder, update, ownership) }
}
fun update(context: Context, game: InstalledStoreGame) {
val app = context.applicationContext
Thread({
val item = updateItem(game, installUid(app, game))
game.folder.parentFile?.parentFile?.let { com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, it) }
enqueue(app, item, game.folder, update = true)
val uid = installUid(app, game)
if (uid == null) {
Log.w(TAG, "no Battle.net install matches ${game.folder}")
StoresState.logLine("Battle.net: no registration matches ${game.folder.name}; update it from Battle.net")
StoresState.post { updates.remove(updateKey(game.sidecar.id, game.folder)) }
} else {
enqueue(app, updateItem(game, uid), game.folder, update = true)
}
}, "battlenet-update").start()
}
@@ -111,17 +149,120 @@ object BattleNetInstall {
internal fun updateFolder(item: CatalogItem): File? = item.extra[UPDATE_FOLDER]?.let(::File)
internal const val INSTALL_UID = "installUid"
internal const val PREEXISTING = "preexisting"
internal const val UPDATE_FOLDER = "updateFolder"
internal const val STALLED = "stalled"
internal fun installUid(context: Context, game: InstalledStoreGame): String =
runCatching { BattleNet.games(context).firstOrNull { it.uid == game.sidecar.id }?.installUid }.getOrNull() ?: game.sidecar.id
/** The registration of this folder: games() keeps one copy per launch code, so a second copy is not in it. */
internal fun installUid(context: Context, game: InstalledStoreGame): String? =
runCatching { BattleNet.installedRegistrationAt(context, game.sidecar.id, game.folder) }.getOrNull()?.first
fun uninstall(context: Context, game: InstalledStoreGame): Boolean {
if (product(game.sidecar.id) == null || !BattleNet.installed(context)) return false
val done = agentUninstall(context, installUid(context, game))
if (done) StoresState.post { StoresState.notifyLibraryChanged(context.applicationContext) }
return done
val uid = installUid(context, game) ?: return false
val done = agentUninstall(context, uid)
val gone = registrationsGone(context, game.sidecar.id, game.folder, UNINSTALL_VERIFY_MS)
if (gone == null || gone.isNotEmpty()) {
Log.w(TAG, "uninstall $uid: the registration in ${game.folder.path} is still there")
return false
}
if (!done) Log.i(TAG, "uninstall $uid: registration gone after the Agent stopped")
BattleNetCleanup.clear(context, game.folder)
StoresState.post { StoresState.notifyLibraryChanged(context.applicationContext) }
return true
}
internal fun registrationsGone(context: Context, id: String, folder: File, timeoutMs: Long): List<String>? {
val deadline = System.currentTimeMillis() + timeoutMs
while (true) {
val found = runCatching { BattleNet.registrationsAt(context, id, folder) }.getOrNull() ?: return null
if (found.isEmpty() || System.currentTimeMillis() >= deadline) return found
Thread.sleep(250)
}
}
/**
* Retries the markers a cancelled install leaves when the registration it wrote is still
* present, or when it wrote one after the cancellation had already looked.
*/
fun reconcile(context: Context) {
val app = context.applicationContext
if (BattleNetCleanup.pending(app).isEmpty()) return
if (!reconciling.compareAndSet(false, true)) return
Thread({
try {
reconcileNow(app)
} finally {
reconciling.set(false)
}
}, "battlenet-cleanup-reconcile").start()
}
internal fun reconcileNow(
context: Context,
uninstall: (String) -> Boolean = { agentUninstall(context, it) },
verifyMs: Long = CLEANUP_VERIFY_MS,
watchMs: Long = CLEANUP_WATCH_MS,
) {
val now = System.currentTimeMillis()
for (pending in BattleNetCleanup.pending(context)) {
if (pending.nextAt > now) continue
if (pending.folder.absolutePath in cleanupRunning) continue
if (StoreInstalls.isDiscarding(pending.folder)) continue
val key = DownloadEntry(Store.BATTLENET, pending.id, pending.id).key
if (!DownloadQueue.holdForRemoval(key)) continue
try {
val current = BattleNetCleanup.get(context, pending.folder)
if (current == null || current.stamp != pending.stamp || current.id != pending.id ||
current.createdFolder != pending.createdFolder || current.state != pending.state ||
current.attempts != pending.attempts || current.nextAt != pending.nextAt
) continue
val found = runCatching { BattleNet.registrationsAt(context, pending.id, pending.folder) }.getOrNull()
if (found == null) {
retry(context, pending, "the registrations could not be read")
continue
}
if (found.isEmpty()) {
if (pending.createdFolder && pending.folder.exists() && (BattleNet.folderHasRegistrations(context, pending.folder) != false || !deleteFolder(pending.folder))) {
retry(context, pending, "the folder could not be deleted")
continue
}
if (pending.state == BattleNetCleanup.WATCHING && pending.attempts < CLEANUP_MAX_ATTEMPTS) {
BattleNetCleanup.update(context, pending.folder, BattleNetCleanup.WATCHING, pending.attempts + 1, now + watchMs)
continue
}
BattleNetCleanup.clear(context, pending.folder)
Log.i(TAG, "cleanup of ${pending.folder.path}: no registration remains")
continue
}
for (uid in found) uninstall(uid)
val left = registrationsGone(context, pending.id, pending.folder, verifyMs)
if (left == null || left.isNotEmpty()) {
retry(context, pending, "the registration in ${pending.folder.path} is still there")
continue
}
if (pending.createdFolder && pending.folder.exists() && (BattleNet.folderHasRegistrations(context, pending.folder) != false || !deleteFolder(pending.folder))) {
retry(context, pending, "the folder could not be deleted")
continue
}
BattleNetCleanup.clear(context, pending.folder)
Log.i(TAG, "cleanup of ${pending.folder.path}: ${if (pending.createdFolder) "removed" else "registration removed; folder kept"}")
} finally {
DownloadQueue.releaseRemoval(key)
}
}
}
private fun retry(context: Context, pending: BattleNetCleanup.Pending, reason: String) {
val attempts = pending.attempts + 1
val delay = if (attempts >= CLEANUP_MAX_ATTEMPTS) 10 * 60_000L else CLEANUP_RETRY_MS
BattleNetCleanup.update(context, pending.folder, pending.state, attempts, System.currentTimeMillis() + delay)
Log.w(TAG, "cleanup of ${pending.folder.path} is pending: $reason")
}
internal fun deleteFolder(folder: File): Boolean {
com.droiddeck.launcher.core.FileUtils.delete(folder)
return !folder.exists()
}
internal fun agentUninstall(context: Context, uid: String): Boolean {
@@ -175,21 +316,40 @@ object BattleNetInstall {
internal fun check(id: String, folder: File, force: Boolean) {
val product = product(id) ?: return
val key = updateKey(id, folder)
val now = System.currentTimeMillis()
synchronized(checkedAt) {
if (!force && now - (checkedAt[id] ?: 0L) < CHECK_AGAIN_MS) return
checkedAt[id] = now
if (!force && now - (checkedAt[key] ?: 0L) < CHECK_AGAIN_MS) return
// A new regular check starts a new retry cycle; a forced re-check does not.
if (!force) checkAttempts.remove(key)
checkedAt[key] = now
}
fun retryLater(reschedule: Boolean = false) {
synchronized(checkedAt) { if (checkedAt[key] == now) checkedAt.remove(key) }
StoresState.post { updates.remove(key) }
if (!reschedule) return
// A build that changed while the request ran can be checked again, but only a few times.
val attempt = checkAttempts.merge(key, 1) { old, _ -> old + 1 } ?: 1
if (attempt > CHECK_RETRY_MAX) return
scheduleRecheck({
Log.i(TAG, "$id: the build changed while checking; asking the version service again")
check(id, folder, force = true)
}, CHECK_RETRY_MS * attempt)
}
fun retryLater() = synchronized(checkedAt) { if (checkedAt[id] == now) checkedAt.remove(id) }
checks.execute {
val local = runCatching { buildKey(File(folder, BUILD_INFO).readText()) }.getOrNull()
?: return@execute retryLater()
val latest = runCatching { latestBuild(fetch(versionsUrl(local.first, product)), local.first) }
.onFailure { Log.w(TAG, "versions of $product: ${it.javaClass.simpleName}") }.getOrNull()
val served = if (local.first == CN) chinaProduct(id) ?: product else product
val latest = runCatching { latestBuild(fetchVersions(versionsUrl(local.first, served)), local.first) }
.onFailure { Log.w(TAG, "versions of $served: ${it.javaClass.simpleName}") }.getOrNull()
?: return@execute retryLater()
val behind = latest != local.second
val current = runCatching { buildKey(File(folder, BUILD_INFO).readText()) }.getOrNull()
?: return@execute retryLater()
if (current != local) return@execute retryLater(reschedule = true)
val behind = latest != current.second
Log.i(TAG, "$id: ${if (behind) "update available" else "up to date"}")
StoresState.post { if (behind) updates[id] = true else updates.remove(id) }
StoresState.post { if (behind) updates[key] = true else updates.remove(key) }
checkAttempts.remove(key)
}
}
@@ -232,22 +392,53 @@ object BattleNetInstall {
private const val APPLY_PHASE = 2000
}
internal class Ownership(item: CatalogItem) {
@Volatile var known = item.extra[BattleNetInstall.PREEXISTING] in setOf("0", "1")
@Volatile var preexisting = item.extra[BattleNetInstall.PREEXISTING] == "1"
val createdFolder = AtomicBoolean(false)
}
internal class BattleNetInstaller(
private val app: Context,
private val item: CatalogItem,
private val folder: File,
private val update: Boolean,
private val ownership: Ownership = Ownership(item),
private val registrationWaitMs: Long = REGISTRATION_WAIT_MS,
private val cleanupVerifyMs: Long = CLEANUP_VERIFY_MS,
private val uninstall: (String) -> Boolean = { BattleNetInstall.agentUninstall(app, it) },
private val registration: () -> List<String>? = {
BattleNet.registrationsAt(app, item.id, folder)
},
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private val cleanupStarted = AtomicBoolean(false)
private val started = AtomicBoolean(false)
private val queueKey = DownloadEntry(Store.BATTLENET, item.id, item.title).key
private val ended = java.util.concurrent.CountDownLatch(1)
private var before = 0L
private var kept = -1L
override fun run(handle: DownloadQueue.JobHandle): String? {
if (!cancelled.get() && !ownership.known) {
val found = runCatching { registration() }.getOrNull()
ownership.preexisting = found == null || found.isNotEmpty()
ownership.known = found != null
if (found != null) {
SavedQueue.remember(
app,
item.copy(extra = item.extra + (BattleNetInstall.PREEXISTING to if (ownership.preexisting) "1" else "0")),
folder.parentFile?.parentFile,
)
}
}
started.set(true)
try {
return if (cancelled.get()) null else work(handle)
} catch (t: Throwable) {
if (!cancelled.get()) BattleNetCleanup.clear(app, folder)
throw t
} finally {
ended.countDown()
}
@@ -260,7 +451,10 @@ internal class BattleNetInstaller(
val title = BattleNet.title(item.id)
val product = title?.product ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, item.id))
val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: title.uid
if (!update) folder.mkdirs()
if (!update && folder.mkdirs()) {
ownership.createdFolder.set(true)
BattleNetCleanup.markActive(app, folder, item.id, createdFolder = true)
}
val guest = AddedGames.guestPath(app, folder) ?: throw IllegalStateException(app.getString(R.string.bnet_dl_failed, folder.path))
val (country, region) = BattleNetInstall.country(Locale.getDefault())
val args = if (update) listOf("agent-update", uid)
@@ -282,10 +476,11 @@ internal class BattleNetInstaller(
if (done == null) throw IllegalStateException(BattleNetInstall.failure(app, reason, code))
handle.log("Battle.net: ${item.title} ${if (update) "updated" else "installed"} ${done?.optString("version").orEmpty()}".trimEnd())
StoresState.post {
BattleNetInstall.updates.remove(item.id)
BattleNetInstall.updates.remove(BattleNetInstall.updateKey(item.id, folder))
StoresState.notifyLibraryChanged(app)
}
BattleNetInstall.check(item.id, folder, force = true)
BattleNetCleanup.clear(app, folder)
return folder.absolutePath
}
@@ -302,17 +497,109 @@ internal class BattleNetInstaller(
}
}
/**
* The client writes the install registration a little after the download starts; a cancel
* right after the request would otherwise read an empty list and leave the registration behind.
*/
private fun registrationsWaiting(): List<String>? {
val deadline = System.currentTimeMillis() + registrationWaitMs
while (true) {
val found = runCatching { registration() }.getOrNull() ?: return null
if (found.isNotEmpty() || System.currentTimeMillis() >= deadline) return found
Thread.sleep(250)
}
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (!deleteFiles || update) return
val uid = item.extra[BattleNetInstall.INSTALL_UID] ?: BattleNet.title(item.id)?.uid ?: return
Thread({
if (started.get() && !ended.await(END_WAIT_S, TimeUnit.SECONDS)) Log.w("BattleNetInstall", "the cancelled install of $uid is still stopping")
val gone = BattleNetInstall.agentUninstall(app, uid)
if (folder.isDirectory && (gone || folder.list().isNullOrEmpty())) com.droiddeck.launcher.core.FileUtils.delete(folder)
Log.i("BattleNetInstall", "cancelled install of $uid: ${if (gone) "removed" else "left for Battle.net to remove"}")
}, "battlenet-cancel").start()
if (!deleteFiles || update) {
if (update) DownloadQueue.cleanupFinished(queueKey)
return
}
if (!cleanupStarted.compareAndSet(false, true)) return
if (!started.get() && !ownership.known) ownership.preexisting = true
val initialCreated = BattleNetCleanup.get(app, folder)?.createdFolder ?: ownership.createdFolder.get()
val path = folder.absolutePath
cleanupRunning.add(path)
if (!ownership.preexisting) {
BattleNetCleanup.mark(app, folder, item.id, initialCreated, BattleNetCleanup.PENDING)
}
val cleanup = Thread({
var discarding = false
try {
val stopped = !started.get() || ended.await(END_WAIT_S, TimeUnit.SECONDS)
val createdFolder = ownership.createdFolder.get() || (BattleNetCleanup.get(app, folder)?.createdFolder ?: false)
if (!ownership.preexisting && createdFolder != initialCreated) {
BattleNetCleanup.mark(app, folder, item.id, createdFolder, BattleNetCleanup.PENDING)
}
if (ownership.preexisting) {
BattleNetCleanup.clear(app, folder)
Log.i("BattleNetInstall", "cancelled install left the pre-existing registration in ${folder.path}")
} else if (!stopped) {
pending(createdFolder, "the cancelled install is still stopping")
} else {
StoreInstalls.beginDiscard(folder)
discarding = true
val created = registrationsWaiting()
if (created == null) {
pending(createdFolder, "the registrations could not be read")
} else if (created.isEmpty()) {
if (createdFolder && (BattleNet.folderHasRegistrations(app, folder) != false || !BattleNetInstall.deleteFolder(folder))) {
pending(createdFolder, "the folder could not be deleted")
} else {
BattleNetCleanup.mark(app, folder, item.id, createdFolder, BattleNetCleanup.WATCHING)
BattleNetCleanup.update(app, folder, BattleNetCleanup.WATCHING, 0, System.currentTimeMillis() + CLEANUP_WATCH_MS)
Log.i("BattleNetInstall", "cancelled install of ${item.id}: no registration yet; watching ${folder.path}")
}
} else {
for (uid in created.distinct()) uninstall(uid)
val left = registrationsGoneHere(cleanupVerifyMs)
if (left == null || left.isNotEmpty()) {
pending(createdFolder, "the registration in ${folder.path} is still there")
} else if (createdFolder && (BattleNet.folderHasRegistrations(app, folder) != false || !BattleNetInstall.deleteFolder(folder))) {
pending(createdFolder, "the folder could not be deleted")
} else {
BattleNetCleanup.clear(app, folder)
Log.i("BattleNetInstall", "cancelled install of ${created.first()}: ${if (createdFolder) "removed" else "registration removed; folder kept"}")
}
}
}
} finally {
cleanupRunning.remove(path)
if (discarding) StoreInstalls.endDiscard(folder)
DownloadQueue.cleanupFinished(queueKey)
}
}, "battlenet-cancel")
try {
cleanup.start()
} catch (t: Throwable) {
cleanupRunning.remove(path)
DownloadQueue.cleanupFinished(queueKey)
throw t
}
}
private fun pending(createdFolder: Boolean, reason: String) {
BattleNetCleanup.mark(app, folder, item.id, createdFolder, BattleNetCleanup.PENDING)
BattleNetCleanup.update(app, folder, BattleNetCleanup.PENDING, 1, System.currentTimeMillis() + CLEANUP_RETRY_MS)
Log.w("BattleNetInstall", "cleanup of ${folder.path} is pending: $reason")
}
private fun registrationsGoneHere(timeoutMs: Long): List<String>? {
val deadline = System.currentTimeMillis() + timeoutMs
while (true) {
val found = runCatching { registration() }.getOrNull() ?: return null
if (found.isEmpty() || System.currentTimeMillis() >= deadline) return found
Thread.sleep(250)
}
}
}
private const val END_WAIT_S = 120L
private const val REGISTRATION_WAIT_MS = 5_000L
private val cleanupRunning = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
private const val CLEANUP_VERIFY_MS = 30_000L
private const val CLEANUP_WATCH_MS = 15_000L
private const val CLEANUP_RETRY_MS = 60_000L
private const val CLEANUP_MAX_ATTEMPTS = 4
private const val UNINSTALL_VERIFY_MS = 30_000L
@@ -24,7 +24,6 @@ internal object BlizzardArt {
"WoWC" to "${KEY_ART_ASSETS}blt6a80c8e7260f84f2/690d2219b415dd246153245b/BCC.png",
"WoWF" to "${KEY_ART_ASSETS}blt1d58537e928b17c5/6ae2c99668c747dd1b4f558b/WoW_Forever_AnimatedTrailerSupportAssets_BnetShop_1920x1080.png",
"D3" to "${KEY_ART_CATALOG}/f96/8d92f4d8bd316d3787f02d8a86935d6a-Store_Product_960x540_D3.jpg",
"D3CN" to "${KEY_ART_CATALOG}/f96/8d92f4d8bd316d3787f02d8a86935d6a-Store_Product_960x540_D3.jpg",
"S2" to "${KEY_ART_ASSETS}blt4b6d6857f147a6de/61254804841f180993fedb61/6885-32192.png",
"S1" to "${KEY_ART_ASSETS}blt03d69a4563a6ae63/6a34b50f799ece2cb2da248c/9458-28298.jpg",
"WTCG" to "${KEY_ART_ASSETS}blt5a3d84e1d0b2bbcf/662aea9f842cecfd4fd95327/HS_Key_Art_SG2.png",
@@ -34,6 +34,7 @@ data class DownloadEntry(
val interruptible: Boolean = true,
val reusedBytes: Long = 0L,
val appliedBytes: Long = 0L,
val cleanupKey: String? = null,
) {
fun passed(s: DownloadStage): Boolean = state == DownloadState.INSTALLED || (stagesPassed and (1 shl s.ordinal)) != 0
@@ -107,6 +107,7 @@ object DownloadQueue {
}
private val lock = Any()
private val cancelling = HashSet<String>()
private val items = LinkedHashMap<String, Item>()
private val heldPaused = HashSet<String>()
private val removing = HashSet<String>()
@@ -114,7 +115,9 @@ object DownloadQueue {
fun holdForRemoval(key: String): Boolean = synchronized(lock) {
val item = items[key]
if (item?.entry?.isActive == true || item?.job != null || key in cleaningUp || key in removing) return@synchronized false
if (item?.entry?.isActive == true || item?.job != null || key in cleaningUp || key in removing || key in cancelling) {
return@synchronized false
}
removing.add(key)
true
}
@@ -127,7 +130,7 @@ object DownloadQueue {
return synchronized(lock) {
while (true) {
val busy = busyLocked(key)
if (!busy && key !in cleaningUp && key !in removing) break
if (!busy && key !in cleaningUp && key !in removing && key !in cancelling) break
val left = deadline - android.os.SystemClock.uptimeMillis()
if (busy && left <= 0) return@synchronized false
(lock as Object).wait(if (busy) left else 0L)
@@ -192,14 +195,31 @@ object DownloadQueue {
fun isActive(key: String): Boolean = entry(key)?.isActive == true
fun isCancelling(key: String): Boolean = synchronized(lock) { key in cancelling }
internal fun cleanupFinished(key: String?) {
if (key == null) return
synchronized(lock) {
cancelling.remove(key)
(lock as Object).notifyAll()
}
}
fun anyActive(): Boolean = synchronized(lock) { items.values.any { it.entry.isActive } }
fun enqueue(context: Context, entry: DownloadEntry, factory: () -> DownloadJob) {
fun enqueue(context: Context, entry: DownloadEntry, onAccepted: (() -> Unit)? = null, factory: () -> DownloadJob): Boolean {
val app = context.applicationContext
synchronized(lock) {
if (entry.key in removing) { Log.i(TAG, "${entry.key}: being uninstalled"); return }
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return } }
val cleanupKey = entry.cleanupKey
if (cleanupKey != null && isCancelling(cleanupKey)) {
Log.i(TAG, "${entry.key}: previous cancellation is still cleaning up")
return false
}
if (entry.key in removing) { Log.i(TAG, "${entry.key}: being uninstalled"); return false }
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return false } }
items.remove(entry.key)
// The callback records the task's ownership snapshot; run it before advance() can see the item.
onAccepted?.invoke()
val state = if (heldPaused.remove(entry.key)) DownloadState.PAUSED else DownloadState.QUEUED
items[entry.key] = Item(entry.copy(state = state, stage = DownloadStage.MANIFEST, startedAt = System.currentTimeMillis()), factory)
renumber()
@@ -207,6 +227,7 @@ object DownloadQueue {
StoresState.logLine("${entry.store.label}: queued \"${entry.name}\"" + if (entry.bytesTotal > 0) " (${com.droiddeck.launcher.stores.formatBytes(entry.bytesTotal)})" else "")
publish(app)
advance(app)
return true
}
fun recordFailed(context: Context, entry: DownloadEntry, error: String, retry: (() -> Unit)? = null) {
@@ -274,26 +295,39 @@ object DownloadQueue {
val app = context.applicationContext
val item: Item
val wasRunning: Boolean
var cleanupKey: String? = null
var cleanup = false
var awaitDeletion: List<Thread> = emptyList()
synchronized(lock) {
item = items[key] ?: return
if (!item.entry.interruptible) return
val candidate = item.entry.cleanupKey?.takeIf { item.factory != null }
if (candidate != null && !cancelling.add(candidate)) {
Log.i(TAG, "$key: already cancelling")
return
}
cleanupKey = candidate
wasRunning = item.entry.state == DownloadState.RUNNING
if (wasRunning) {
item.pauseRequested = false
item.cancelled.set(true)
val deleting = StoreInstalls.collectingDiscards { runCatching { item.job?.cancel(deleteFiles = true) } }
val deleting = StoreInstalls.collectingDiscards {
if (runCatching { item.job?.cancel(deleteFiles = true) }.isFailure) cleanupFinished(cleanupKey)
}
if (deleting.isNotEmpty()) { holdCleanup(key); awaitDeletion = deleting }
}
if (!wasRunning) {
cleanup = beginCleanup(key)
if (!cleanup) cleanupFinished(cleanupKey)
item.entry = item.entry.copy(state = DownloadState.CANCELLED, queuePosition = 0, finishedAt = System.currentTimeMillis())
renumber()
publishLocked()
}
}
if (cleanup) {
cleanUpLater(app, key, "store-dl-cancel") { runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }
if (!wasRunning && cleanup) {
cleanUpLater(app, key, "store-dl-cancel") {
if (runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) }.isFailure) cleanupFinished(cleanupKey)
}
}
if (awaitDeletion.isNotEmpty()) cleanUpLater(app, key, "store-dl-cancel-wait") { awaitDeletion.forEach { it.join() } }
StoresState.logLine("cancelled \"${item.entry.name}\"")
@@ -303,17 +337,27 @@ object DownloadQueue {
}
fun clear(context: Context, key: String) {
val app = context.applicationContext
val item: Item
val cleanup: Boolean
var cleanupKey: String? = null
var cleanup = false
synchronized(lock) {
item = items[key] ?: return
if (item.entry.state == DownloadState.RUNNING || item.entry.state == DownloadState.QUEUED) return
cleanup = (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) && beginCleanup(key)
if (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) {
val candidate = item.entry.cleanupKey?.takeIf { item.factory != null }
if (candidate == null || cancelling.add(candidate)) {
cleanup = beginCleanup(key)
if (cleanup) cleanupKey = candidate else cleanupFinished(candidate)
}
}
items.remove(key)
publishLocked()
}
if (cleanup) cleanUpLater(context.applicationContext, key, "store-dl-clear") { runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }
StoreDownloadService.finish(context.applicationContext, key)
if (cleanup) cleanUpLater(app, key, "store-dl-clear") {
if (runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) }.isFailure) cleanupFinished(cleanupKey)
}
StoreDownloadService.finish(app, key)
}
fun dismissFinished() {
@@ -393,11 +437,27 @@ object DownloadQueue {
var error: String? = null
try {
val job = checkNotNull(item.factory).invoke()
synchronized(lock) { item.job = job }
var cancelled = false
var paused = false
synchronized(lock) {
item.job = job
cancelled = item.cancelled.get()
paused = item.pauseRequested
}
StoresState.logLine("${item.entry.store.label}: fetching manifest for \"${item.entry.name}\"")
val deleting = ArrayList<Thread>()
try {
StoreInstalls.collectingDiscards(deleting) { result = job.run(handle) }
StoreInstalls.collectingDiscards(deleting) {
if (cancelled) {
try {
job.cancel(deleteFiles = !paused)
} catch (t: Throwable) {
synchronized(lock) { cleanupFinished(item.entry.cleanupKey) }
throw t
}
}
result = job.run(handle)
}
} finally {
if (deleting.isNotEmpty()) {
holdCleanup(item.entry.key)
@@ -408,6 +468,9 @@ object DownloadQueue {
} catch (t: Throwable) {
error = t.message ?: t.javaClass.simpleName
Log.w(TAG, "${item.entry.key} failed", t)
synchronized(lock) {
if (item.job == null) cleanupFinished(item.entry.cleanupKey)
}
}
synchronized(lock) {
running--
@@ -29,6 +29,16 @@ object SavedQueue {
wanted[key(item)] = Wanted(item, root)
}
internal fun remembered(key: String): CatalogItem? = synchronized(this) { wanted[key]?.item }
internal fun resetForTest() {
synchronized(this) {
restored = false
wanted.clear()
app = null
}
}
fun save(entries: List<DownloadEntry>) {
val context = app ?: return
val rows = synchronized(this) {
@@ -6,9 +6,6 @@ import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionService
@@ -46,8 +43,6 @@ internal object SteamStore {
/** InvalidPassword, AccessDenied, AccountNotFound, Revoked, Expired, AccountLogonDenied. */
private val REFUSALS = setOf(5, 15, 18, 26, 27, 63)
var picking by mutableStateOf<CatalogItem?>(null)
class Plan(val installDir: String, val downloadBytes: Long, val installBytes: Long, val buildId: String, val linuxBuild: Boolean) {
companion object {
fun of(json: JSONObject): Plan? {
@@ -222,7 +217,7 @@ internal object SteamStore {
toast(context, R.string.steam_store_close_steam)
return
}
picking = item
StoresState.steamPicking = item
}
fun install(context: Context, item: CatalogItem, target: SteamClient.Target) {
@@ -94,17 +94,16 @@ internal object XboxManifest {
}
fun executable(folder: File): String {
for (path in read(folder).executables) {
val listed = read(folder).executables
for (path in listed) {
require(!path.startsWith('/') && !path.contains(':') && path.split('/').none { it == ".." || it.isEmpty() })
var file = folder
for (part in path.split('/')) {
val matches = file.listFiles().orEmpty().filter { it.name.equals(part, true) }
require(matches.size == 1) { "Missing or ambiguous Xbox launch path." }
file = matches.single()
}
val file = path.split('/').fold<String, File?>(folder) { dir, part ->
dir?.listFiles().orEmpty().filter { it.name.equals(part, true) }.singleOrNull()
} ?: continue
require(file.canonicalPath.startsWith(folder.canonicalPath + File.separator))
if (file.isFile) return forwarded(folder, file) ?: file.relativeTo(folder).invariantSeparatorsPath
}
require(listed.isEmpty()) { "Missing or ambiguous Xbox launch path." }
error("The Xbox package has no supported PC launch executable.")
}
@@ -7,7 +7,6 @@ import android.os.Bundle
import android.view.Display
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.PointerIcon
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
@@ -45,7 +44,6 @@ class BottomGameScreen(
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
surfaceView.pointerIcon = PointerIcon.getSystemIcon(context, PointerIcon.TYPE_NULL)
surfaceView.setOnTouchListener { _, event -> onTouch(event) }
surfaceView.holder.addCallback(callback)
}
@@ -847,7 +847,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
com.droiddeck.launcher.stores.steam.SteamStore.picking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.steam.SteamStore.picking = null } } }
com.droiddeck.launcher.stores.StoresState.steamPicking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.StoresState.steamPicking = null } } }
StepsLayer(screenAt)
UiZooSheet()
SessionDrawerPreview(s.secondScreenDisplays)
@@ -177,7 +177,7 @@ internal fun GameDetail(
SideEffect { if (store != null && id != null) known[0] = store to id }
val game = found ?: if (store != null && id != null) s.steamGames.firstOrNull { it.source == store.id && it.storeId == id } else null
val item = if (store != null && id != null) StoresState.detailItem(store, id) else null
val installed = if (store != null && id != null) StoresState.installedGame(store, id) else null
val installed = if (store != null && id != null) StoresState.installedGame(store, id, game?.gameFiles) else null
val rawDownload = if (store != null && id != null) StoresState.download("${store.id}:$id") else null
val download = rawDownload?.takeIf { it.isActive }
val failed = rawDownload?.takeIf { it.state == DownloadState.FAILED }
@@ -584,12 +584,25 @@ internal fun GameActions(
}
if (store == Store.BATTLENET) {
if (installed != null && id != null) {
LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) }
val updateKey = BattleNetInstall.updateKey(id, installed.folder)
var wasRunning by remember(updateKey) { mutableStateOf(false) }
// SessionState.running is not snapshot state, so poll it while this detail is shown.
val sessionRunning by produceState(SessionState.running) {
while (true) {
value = SessionState.running
kotlinx.coroutines.delay(1000)
}
}
LaunchedEffect(updateKey, sessionRunning) {
val ended = wasRunning && !sessionRunning
wasRunning = sessionRunning
if (!sessionRunning) BattleNetInstall.checkUpdate(ctx, installed, force = ended)
}
if (download != null) {
SteadyDownloadChip(download)
if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) }
else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) }
} else if (BattleNetInstall.updates[id] == true) {
} else if (BattleNetInstall.updates[updateKey] == true) {
SecondaryButton(stringResource(R.string.bnet_update)) { BattleNetInstall.update(ctx, installed) }
}
}
@@ -195,6 +195,10 @@ internal fun librarySources(
}
}
internal fun alwaysLibraryTabs(signedIn: Collection<Store>, stores: Boolean, soundMode: Boolean): Set<String> =
(if (soundMode) emptyList() else signedIn.map { it.librarySource }).toSet() +
listOfNotNull(Library.ADDED.takeIf { stores }, Store.BATTLENET.id.takeIf { stores })
internal object LibraryDisplay {
const val DEFAULT_LEVEL = 2
val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f)
@@ -374,7 +378,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
.map { it.store.id }.toSet()
val sources = librarySources(
all, storeTabs.map { it.store.id },
listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.ADDED.takeIf { stores }, Store.BATTLENET.id.takeIf { stores }).toSet() + signInChips,
alwaysLibraryTabs(owned.keys, stores, soundMode) + signInChips,
favorites, concealed,
offStores = if (soundMode) emptySet() else storeTabs.filterNot { it.shown }.map { it.store.id }.toSet(),
places = if (soundMode) DEFAULT_LIBRARY_PLACES else StoreTabsState.libraryPlaces,
@@ -1194,8 +1198,22 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?, showDownlo
}
}
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean = e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available || it in com.droiddeck.launcher.stores.ea.EaUpdates.available } == true ||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE
private fun libraryUpdateAvailable(e: LibraryEntry): Boolean {
val installed = e.storeKey?.let { key ->
val store = Store.byId(e.source)
val id = e.item?.id ?: e.game?.storeId
if (store != null && id != null) StoresState.installedGame(store, id, e.game?.gameFiles)
else StoresState.installed.firstOrNull { it.key == key }
}
val battleNet = installed?.let {
com.droiddeck.launcher.stores.battlenet.BattleNetInstall.updates[
com.droiddeck.launcher.stores.battlenet.BattleNetInstall.updateKey(it.sidecar.id, it.folder)
] == true
} == true
return battleNet ||
e.storeKey?.let { it in ItchUpdates.available || it in GameJoltUpdates.available || it in com.droiddeck.launcher.stores.ea.EaUpdates.available } == true ||
e.source == Store.GOG.id && (e.item?.id ?: e.game?.storeId)?.let { GogMaintenance.checks[it]?.state } == GogMaintenance.State.AVAILABLE
}
@Composable
private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, choose: (() -> Unit)?, onOpen: (String) -> Unit) {
+1
View File
@@ -1754,6 +1754,7 @@
<string name="game_link_program_unknown">Add this game to DroidDeck first, then start it from your frontend.</string>
<string name="game_link_session_busy">Stop the current session before launching a Steam game.</string>
<string name="game_link_failed">Could not send the game to Steam. Try launching it again.</string>
<string name="game_link_battlenet_missing">Could not verify this Battle.net installation. Retry or open Battle.net to check the installed copy.</string>
<string name="game_needs_app_model">%1$s is a UWP app. This runtime has no Windows app-model host to start it.</string>
<string name="setup_retry_removal">Retry removal</string>
<string name="runtime_removing">Removing</string>
@@ -50,4 +50,28 @@ class MaliAutoRouteTest {
assertTrue(MaliAutoRoute.userChoice(true, MaliAutoRoute.VENUS, MaliAutoRoute.BRIDGE))
assertFalse(MaliAutoRoute.userChoice(false, MaliAutoRoute.NONE, MaliAutoRoute.BRIDGE))
}
@Test
fun venusTheUserSwitchedOffIsNotSwitchedBackOn() {
assertFalse(MaliAutoRoute.venusStandsIn(true, true, false, true, "Mali-G715"))
assertTrue(MaliAutoRoute.venusStandsIn(true, true, true, true, "Mali-G2-Ultra-NX MC12"))
}
@Test
fun venusIsAutosStandInOnlyWhereSteamStartsThroughIt() {
assertTrue(MaliAutoRoute.venusStandsIn(true, true, false, false, "Mali-G715"))
assertFalse(MaliAutoRoute.venusStandsIn(true, true, false, false, "Mali-G2-Ultra-NX MC12"))
assertFalse(MaliAutoRoute.venusStandsIn(true, true, true, false, "Mali-G2-Ultra-NX MC16"))
assertFalse(MaliAutoRoute.venusStandsIn(false, true, true, true, "Mali-G715"))
assertFalse(MaliAutoRoute.venusStandsIn(true, false, true, true, "Mali-G715"))
}
@Test
fun venusThatAutoTurnedOffIsStillAutosToTurnOn() {
// Auto clears the stored key when it moves to the bridge: a stored "off" would read as the user's own choice.
val cleared = MaliAutoRoute.userChoice(keyStored = false, owner = MaliAutoRoute.BRIDGE, route = MaliAutoRoute.VENUS)
val writtenOff = MaliAutoRoute.userChoice(keyStored = true, owner = MaliAutoRoute.BRIDGE, route = MaliAutoRoute.VENUS)
assertTrue(MaliAutoRoute.venusStandsIn(true, true, false, cleared, "Mali-G715"))
assertFalse(MaliAutoRoute.venusStandsIn(true, true, false, writtenOff, "Mali-G715"))
}
}
@@ -20,6 +20,24 @@ class GameEnvironmentTest {
assertEquals("1", GameEnvironment.effective(config, "", "43", forceSsbs = true)[GameEnvironment.FORCE_SSBS])
}
@Test fun knownGameFixesBeatSharedSettingsButNotTheGamesOwn() {
val shared = GameEnvironment.Config(shared = mapOf("FEX_X87REDUCEDPRECISION" to "1"))
assertEquals("0", GameEnvironment.effective(shared, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"])
assertEquals("1", GameEnvironment.effective(shared, "PERFORMANCE_TSO", "12110")["FEX_X87REDUCEDPRECISION"])
val own = shared.withEntries("12100", mapOf("FEX_X87REDUCEDPRECISION" to "1"))
assertEquals("1", GameEnvironment.effective(own, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"])
assertEquals("1", GameEnvironment.withKnownGames(own).games["12100"]?.get("FEX_X87REDUCEDPRECISION"))
assertEquals("0", GameEnvironment.withKnownGames(shared).games["12100"]?.get("FEX_X87REDUCEDPRECISION"))
}
@Test fun aGamePresetKeepsTheGamesKnownFix() {
val picked = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "12100", "PERFORMANCE")
assertEquals("0", GameEnvironment.effective(picked, "PERFORMANCE_TSO", "12100")["FEX_X87REDUCEDPRECISION"])
assertEquals("PERFORMANCE", GameEnvironment.gameFexPreset(picked, "12100"))
val other = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "12110", "PERFORMANCE")
assertEquals("1", GameEnvironment.effective(other, "PERFORMANCE_TSO", "12110")["FEX_X87REDUCEDPRECISION"])
}
@Test fun gameOverridesSharedAndPresetWithoutLeakingToOtherGames() {
val config = GameEnvironment.Config(
shared = mapOf("FEX_MULTIBLOCK" to "0", "VKD3D_FEATURE_LEVEL" to "12_2"),
@@ -21,4 +21,20 @@ class AllFilesAccessTest {
assertTrue(AllFilesAccess.missing(sdk = 35) { false })
assertFalse(AllFilesAccess.missing(sdk = 35) { true })
}
@Test
fun onlySharedStorageNeedsIt() {
assertTrue(AllFilesAccess.covers("/storage/emulated/0"))
assertTrue(AllFilesAccess.covers("/storage/1A2B-3C4D/Games"))
assertTrue(AllFilesAccess.covers("/sdcard/Download"))
assertFalse(AllFilesAccess.covers("/storage/emulated/0/Android/data"))
assertFalse(AllFilesAccess.covers("/storage/1A2B-3C4D/Android/obb"))
assertTrue(AllFilesAccess.covers("/storage/emulated/0/Android"))
assertTrue(AllFilesAccess.covers("/storage/emulated/0/Android/database"))
assertTrue(AllFilesAccess.covers("/storage/emulated/0/Download/Android/data"))
assertTrue(AllFilesAccess.covers("/storage/1A2B-3C4D/Games/Android/obb/x"))
assertFalse(AllFilesAccess.covers("/storage/emulated/0/Android/data/com.droiddeck.launcher/files"))
assertFalse(AllFilesAccess.covers("/storage/1A2B-3C4D/Android/obb/com.droiddeck.launcher"))
assertFalse(AllFilesAccess.covers("/data/user/0/com.droiddeck.launcher/files"))
}
}
@@ -259,7 +259,7 @@ class PadPartialAxesTest {
}
@Test fun keyTriggerDecision() {
val held = BooleanArray(2)
val held = PadBridge.TriggerKey.slots(1)[0]
assertEquals(1f, PadBridge.keyTrigger(0f, true, 0, false, held, 0))
assertEquals(0f, PadBridge.keyTrigger(1f, false, 0, false, held, 0))
assertEquals(0.25f, PadBridge.keyTrigger(0.25f, true, 1, false, held, 0))
@@ -271,6 +271,64 @@ class PadPartialAxesTest {
assertEquals(0f, PadBridge.axisTrigger(0f, held, 1))
}
@Test fun keyBeforeAxisOnAFullPullIsOnePress() {
val device = device(MotionEvent.AXIS_GAS)
motion(device)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
assertEquals(1f, pad().rightTrigger)
for (value in listOf(0.1f, 0.3f, 0.6f, 1f, 0.98f)) {
motion(device, MotionEvent.AXIS_GAS to value)
assertEquals(1f, pad().rightTrigger)
}
motion(device, MotionEvent.AXIS_GAS to 0.7f)
assertEquals(0.7f, pad().rightTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP)
assertEquals(0.7f, pad().rightTrigger)
motion(device, MotionEvent.AXIS_GAS to 0f)
assertEquals(0f, pad().rightTrigger)
}
@Test fun releasingDuringTheHandoffFollowsTheAxis() {
val device = device(MotionEvent.AXIS_GAS)
motion(device)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
motion(device, MotionEvent.AXIS_GAS to 0.4f)
assertEquals(1f, pad().rightTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP)
assertEquals(0.4f, pad().rightTrigger)
}
@Test fun movingTriggerAxisStaysAnalogWhenItsKeyFiresFirst() {
val device = device(MotionEvent.AXIS_GAS)
motion(device, MotionEvent.AXIS_GAS to 0.5f)
motion(device, MotionEvent.AXIS_GAS to 0f)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
assertEquals(0f, pad().rightTrigger)
motion(device, MotionEvent.AXIS_GAS to 0.1f)
assertEquals(0.1f, pad().rightTrigger)
motion(device, MotionEvent.AXIS_GAS to 0.35f)
assertEquals(0.35f, pad().rightTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP)
motion(device, MotionEvent.AXIS_GAS to 0f)
assertEquals(0f, pad().rightTrigger)
}
@Test fun triggerSwitchedToDigitalPressesAgainAfterOneSilentPress() {
val device = device(MotionEvent.AXIS_GAS)
motion(device, MotionEvent.AXIS_GAS to 0.5f)
motion(device, MotionEvent.AXIS_GAS to 0f)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
motion(device)
key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP)
assertEquals(0f, pad().rightTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_R2)
assertEquals(1f, pad().rightTrigger)
motion(device)
assertEquals(1f, pad().rightTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_R2, KeyEvent.ACTION_UP)
assertEquals(0f, pad().rightTrigger)
}
@Test fun silentTriggerAxesLetTheirKeysPress() {
val device = device(MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_RTRIGGER)
motion(device)
@@ -294,11 +352,15 @@ class PadPartialAxesTest {
key(device, KeyEvent.KEYCODE_BUTTON_L2)
assertEquals(1f, pad().leftTrigger)
motion(device, MotionEvent.AXIS_LTRIGGER to 0.4f)
assertEquals(0.4f, pad().leftTrigger)
assertEquals(1f, pad().leftTrigger)
motion(device, MotionEvent.AXIS_LTRIGGER to 0f)
assertEquals(0f, pad().leftTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.ACTION_UP)
assertEquals(0f, pad().leftTrigger)
key(device, KeyEvent.KEYCODE_BUTTON_L2)
assertEquals(0f, pad().leftTrigger)
motion(device, MotionEvent.AXIS_LTRIGGER to 0.4f)
assertEquals(0.4f, pad().leftTrigger)
}
private fun pad(): PadState = requireNotNull(JoyConPadTest.RecordingWriter.pads[0])
@@ -54,37 +54,6 @@ class PointerCaptureTest {
}
}
@Test fun aHoveringMouseOrTouchpadDrivesThePointer() {
listOf(
event(MotionEvent.ACTION_HOVER_MOVE, InputDevice.SOURCE_MOUSE, x = 640f, y = 360f),
event(MotionEvent.ACTION_BUTTON_PRESS, InputDevice.SOURCE_MOUSE, x = 640f, y = 360f),
event(MotionEvent.ACTION_SCROLL, InputDevice.SOURCE_MOUSE, x = 640f, y = 360f),
event(MotionEvent.ACTION_HOVER_MOVE, InputDevice.SOURCE_TOUCHPAD, x = 640f, y = 360f),
).forEach { event ->
try {
assertTrue(PointerCapture.isMouse(event))
} finally {
event.recycle()
}
}
}
@Test fun touchesPensControllersAndCapturedMiceAreNotAHoveringMouse() {
listOf(
InputDevice.SOURCE_TOUCHSCREEN,
InputDevice.SOURCE_STYLUS,
InputDevice.SOURCE_JOYSTICK,
InputDevice.SOURCE_MOUSE_RELATIVE,
).forEach { source ->
val event = event(MotionEvent.ACTION_MOVE, source, x = 640f, y = 360f)
try {
assertFalse(PointerCapture.isMouse(event))
} finally {
event.recycle()
}
}
}
@Test fun touchpadTravelMatchesTheSameDistanceOnScreen() {
assertEquals(0.5f, PointerCapture.touchpadScale(unitsPerMm = 20f, padWidth = 2000f, pixelsPerMm = 10f, screenWidth = 1920), 0.001f)
}
@@ -157,42 +157,10 @@ class SessionPenRoutingTest {
SessionPrefs.setPenSetting(activity, "pen", SessionPrefs.PEN_TOUCH)
invoke("readPrefs")
assertFalse(hover(event(MotionEvent.ACTION_HOVER_MOVE, 30, pen to 500f)))
assertTrue(hover(event(MotionEvent.ACTION_HOVER_MOVE, 40, finger to 500f, source = InputDevice.SOURCE_MOUSE)))
assertFalse(hover(event(MotionEvent.ACTION_HOVER_MOVE, 40, finger to 500f, source = InputDevice.SOURCE_MOUSE)))
assertEquals(listOf(PEN_IN, PEN_IN or PEN_TIP, 0), CompositorShadow.pens.map { it.flags })
}
@Test fun aMouseOnTheOtherScreensGameMovesTheSessionPointer() {
fun hover(event: MotionEvent) = ReflectionHelpers.callInstanceMethod<Boolean>(activity, "onBottomGameHover",
ReflectionHelpers.ClassParameter.from(MotionEvent::class.java, event))
fun touch(event: MotionEvent) = ReflectionHelpers.callInstanceMethod<Boolean>(activity, "onBottomGameTouch",
ReflectionHelpers.ClassParameter.from(MotionEvent::class.java, event))
val mouse = MotionEvent.TOOL_TYPE_MOUSE
assertTrue(hover(event(MotionEvent.ACTION_HOVER_MOVE, 10, mouse to 250f, source = InputDevice.SOURCE_MOUSE)))
assertTrue(hover(event(MotionEvent.ACTION_BUTTON_PRESS, 20, mouse to 250f, source = InputDevice.SOURCE_MOUSE,
buttons = MotionEvent.BUTTON_PRIMARY)))
assertTrue(touch(event(MotionEvent.ACTION_DOWN, 20, mouse to 250f, source = InputDevice.SOURCE_MOUSE,
buttons = MotionEvent.BUTTON_PRIMARY)))
assertTrue(touch(event(MotionEvent.ACTION_MOVE, 30, mouse to 750f, source = InputDevice.SOURCE_MOUSE,
buttons = MotionEvent.BUTTON_PRIMARY)))
assertTrue(touch(event(MotionEvent.ACTION_UP, 40, mouse to 750f, source = InputDevice.SOURCE_MOUSE)))
assertTrue(hover(event(MotionEvent.ACTION_HOVER_MOVE, 50, finger to 600f, source = InputDevice.SOURCE_TOUCHPAD)))
assertEquals(
listOf(InputSpace.x(250f, 1000), InputSpace.x(250f, 1000), InputSpace.x(750f, 1000), InputSpace.x(600f, 1000)),
CompositorShadow.pointers.map { it.second },
)
assertTrue(CompositorShadow.pointers.all { it.first == 1 && it.third == InputSpace.y(300f, 600) })
assertTrue(CompositorShadow.pens.isEmpty())
assertTrue(CompositorShadow.touches.isEmpty())
}
@Test fun aControllerOnTheOtherScreensGameIsNotTakenAsAMouse() {
fun hover(event: MotionEvent) = ReflectionHelpers.callInstanceMethod<Boolean>(activity, "onBottomGameHover",
ReflectionHelpers.ClassParameter.from(MotionEvent::class.java, event))
assertFalse(hover(event(MotionEvent.ACTION_MOVE, 10, finger to 500f, source = InputDevice.SOURCE_JOYSTICK)))
assertTrue(CompositorShadow.pointers.isEmpty())
assertTrue(CompositorShadow.pens.isEmpty())
}
@Test fun glassesAProgramPointerLockAndAppUiDropPenHover() {
state<Boolean>("glassesOutputActive").value = true
activity.dispatchGenericMotionEvent(event(MotionEvent.ACTION_HOVER_MOVE, 10, pen to 500f))
@@ -3,6 +3,17 @@ package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.GameEnvironmentStore
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.battlenet.BattleNetCleanup
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
import com.droiddeck.launcher.stores.battlenet.BattleNetInstaller
import com.droiddeck.launcher.stores.battlenet.Ownership
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.github.luben.zstd.ZstdOutputStream
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
@@ -21,6 +32,10 @@ import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.nio.file.Files
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import java.util.zip.CRC32
private val REGISTRY = """
@@ -65,6 +80,7 @@ class BattleNetTest {
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
File(context.filesDir, "components").deleteRecursively()
File(context.filesDir, "battlenet-cleanup").deleteRecursively()
LinuxRuntime.rootDir(context).deleteRecursively()
}
@@ -345,17 +361,511 @@ class BattleNetTest {
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "osic"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo II Resurrected"))))),
field(1, message(field(1, "s2_cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/StarCraft II"))))),
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))),
))
for (folder in listOf("Diablo II Resurrected", "StarCraft II")) {
for (folder in listOf("Diablo II Resurrected", "StarCraft II", "Diablo III")) {
File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/$folder").mkdirs()
}
val games = BattleNet.games(context)
assertEquals(listOf("osic", "s2_cn"), games.map { it.installUid })
assertEquals(listOf("osi", "s2"), games.map { it.uid })
assertEquals(listOf("Diablo II: Resurrected" to "OSI", "StarCraft II" to "S2"), games.map { it.name to it.code })
assertFalse(BattleNet.notInstalled(BattleNet.title("osi")!!, listOf("osic")))
assertFalse(BattleNet.notInstalled(BattleNet.title("s2")!!, games.map { it.installUid }))
assertEquals(listOf("osic", "s2_cn", "d3cn"), games.map { it.installUid })
assertEquals(listOf("osi", "s2", "diablo3"), games.map { it.uid })
assertEquals(listOf("Diablo II: Resurrected" to "OSI", "StarCraft II" to "S2", "Diablo III" to "D3CN"), games.map { it.name to it.code })
assertEquals("osic", BattleNet.title("osic")?.product)
assertEquals("s2c", BattleNet.title("s2_cn")?.product)
assertEquals("anbs", BattleNet.title("anbs_cn")?.product)
assertEquals("d3cn", BattleNet.title("d3cn")?.product)
assertEquals("s2c", BattleNet.title("s2_cn_zhcn")?.product)
assertEquals("osic", BattleNet.title("osic_zhcn")?.product)
assertEquals("anbs", BattleNet.title("anbs_cn_zhcn")?.product)
}
@Test fun theFolderPicksBetweenTwoDiabloThreeInstalls() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val legacy = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III")
val china = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III China")
legacy.mkdirs()
china.mkdirs()
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "diablo3"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))),
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III China"))))),
))
assertEquals(setOf("diablo3", "d3cn"), BattleNet.games(context).map { it.installUid }.toSet())
val sidecar = StoreGameSidecar(Store.BATTLENET, "diablo3", "Diablo III", "")
val oldGame = InstalledStoreGame(sidecar, legacy)
val chinaGame = InstalledStoreGame(sidecar, china)
val records = listOf(oldGame, chinaGame)
assertEquals(chinaGame, StoresState.pickInstalled(Store.BATTLENET, "diablo3", china, records))
assertEquals(oldGame, StoresState.pickInstalled(Store.BATTLENET, "diablo3", legacy, records))
assertEquals("d3cn", BattleNetInstall.installUid(context, chinaGame))
assertEquals("diablo3", BattleNetInstall.installUid(context, oldGame))
val missing = File(china, "missing")
assertNull(StoresState.pickInstalled(Store.BATTLENET, "diablo3", missing, records))
assertNull(BattleNetInstall.installUid(context, InstalledStoreGame(sidecar, missing)))
}
@Test fun anUnfinishedInstallIsARegistrationButNotAGame() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/StarCraft II").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(
field(1, "s2_cn"), field(2, "s2c"),
field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/StarCraft II"))),
field(4, message(field(1, message(varintField(1, 0), varintField(2, 0))))),
)),
))
assertTrue("an unfinished install is not a library game", BattleNet.games(context).none { it.installUid == "s2_cn" })
assertEquals(listOf("s2_cn"), BattleNet.registrationsAt(context, "s2", folder))
}
@Test fun aChinaCopyLaunchesWithItsRecordedCode() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val legacy = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III").apply { mkdirs() }
val china = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III China").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "diablo3"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))),
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III China"))))),
))
assertEquals("D3CN", BattleNet.launchCode(context, "diablo3", china))
assertEquals("D3CN", BattleNet.launchCode(context, "d3cn", china))
assertEquals(listOf("d3cn"), BattleNet.registrationsAt(context, "d3cn", china))
assertEquals("D3", BattleNet.launchCode(context, "diablo3", legacy))
assertEquals("D3", BattleNet.launchCode(context, "diablo3", null))
assertNull(BattleNet.launchCode(context, "diablo3", File(china, "missing")))
val game = com.droiddeck.launcher.frontend.Library.SteamGame(
1234, "Diablo III", null, com.droiddeck.launcher.frontend.Library.ADDED,
source = Store.BATTLENET.id, storeId = "diablo3", gameFiles = china,
)
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(context, game, null)!!
assertEquals(com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET, command.program)
assertEquals(listOf("launch", "D3CN"), command.args)
}
@Test fun aCopyInAnotherFolderResolvesItsOwnLaunchCode() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val first = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/StarCraft II").apply { mkdirs() }
val second = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/StarCraft II Copy").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "s2_cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/StarCraft II"))))),
field(1, message(field(1, "s2_cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/StarCraft II Copy"))))),
))
// games() keeps one copy per launch code, so the second folder is only reachable per folder.
assertEquals(1, BattleNet.games(context).size)
assertEquals("S2", BattleNet.launchCode(context, "s2", first))
assertEquals("S2", BattleNet.launchCode(context, "s2", second))
}
@Test fun aCopyRegisteredUnderAnotherUidOfTheSameProductStillLaunches() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo IV").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "fen"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo IV"))))),
))
assertTrue(BattleNet.sameTitle("fen", "fenris"))
assertFalse(BattleNet.sameTitle("fen", "wow"))
assertEquals("Fen", BattleNet.launchCode(context, "fenris", folder))
assertEquals("Fen", BattleNet.launchCode(context, "fen", folder))
}
@Test fun aMissingInstallFolderCannotLaunchEvenWhenRegistered() {
val pfx = File(BattleNet.prefix(context), "pfx")
val db = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").apply { parentFile!!.mkdirs() }
val folder = File(pfx, "drive_c/Games/D3")
db.writeBytes(message(field(1, message(field(1, "d3cn"), field(3, message(field(1, "C:/Games/D3")))))))
assertNull(BattleNet.launchCode(context, "diablo3", folder))
assertEquals(true, BattleNet.folderHasRegistrations(context, folder))
}
@Test fun anUnreadableAgentDatabaseDoesNotAuthorizeFolderDeletion() {
val pfx = File(BattleNet.prefix(context), "pfx")
val db = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").apply { parentFile!!.mkdirs() }
val folder = File(pfx, "drive_c/Games/D3").apply { mkdirs() }
db.writeBytes(byteArrayOf(0x0a, 0x7f))
assertFalse(BattleNet.registrationsReadable(context))
assertNull(BattleNet.folderHasRegistrations(context, folder))
}
@Test fun productFallbackResolvesBothLaunchCodeAndManagementUid() {
val pfx = File(BattleNet.prefix(context), "pfx")
val db = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").apply { parentFile!!.mkdirs() }
val folder = File(pfx, "drive_c/Games/WoW").apply { mkdirs() }
db.writeBytes(message(field(1, message(field(1, "wowf_live"), field(2, "wowf"), field(3, message(field(1, "C:/Games/WoW")))))))
assertEquals("WoWF", BattleNet.launchCode(context, "wow_forever", folder))
val sidecar = StoreGameSidecar(Store.BATTLENET, "wow_forever", "World of Warcraft", "")
assertEquals("wowf_live", BattleNetInstall.installUid(context, InstalledStoreGame(sidecar, folder)))
}
@Test fun aRegistrationForAMissingFolderStillCountsAsPreexisting() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III")
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))),
))
assertTrue(BattleNet.games(context).none { it.folder.absolutePath == folder.absolutePath })
assertEquals(listOf("d3cn"), BattleNet.registrationsAt(context, "diablo3", folder))
folder.mkdirs()
val uninstalled = AtomicBoolean(false)
val item = CatalogItem(Store.BATTLENET, "diablo3", "Diablo III", null)
BattleNetInstaller(context, item, folder, false, uninstall = {
uninstalled.set(true)
true
}).cancel(true)
Thread.sleep(100)
assertFalse("a registration whose folder was missing is still pre-existing", uninstalled.get())
}
@Test fun aStaleRegistryRowDoesNotHideAnAgentRegistrationInAnotherFolder() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val a = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III A")
val b = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III B")
File(pfx, "system.reg").writeText("""
WINE REGISTRY Version 2
[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Diablo III] 1
"InstallLocation"="Z:/root/Games/Stores/Battle.net/Diablo III A"
"UninstallString"="\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\" --uid=d3cn"
""".trimIndent())
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III B"))))),
))
assertEquals(emptyList<String>(), BattleNet.registrationsAt(context, "diablo3", a))
assertEquals(listOf("d3cn"), BattleNet.registrationsAt(context, "diablo3", b))
}
@Test fun aPathOnlyAgentRegistrationMakesTheFolderUnknown() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III")
val db = message(field(1, message(field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))))
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(db)
assertEquals("", BattleNet.productDbRegistrations(db)!!.single().uid)
assertNull(BattleNet.registrationsAt(context, "diablo3", folder))
}
@Test fun aPreexistingRegistrationIsNotUninstalled() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "1"),
)
val uninstalled = AtomicBoolean(false)
val installer = BattleNetInstaller(context, item, folder, false, uninstall = {
uninstalled.set(true)
true
}) { listOf("osic") }
installer.cancel(true)
Thread.sleep(100)
assertFalse("a registration that existed before the task must survive", uninstalled.get())
}
@Test fun aCancelledInstallUninstallsOnlyTheRegistrationItCreated() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val seen = AtomicReference<String?>(null)
val done = CountDownLatch(1)
val installer = BattleNetInstaller(context, item, folder, false, cleanupVerifyMs = 0, uninstall = { uid ->
seen.set(uid)
done.countDown()
true
}) { listOf("osic") }
installer.cancel(true)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("osic", seen.get())
}
@Test fun aCancelledInstallsCleanupHoldsTheFolderForUninstall() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val holding = AtomicBoolean(false)
val done = CountDownLatch(1)
val ownership = Ownership(item)
ownership.createdFolder.set(true)
var registered = true
val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, cleanupVerifyMs = 0, uninstall = { uid ->
holding.set(StoreInstalls.isDiscarding(folder))
registered = false
done.countDown()
true
}) { if (registered) listOf("osic") else emptyList() }
installer.cancel(true)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertTrue("the cleanup must hold the folder against uninstall", holding.get())
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (StoreInstalls.isDiscarding(folder) && System.nanoTime() < until) Thread.sleep(10)
assertFalse(StoreInstalls.isDiscarding(folder))
assertFalse(folder.exists())
}
@Test fun aLateRegistrationReportedWhileTheWorkerStopsIsUsedForCancellation() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(Store.BATTLENET, "osi", "Diablo II: Resurrected", null)
var visible = false
val seen = AtomicReference<String?>(null)
val done = CountDownLatch(1)
val installer = BattleNetInstaller(context, item, folder, false, registrationWaitMs = 1000, cleanupVerifyMs = 0, uninstall = { uid ->
seen.set(uid)
done.countDown()
true
}) {
if (visible) listOf("osic") else emptyList()
}
val started = BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true }
(started.get(installer) as AtomicBoolean).set(true)
val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true }
.get(installer) as CountDownLatch
installer.cancel(true)
visible = true
ended.countDown()
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("osic", seen.get())
}
@Test fun aCancelledInstallRemovesAFolderItCreatedWithoutARegistration() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected")
assertFalse(folder.exists())
folder.mkdirs()
File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3))
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val ownership = Ownership(item)
val uninstalled = AtomicBoolean(false)
val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, registrationWaitMs = 0, uninstall = {
uninstalled.set(true)
false
}) { emptyList() }
ownership.createdFolder.set(true)
BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true }
.set(installer, AtomicBoolean(true))
val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true }
.get(installer) as CountDownLatch
installer.cancel(true)
ended.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (folder.exists() && System.nanoTime() < until) Thread.sleep(10)
assertFalse("a folder this task created must not survive a cancel", folder.exists())
assertFalse(uninstalled.get())
}
@Test fun aCancelledInstallKeepsTheFolderWhileItsRegistrationRemains() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3))
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val installer = BattleNetInstaller(context, item, folder, false, cleanupVerifyMs = 0, uninstall = { true }) {
listOf("osic")
}
BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true }
.set(installer, AtomicBoolean(true))
val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true }
.get(installer) as CountDownLatch
installer.cancel(true)
ended.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(3)
while (BattleNetCleanup.get(context, folder) == null && System.nanoTime() < until) Thread.sleep(10)
assertTrue("the folder must stay while the registration exists", folder.exists())
assertEquals(BattleNetCleanup.PENDING, BattleNetCleanup.get(context, folder)?.state)
}
@Test fun aCancelledInstallDeletesTheFolderOnceItsRegistrationGoes() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3))
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val ownership = Ownership(item)
ownership.createdFolder.set(true)
var registered = true
val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, cleanupVerifyMs = 0, uninstall = {
registered = false
true
}) { if (registered) listOf("osic") else emptyList() }
BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true }
.set(installer, AtomicBoolean(true))
val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true }
.get(installer) as CountDownLatch
installer.cancel(true)
ended.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (folder.exists() && System.nanoTime() < until) Thread.sleep(10)
assertFalse(folder.exists())
assertNull(BattleNetCleanup.get(context, folder))
}
@Test fun reconcileCleansAMarkerAfterItsRegistrationGoes() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/Diablo III").apply { mkdirs() }
File(folder, "partial.bin").writeBytes(byteArrayOf(1, 2, 3))
val db = File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
db.writeBytes(message(
field(1, message(field(1, "d3cn"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/Diablo III"))))),
))
BattleNetCleanup.mark(context, folder, "diablo3", createdFolder = true, state = BattleNetCleanup.PENDING)
BattleNetInstall.reconcileNow(context, uninstall = { uid ->
assertEquals("d3cn", uid)
db.writeBytes(ByteArray(0))
true
}, verifyMs = 0, watchMs = 0)
assertFalse(folder.exists())
assertNull(BattleNetCleanup.get(context, folder))
}
@Test fun aCancellationRecordsItsMarkerBeforeItWaitsForTheWorker() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val installer = BattleNetInstaller(context, item, folder, false, registrationWaitMs = 0, cleanupVerifyMs = 0) {
emptyList()
}
BattleNetInstaller::class.java.getDeclaredField("started").apply { isAccessible = true }
.set(installer, AtomicBoolean(true))
val ended = BattleNetInstaller::class.java.getDeclaredField("ended").apply { isAccessible = true }
.get(installer) as CountDownLatch
installer.cancel(true)
assertEquals(BattleNetCleanup.PENDING, BattleNetCleanup.get(context, folder)?.state)
ended.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(2)
while (BattleNetCleanup.get(context, folder)?.state == BattleNetCleanup.PENDING && System.nanoTime() < until) Thread.sleep(10)
}
@Test fun anActiveMarkerCannotOverwriteACancellation() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
BattleNetCleanup.mark(context, folder, "osi", createdFolder = false, state = BattleNetCleanup.PENDING)
BattleNetCleanup.markActive(context, folder, "osi", createdFolder = true)
val pending = BattleNetCleanup.get(context, folder)!!
assertEquals(BattleNetCleanup.PENDING, pending.state)
assertTrue(pending.createdFolder)
}
@Test fun aCleanupMarkerRewrittenForAReplacementHasANewStamp() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
BattleNetCleanup.mark(context, folder, "osi", createdFolder = false, state = BattleNetCleanup.PENDING)
val first = BattleNetCleanup.get(context, folder)!!
BattleNetCleanup.mark(context, folder, "osi", createdFolder = true, state = BattleNetCleanup.PENDING)
val second = BattleNetCleanup.get(context, folder)!!
assertTrue(second.stamp > first.stamp)
}
@Test fun aCleanupMarkerIsRestoredWithoutTheTask() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
BattleNetCleanup.mark(context, folder, "osi", createdFolder = true, state = BattleNetCleanup.PENDING)
val pending = BattleNetCleanup.pending(context).single()
assertEquals(folder.absolutePath, pending.folder.absolutePath)
assertEquals("osi", pending.id)
assertTrue(pending.createdFolder)
assertEquals(BattleNetCleanup.PENDING, pending.state)
BattleNetCleanup.clear(context, folder)
assertTrue(BattleNetCleanup.pending(context).isEmpty())
}
@Test fun aRegistrationSourceFailureMakesOwnershipUnknown() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db")
.writeBytes(byteArrayOf(0x0a, 0x03, 0x0a, 0x7f, 0x01))
assertNull(BattleNet.registrationsAt(context, "osi", File(LinuxRuntime.rootDir(context), "root/Games/D2R")))
}
@Test fun aWorkerOwnershipSnapshotFailureDoesNotUninstall() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(Store.BATTLENET, "osi", "Diablo II: Resurrected", null)
val ownership = Ownership(item)
val uninstalled = AtomicBoolean(false)
val installer = BattleNetInstaller(context, item, folder, false, ownership = ownership, uninstall = {
uninstalled.set(true)
true
}) { null }
runCatching { installer.run(DownloadQueue.JobHandle("battlenet:snapshot-failure", AtomicBoolean(false))) }
assertFalse("a failed read must not become a final ownership decision", ownership.known)
assertTrue(ownership.preexisting)
installer.cancel(true)
Thread.sleep(100)
assertFalse("a failed worker snapshot must disable destructive cleanup", uninstalled.get())
}
@Test fun aFailedRegistrationReadDoesNotUninstall() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val uninstalled = AtomicBoolean(false)
BattleNetInstaller(context, item, folder, false, uninstall = {
uninstalled.set(true)
true
}) { null }.cancel(true)
Thread.sleep(100)
assertFalse("an unreadable registration source must disable destructive cleanup", uninstalled.get())
}
@Test fun aResumedInstallerKeepsTheOwnershipDecision() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(Store.BATTLENET, "osi", "Diablo II: Resurrected", null)
val ownership = Ownership(item)
ownership.known = true
ownership.preexisting = false
val seen = AtomicReference<String?>(null)
val done = CountDownLatch(1)
BattleNetInstaller(context, item, folder, false, ownership = ownership, cleanupVerifyMs = 0, uninstall = { uid ->
seen.set(uid)
done.countDown()
true
}) { listOf("osic") }.cancel(true)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("osic", seen.get())
}
@Test fun aRestoredPausedInstallUninstallsTheRegistrationItCreated() {
val folder = File(LinuxRuntime.rootDir(context), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(
Store.BATTLENET, "osi", "Diablo II: Resurrected", null,
extra = mapOf(BattleNetInstall.PREEXISTING to "0"),
)
val seen = AtomicReference<String?>(null)
val done = CountDownLatch(1)
BattleNetInstaller(context, item, folder, false, cleanupVerifyMs = 0, uninstall = { uid ->
seen.set(uid)
done.countDown()
true
}) { listOf("osic") }.cancel(true)
assertTrue(done.await(5, TimeUnit.SECONDS))
assertEquals("osic", seen.get())
}
@Test fun theTitlePicksBetweenWarcraftFlavorsInOneFolder() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
val wow = File(LinuxRuntime.rootDir(context), "root/Games/Stores/Battle.net/World of Warcraft")
wow.mkdirs()
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "wow"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/World of Warcraft"))))),
field(1, message(field(1, "wow_classic"), field(3, message(field(1, "Z:/root/Games/Stores/Battle.net/World of Warcraft"))))),
))
val sidecar = StoreGameSidecar(Store.BATTLENET, "wow_classic", "World of Warcraft Classic", "")
assertEquals("wow_classic", BattleNetInstall.installUid(context, InstalledStoreGame(sidecar, wow)))
assertEquals(listOf("wow"), BattleNet.registrationsAt(context, "wow", File(wow, "_retail_")))
assertEquals(listOf("wow_classic"), BattleNet.registrationsAt(context, "wow_classic", File(wow, "_classic_")))
val single = StoreGameSidecar(Store.BATTLENET, "wow", "World of Warcraft", "")
assertNull(BattleNetInstall.installUid(context, InstalledStoreGame(single, File(wow, "missing"))))
}
@Test fun aScannedGamesShortcutReusesTheKeptRankingInsteadOfWalkingItsFolder() {
@@ -408,8 +918,9 @@ class BattleNetTest {
assertEquals("wow_forever", BattleNet.STORE.first { it.code == "WoWF" }.uid)
assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid)
assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) })
val installed = listOf("fenris", "diablo3_enus", null)
val offered = BattleNet.STORE.filter { BattleNet.notInstalled(it, installed) }.map { it.code }
val installedUids = listOf("fenris", "diablo3_enus", null)
.mapNotNull { uid -> uid?.let { BattleNet.title(it)?.uid } }.toSet()
val offered = BattleNet.STORE.filterNot { it.uid in installedUids }.map { it.code }
assertFalse("Fen" in offered || "D3" in offered)
assertTrue("OSI" in offered && "WoWF" in offered)
assertFalse("WoWF" in BattleNet.STORE.filter { BattleNet.notInstalled(it, listOf("wow_forever")) }.map { it.code })
@@ -428,7 +939,7 @@ class BattleNetTest {
assertFalse(noSteam.enabled(context, game))
assertTrue(BattleNet.ensureNoSteam(context))
assertTrue(noSteam.enabled(context, game))
val command = noSteam.command(game, shortcut)!!
val command = noSteam.command(context, game, shortcut)!!
assertEquals(noSteam.BATTLENET, command.program)
assertEquals(listOf("launch", "Fen"), command.args)
GameEnvironmentStore.setGameNoSteam(context, BattleNet.APP_ID.toString(), false)
@@ -0,0 +1,79 @@
package com.droiddeck.launcher.runtime
import androidx.test.core.app.ApplicationProvider
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class NativeGuestPrepareTest {
private val svc = 0xd4000001.toInt()
private val rseq = 0xd28024a8.toInt()
private val enosys = 0x928004a0.toInt()
private fun unpatchedLoader(): ByteArray {
val data = ByteArray(0x200)
val b = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)
b.put(0, 0x7f); b.put(1, 'E'.code.toByte()); b.put(2, 'L'.code.toByte()); b.put(3, 'F'.code.toByte())
b.put(4, 2); b.put(5, 1)
b.putShort(18, 183)
b.putLong(32, 64)
b.putShort(54, 56); b.putShort(56, 1)
b.putInt(64, 1); b.putInt(68, 5)
b.putLong(72, 0x100); b.putLong(96, 0x100)
b.putInt(0x100, rseq); b.putInt(0x104, svc)
return data
}
private fun rootWithUnpatchedLoader(): Pair<File, File> {
val root = Files.createTempDirectory("native-prepare").toFile()
val loader = File(root, "usr/lib/ld-linux-aarch64.so.1")
loader.parentFile!!.mkdirs()
loader.writeBytes(unpatchedLoader())
return root to loader
}
private fun instructionAfterRseq(loader: File): Int =
ByteBuffer.wrap(loader.readBytes()).order(ByteOrder.LITTLE_ENDIAN).getInt(0x104)
@After
fun endSession() {
NativeGuest.sessionMode = null
}
@Test
fun aProgramStartedOutsideASessionGetsALoaderThatSurvivesSeccomp() {
val (root, loader) = rootWithUnpatchedLoader()
NativeGuest.sessionMode = null
NativeGuest.processBuilder(ApplicationProvider.getApplicationContext(), root, emptyList(), listOf("/usr/bin/true"))
assertEquals(enosys, instructionAfterRseq(loader))
}
@Test
fun aProgramStartedInARunningSessionLeavesTheRootfsAsTheSessionPreparedIt() {
val (root, loader) = rootWithUnpatchedLoader()
val before = loader.readBytes()
NativeGuest.sessionMode = true
NativeGuest.processBuilder(ApplicationProvider.getApplicationContext(), root, emptyList(), listOf("/usr/bin/true"))
assertArrayEquals(before, loader.readBytes())
}
@Test
fun anAlreadyPreparedLoaderIsNotRewritten() {
val (root, loader) = rootWithUnpatchedLoader()
NativeGuest.processBuilder(ApplicationProvider.getApplicationContext(), root, emptyList(), listOf("/usr/bin/true"))
val modified = loader.lastModified()
val bytes = loader.readBytes()
loader.setLastModified(modified - 10_000)
NativeGuest.processBuilder(ApplicationProvider.getApplicationContext(), root, emptyList(), listOf("/usr/bin/true"))
assertArrayEquals(bytes, loader.readBytes())
assertEquals(modified - 10_000, loader.lastModified())
}
}
@@ -202,11 +202,19 @@ class GameEnvironmentStoreTest {
assertEquals("false", published.shared["MESA_SHADER_CACHE_DISABLE"])
assertFalse(published.shared.containsKey("VKD3D_FEATURE_LEVEL"))
assertFalse(published.shared.containsKey("VKD3D_SHADER_MODEL"))
assertEquals(config.games, published.games)
assertEquals(config.games + GameEnvironment.knownGames, published.games)
assertEquals(config.shared["LITERAL"], published.shared["LITERAL"])
assertEquals("", published.shared["EMPTY"])
}
@Test fun aKnownGamesFixReachesTheGuestWithoutBeingSavedAsTheUsersSetting() {
GameEnvironmentStore.save(context, GameEnvironment.Config())
assertEquals(emptyMap<String, Map<String, String?>>(), GameEnvironmentStore.read(context).games)
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
assertEquals(GameEnvironment.knownGames, published.games)
assertEquals("0", published.entries("12100")["FEX_X87REDUCEDPRECISION"])
}
@Test fun publishingPreservesExplicitSharedGraphicsCapabilities() {
val config = GameEnvironment.Config(shared = mapOf(
"VKD3D_FEATURE_LEVEL" to "12_1", "VKD3D_SHADER_MODEL" to "6_6",
@@ -266,7 +274,7 @@ class GameEnvironmentStoreTest {
assertEquals(original.entries("43"), saved.entries("43"))
assertEquals("PERFORMANCE_TSO", SessionPrefs.fexPreset(context))
val published = GameEnvironmentStore.decode(JSONObject(guest.readText()))
assertEquals(saved.games, published.games)
assertEquals(saved.games + GameEnvironment.knownGames, published.games)
assertEquals("0", published.shared["FEX_HALFBARRIERTSOENABLED"])
assertEquals("1", published.entries("42")["FEX_HALFBARRIERTSOENABLED"])
}
@@ -55,7 +55,7 @@ class NoSteamLaunchTest {
"/mnt/droiddeck-sd/Games/Epic/Hogwarts Legacy/.droiddeck-launch.bat", "/mnt/droiddeck-sd/Games/Epic/Hogwarts Legacy",
2733369024L, 0L, emptyList(), source = "epic", launchOptions = "-windowed",
)
val added = NoSteamLaunch.command(shortcut, game)!!
val added = NoSteamLaunch.command(context, shortcut, game)!!
assertEquals(NoSteamLaunch.PROTON_RUN, added.program)
assertEquals(
listOf("--app", "2733369024", "--dir", game.guestDir, "--options", "-windowed", "--", game.guestExe),
@@ -63,10 +63,10 @@ class NoSteamLaunchTest {
)
val plain = NoSteamLaunch.addedCommand(AddedGames.Game(game.folder, game.name, game.exe, game.guestExe, game.guestDir, 2733369024L, 0L, emptyList(), source = "gog"))
assertEquals(listOf("--app", "2733369024", "--dir", game.guestDir, "--", game.guestExe), plain.args)
assertNull(NoSteamLaunch.command(shortcut, null))
val steam = NoSteamLaunch.command(steamGame, null)!!
assertNull(NoSteamLaunch.command(context, shortcut, null))
val steam = NoSteamLaunch.command(context, steamGame, null)!!
assertEquals(listOf("--app", "413150"), steam.args)
val epic = NoSteamLaunch.command(launcher, null)!!
val epic = NoSteamLaunch.command(context, launcher, null)!!
assertEquals(NoSteamLaunch.EPIC to listOf("run"), epic.program to epic.args)
}
@@ -86,14 +86,14 @@ class NoSteamLaunchTest {
assertEquals(413150L, NoSteamLaunch.settingsId(routed))
val entry = Library.SteamGame(413150, "Stardew Valley", null, Library.ADDED)
assertEquals(NoSteamLaunch.settingsId(routed).toString(), NoSteamLaunch.scope(entry))
val command = NoSteamLaunch.command(entry, routed)!!
val command = NoSteamLaunch.command(context, entry, routed)!!
assertEquals(NoSteamLaunch.PROTON_RUN to listOf("--app", "413150"), command.program to command.args)
val plain = AddedGames.Game(File("/x/a"), "a", File("/x/a/a.exe"), "/g/a.exe", "/g", 2733369024L, 0L, emptyList())
assertEquals(2733369024L, NoSteamLaunch.settingsId(plain))
}
@Test fun theRunningSessionIsNamedAfterItsGame() {
val command = NoSteamLaunch.command(steamGame, null)!!
val command = NoSteamLaunch.command(context, steamGame, null)!!
assertNull(NoSteamLaunch.nameFor(command.program, command.args))
NoSteamLaunch.remember(command)
assertEquals("Stardew Valley", NoSteamLaunch.nameFor(command.program, command.args))
@@ -28,6 +28,41 @@ class BattleNetInstallTest {
eu|e474008a3535d8ea978949a90d9873e6|db0583272ed15286569b5f24ce516876||119725|16.1.2.119725|f6a454799d25791e5a37a7547d75ce49
""".trimIndent()
private val osiVersions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 3964805
us|11111111111111111111111111111111|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa||93847|3.3.93847|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
eu|11111111111111111111111111111111|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa||93847|3.3.93847|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
kr|11111111111111111111111111111111|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa||93847|3.3.93847|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
""".trimIndent()
private val osicVersions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 3964866
cn|44444444444444444444444444444444|cccccccccccccccccccccccccccccccc||93854|3.3.93854|dddddddddddddddddddddddddddddddd
""".trimIndent()
private val s2Versions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 4064835
us|55555555555555555555555555555555|eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee||98310|5.0.17.98310|ffffffffffffffffffffffffffffffff
cn|66666666666666666666666666666666|eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee||93333|5.0.14.93333|ffffffffffffffffffffffffffffffff
""".trimIndent()
private val s2cVersions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 4064962
cn|77777777777777777777777777777777|eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee||98370|5.0.17.98370|ffffffffffffffffffffffffffffffff
""".trimIndent()
private val anbsVersions = """
Region!STRING:0|BuildConfig!HEX:16|CDNConfig!HEX:16|KeyRing!HEX:16|BuildId!DEC:4|VersionsName!String:0|ProductConfig!HEX:16
## seqn = 4105154
us|88888888888888888888888888888888|99999999999999999999999999999999||3935504|5.1.3.3935504|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab
eu|88888888888888888888888888888888|99999999999999999999999999999999||3935504|5.1.3.3935504|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab
kr|88888888888888888888888888888888|99999999999999999999999999999999||3935504|5.1.3.3935504|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab
""".trimIndent()
@Test fun theActiveRowGivesTheRegionAndBuildOnDisk() {
assertEquals("us" to "e474008a3535d8ea978949a90d9873e6", BattleNetInstall.buildKey(buildInfo))
assertNull(BattleNetInstall.buildKey("Branch!STRING:0|Active!DEC:1\n"))
@@ -41,9 +76,18 @@ class BattleNetInstallTest {
assertNull(BattleNetInstall.latestBuild("", "us"))
}
@Test fun theChinaProductsAreNotOnTheGlobalVersionLine() {
assertNull(BattleNetInstall.latestBuild(osiVersions, "cn"))
assertEquals("44444444444444444444444444444444", BattleNetInstall.latestBuild(osicVersions, "cn"))
assertEquals("66666666666666666666666666666666", BattleNetInstall.latestBuild(s2Versions, "cn"))
assertEquals("77777777777777777777777777777777", BattleNetInstall.latestBuild(s2cVersions, "cn"))
assertNull(BattleNetInstall.latestBuild(anbsVersions, "cn"))
}
@Test fun theVersionServiceIsBlizzardsChineseOneForChina() {
assertEquals("https://us.version.battle.net/v2/products/wow/versions", BattleNetInstall.versionsUrl("us", "wow"))
assertEquals("https://cn.version.battlenet.com.cn/v2/products/d3cn/versions", BattleNetInstall.versionsUrl("cn", "d3cn"))
assertEquals("https://cn.version.battlenet.com.cn/v2/products/s2c/versions", BattleNetInstall.versionsUrl("cn", "s2c"))
}
@Test fun theDeviceLanguagePicksABlizzardLocale() {
@@ -69,7 +113,16 @@ class BattleNetInstallTest {
assertTrue(BattleNetInstall.headless(CatalogItem(Store.BATTLENET, "gryphon", "Warcraft Rumble", null)))
assertEquals("hsb", BattleNetInstall.product("hs_beta"))
assertEquals("d3", BattleNetInstall.product("diablo3_enus"))
assertFalse(BattleNetInstall.headless(CatalogItem(Store.BATTLENET, "d3cn", "Diablo III", null)))
assertEquals("d3cn", BattleNetInstall.product("d3cn"))
assertEquals("osic", BattleNetInstall.product("osic"))
assertEquals("s2c", BattleNetInstall.product("s2_cn"))
assertEquals("anbs", BattleNetInstall.product("anbs_cn"))
assertEquals("osic", BattleNetInstall.chinaProduct("osi"))
assertEquals("s2c", BattleNetInstall.chinaProduct("s2"))
assertEquals("d3cn", BattleNetInstall.chinaProduct("diablo3"))
assertNull(BattleNetInstall.chinaProduct("anbs"))
assertNull(BattleNetInstall.chinaProduct("wow"))
assertTrue(BattleNetInstall.headless(CatalogItem(Store.BATTLENET, "d3cn", "Diablo III", null)))
assertFalse(BattleNetInstall.headless(CatalogItem(Store.EPIC, "gryphon", "Warcraft Rumble", null)))
}
@@ -78,12 +131,76 @@ class BattleNetInstallTest {
try {
BattleNetInstall.check("gryphon", folder, false)
BattleNetInstall.checks.submit {}.get()
assertFalse(synchronized(BattleNetInstall.checkedAt) { "gryphon" in BattleNetInstall.checkedAt })
assertFalse(synchronized(BattleNetInstall.checkedAt) {
BattleNetInstall.updateKey("gryphon", folder) in BattleNetInstall.checkedAt
})
} finally {
folder.deleteRecursively()
}
}
@Test fun aBuildThatChangesDuringTheCheckIsAskedAgainOnlyTwice() {
val folder = Files.createTempDirectory("bnet-retry").toFile()
val scheduled = mutableListOf<Pair<() -> Unit, Long>>()
val originalFetch = BattleNetInstall.fetchVersions
val originalSchedule = BattleNetInstall.scheduleRecheck
try {
File(folder, ".build.info").writeText(buildInfo)
var asked = 0
BattleNetInstall.fetchVersions = {
// Every request runs against a different build, so the post-read never matches.
asked += 1
File(folder, ".build.info").writeText(buildInfo.replace("e474008a3535d8ea978949a90d9873e6", "%032x".format(asked)))
versions
}
BattleNetInstall.scheduleRecheck = { body, delay -> scheduled += body to delay }
synchronized(BattleNetInstall.checkedAt) { BattleNetInstall.checkedAt.clear() }
BattleNetInstall.check("gryphon", folder, false)
BattleNetInstall.checks.submit {}.get()
assertEquals(1, scheduled.size)
assertEquals(30_000L, scheduled[0].second)
scheduled[0].first()
BattleNetInstall.checks.submit {}.get()
assertEquals(2, scheduled.size)
assertEquals(60_000L, scheduled[1].second)
var next = 1
repeat(4) {
if (next < scheduled.size) {
scheduled[next].first()
BattleNetInstall.checks.submit {}.get()
next += 1
}
}
assertEquals("re-checks are bounded", 2, scheduled.size)
assertEquals(30_000L, scheduled[0].second)
assertNull(BattleNetInstall.updates[BattleNetInstall.updateKey("gryphon", folder)])
} finally {
BattleNetInstall.fetchVersions = originalFetch
BattleNetInstall.scheduleRecheck = originalSchedule
synchronized(BattleNetInstall.checkedAt) { BattleNetInstall.checkedAt.remove(BattleNetInstall.updateKey("gryphon", folder)) }
folder.deleteRecursively()
}
}
@Test fun updateStateIsSeparateForEachInstallFolder() {
val one = Files.createTempDirectory("bnet-one").toFile()
val two = Files.createTempDirectory("bnet-two").toFile()
try {
val first = BattleNetInstall.updateKey("diablo3", one)
val second = BattleNetInstall.updateKey("diablo3", two)
assertFalse(first == second)
BattleNetInstall.updates[first] = true
assertNull(BattleNetInstall.updates[second])
BattleNetInstall.updates.remove(first)
} finally {
one.deleteRecursively()
two.deleteRecursively()
}
}
@Test fun theAgentStatusPicksTheDownloadStep() {
assertEquals(BattleNetInstall.Step.PREPARING, BattleNetInstall.step(1008, 0, 0, 0))
assertEquals(BattleNetInstall.Step.PREPARING, BattleNetInstall.step(1003, 500, 0, 0))
@@ -1,8 +1,11 @@
package com.droiddeck.launcher.stores.download
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.*
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
import com.droiddeck.launcher.stores.battlenet.BattleNetInstaller
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@@ -12,9 +15,11 @@ import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.json.JSONArray
import org.json.JSONObject
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowLooper
import org.robolectric.shadows.ShadowStatFs
@RunWith(RobolectricTestRunner::class)
@@ -117,6 +122,351 @@ class DownloadQueueRetryTest {
assertNull(DownloadQueue.entry(entry.key))
}
@Test fun cancellingBeforeTheJobIsPublishedCancelsIt() {
val entry = DownloadEntry(Store.GOG, "cancel-before-publish", "Cancel before publish")
val factoryEntered = CountDownLatch(1)
val release = CountDownLatch(1)
val cancelled = CountDownLatch(1)
val job = object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {
if (deleteFiles) cancelled.countDown()
}
}
DownloadQueue.enqueue(app, entry) {
factoryEntered.countDown()
release.await(5, TimeUnit.SECONDS)
job
}
assertTrue(factoryEntered.await(5, TimeUnit.SECONDS))
DownloadQueue.pause(entry.key)
DownloadQueue.cancel(app, entry.key)
release.countDown()
assertTrue("cancel must reach the job published after the request", cancelled.await(5, TimeUnit.SECONDS))
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.state != DownloadState.CANCELLED && System.nanoTime() < until) {
Thread.sleep(10)
}
assertEquals(DownloadState.CANCELLED, DownloadQueue.entry(entry.key)?.state)
DownloadQueue.clear(app, entry.key)
}
@Test fun aRejectedEnqueueDoesNotRunItsAcceptedCallback() {
val entry = DownloadEntry(
Store.BATTLENET, "rejected-enqueue", "Rejected enqueue",
cleanupKey = "${Store.BATTLENET.id}:rejected-enqueue",
)
val started = CountDownLatch(1)
val release = CountDownLatch(1)
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
started.countDown()
release.await()
return null
}
override fun cancel(deleteFiles: Boolean) {}
}
}
assertTrue(started.await(5, TimeUnit.SECONDS))
var accepted = false
assertFalse(DownloadQueue.enqueue(app, entry, onAccepted = { accepted = true }) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {}
}
})
assertFalse(accepted)
release.countDown()
DownloadQueue.clear(app, entry.key)
}
@Test fun aSavedQueueRestoreCarriesOwnershipIntoEnqueue() {
val root = File(app.filesDir, "restore-root").apply { mkdirs() }
val key = "battlenet:restore-chain"
SavedQueue.resetForTest()
SavedQueue.remember(
app,
CatalogItem(
Store.BATTLENET, "restore-chain", "Restore chain", null,
extra = mapOf("preexisting" to "0"),
),
root,
)
val row = JSONObject().apply {
put("paused", true)
put("root", root.absolutePath)
put("item", JSONObject().apply {
put("store", Store.BATTLENET.id); put("id", "restore-chain"); put("title", "Restore chain")
put("extra", JSONObject().put("preexisting", "0"))
put("owned", true)
})
}
File(app.filesDir, "store-queue.json").writeText(JSONArray().put(row).toString())
DownloadQueue.holdPaused(key)
val previous = StoresState.backend(Store.BATTLENET)
val installed = CountDownLatch(1)
StoresState.register(object : StoreBackend {
override val store = Store.BATTLENET
override fun signIn(context: Context) {}
override fun signOut(context: Context) {}
override fun syncLibrary(context: Context, force: Boolean) {}
override fun loadShelves(context: Context, force: Boolean) {}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
override fun install(context: Context, item: CatalogItem, root: File) {
BattleNetInstall.enqueue(context, item, StoreInstallRoot.folderFor(context, store, item.id, item.title, root))
installed.countDown()
}
})
try {
SavedQueue.restore(app)
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (installed.count > 0 && System.nanoTime() < until) {
ShadowLooper.idleMainLooper()
Thread.sleep(10)
}
assertTrue(installed.await(1, TimeUnit.SECONDS))
assertEquals("0", SavedQueue.remembered(key)?.extra?.get("preexisting"))
DownloadQueue.clear(app, key)
} finally {
if (previous != null) StoresState.register(previous)
SavedQueue.resetForTest()
File(app.filesDir, "store-queue.json").delete()
}
}
@Test fun aRejectedUpdateKeepsTheSavedOwnershipSnapshot() {
val original = CatalogItem(
Store.BATTLENET, "rejected-update", "Rejected update", null,
extra = mapOf("preexisting" to "0"),
)
SavedQueue.remember(app, original, null)
val entry = DownloadEntry(Store.BATTLENET, "rejected-update", "Rejected update")
val started = CountDownLatch(1)
val release = CountDownLatch(1)
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
started.countDown()
release.await()
return null
}
override fun cancel(deleteFiles: Boolean) {}
}
}
assertTrue(started.await(5, TimeUnit.SECONDS))
var accepted = false
assertFalse(DownloadQueue.enqueue(app, entry, onAccepted = {
accepted = true
SavedQueue.remember(app, original.copy(extra = mapOf("preexisting" to "1")), null)
}) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {}
}
})
assertFalse(accepted)
assertEquals("0", SavedQueue.remembered(entry.key)?.extra?.get("preexisting"))
release.countDown()
DownloadQueue.clear(app, entry.key)
}
@Test fun aFactorylessFailedBattleNetEntryDoesNotBlockAReplacement() {
val entry = DownloadEntry(
Store.BATTLENET, "factoryless-failure", "Factoryless failure",
cleanupKey = "${Store.BATTLENET.id}:factoryless-failure",
)
DownloadQueue.recordFailed(app, entry, "failed before a job existed")
DownloadQueue.clear(app, entry.key)
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {}
}
}
assertNotNull("a cleared factoryless failure must not hold a cleanup key", DownloadQueue.entry(entry.key))
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.isActive == true && System.nanoTime() < until) Thread.sleep(10)
DownloadQueue.clear(app, entry.key)
}
@Test fun aBattleNetClientDownloadIsNotInTheGameCleanupGuard() {
val entry = DownloadEntry(Store.BATTLENET, "battlenet-client", "Battle.net")
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {}
}
}
DownloadQueue.cancel(app, entry.key)
assertFalse(DownloadQueue.isCancelling(entry.key))
DownloadQueue.clear(app, entry.key)
}
@Test fun aPauseCallbackDoesNotReleaseAnotherCleanup() {
val title = "Pause during cleanup"
val entry = DownloadEntry(
Store.BATTLENET, "pause-during-cleanup", title,
cleanupKey = "${Store.BATTLENET.id}:pause-during-cleanup",
)
val cancelled = CountDownLatch(1)
val release = CountDownLatch(1)
val job = object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {
if (!deleteFiles) return
cancelled.countDown()
Thread({
release.await()
DownloadQueue.cleanupFinished(entry.key)
}, "test-pause-cleanup").start()
}
}
DownloadQueue.enqueue(app, entry) { job }
DownloadQueue.cancel(app, entry.key)
assertTrue(cancelled.await(5, TimeUnit.SECONDS))
assertTrue(DownloadQueue.isCancelling(entry.key))
val folder = File(LinuxRuntime.rootDir(app), "root/Games/Diablo II Resurrected").apply { mkdirs() }
val item = CatalogItem(Store.BATTLENET, entry.id, title, null)
BattleNetInstaller(app, item, folder, false).cancel(false)
assertTrue("a pause must not release the destructive cleanup guard", DownloadQueue.isCancelling(entry.key))
release.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.isCancelling(entry.key) && System.nanoTime() < until) Thread.sleep(10)
assertFalse(DownloadQueue.isCancelling(entry.key))
val entryUntil = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.state != DownloadState.CANCELLED && System.nanoTime() < entryUntil) {
Thread.sleep(10)
}
DownloadQueue.clear(app, entry.key)
}
@Test fun aDoubleClearStartsOneCleanup() {
val entry = DownloadEntry(
Store.BATTLENET, "double-clear", "Double clear",
cleanupKey = "${Store.BATTLENET.id}:double-clear",
)
val cancelled = CountDownLatch(1)
val release = CountDownLatch(1)
val cancels = AtomicInteger()
val job = object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {
if (!deleteFiles) return
cancels.incrementAndGet()
cancelled.countDown()
Thread({
release.await()
DownloadQueue.cleanupFinished(entry.key)
}, "test-double-clear").start()
}
}
DownloadQueue.enqueue(app, entry) { job }
val failedUntil = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.state != DownloadState.FAILED && System.nanoTime() < failedUntil) {
Thread.sleep(10)
}
DownloadQueue.clear(app, entry.key)
DownloadQueue.clear(app, entry.key)
assertTrue(cancelled.await(5, TimeUnit.SECONDS))
assertEquals(1, cancels.get())
assertTrue(DownloadQueue.isCancelling(entry.key))
release.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.isCancelling(entry.key) && System.nanoTime() < until) Thread.sleep(10)
assertFalse(DownloadQueue.isCancelling(entry.key))
}
@Test fun aCancelledBattleNetJobBlocksAReplacementWhileCleanupRuns() {
val entry = DownloadEntry(
Store.BATTLENET, "same-folder-race", "Same folder race",
cleanupKey = "${Store.BATTLENET.id}:same-folder-race",
)
val started = CountDownLatch(1)
val cancelled = CountDownLatch(1)
val release = CountDownLatch(1)
val cancels = AtomicInteger()
val job = object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
started.countDown()
return null
}
override fun cancel(deleteFiles: Boolean) {
if (!deleteFiles) return
cancels.incrementAndGet()
cancelled.countDown()
Thread({
release.await()
DownloadQueue.cleanupFinished(entry.key)
}, "test-cleanup").start()
}
}
DownloadQueue.enqueue(app, entry) { job }
assertTrue(started.await(5, TimeUnit.SECONDS))
try {
DownloadQueue.cancel(app, entry.key)
DownloadQueue.cancel(app, entry.key)
assertTrue(cancelled.await(5, TimeUnit.SECONDS))
assertEquals(1, cancels.get())
assertTrue(DownloadQueue.isCancelling(entry.key))
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.state != DownloadState.CANCELLED && System.nanoTime() < until) {
Thread.sleep(10)
}
assertEquals(DownloadState.CANCELLED, DownloadQueue.entry(entry.key)?.state)
DownloadQueue.clear(app, entry.key)
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = "replacement"
override fun cancel(deleteFiles: Boolean) {}
}
}
assertNull("replacement must not be published during cleanup", DownloadQueue.entry(entry.key))
} finally {
release.countDown()
}
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.isCancelling(entry.key) && System.nanoTime() < until) Thread.sleep(10)
assertFalse(DownloadQueue.isCancelling(entry.key))
}
@Test fun aCancelledBattleNetJobHoldsRemovalUntilItsCleanupFinishes() {
val entry = DownloadEntry(
Store.BATTLENET, "hold-during-cleanup", "Hold during cleanup",
cleanupKey = "${Store.BATTLENET.id}:hold-during-cleanup",
)
val cancelled = CountDownLatch(1)
val release = CountDownLatch(1)
val job = object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? = null
override fun cancel(deleteFiles: Boolean) {
if (!deleteFiles) return
cancelled.countDown()
Thread({
release.await(5, TimeUnit.SECONDS)
DownloadQueue.cleanupFinished(entry.key)
}, "test-hold-cleanup").start()
}
}
DownloadQueue.enqueue(app, entry) { job }
val failed = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (DownloadQueue.entry(entry.key)?.state != DownloadState.FAILED && System.nanoTime() < failed) Thread.sleep(10)
DownloadQueue.cancel(app, entry.key)
assertTrue(cancelled.await(5, TimeUnit.SECONDS))
assertFalse(DownloadQueue.holdForRemoval(entry.key))
val held = CountDownLatch(1)
Thread({
if (DownloadQueue.stopForRemoval(app, entry.key)) held.countDown()
}, "test-hold-removal").start()
assertFalse("removal must wait for the cancellation cleanup", held.await(300, TimeUnit.MILLISECONDS))
release.countDown()
assertTrue(held.await(5, TimeUnit.SECONDS))
DownloadQueue.releaseRemoval(entry.key)
}
@Test fun heldPausedBackendRestoresAndResumesWithoutAPlaceholder() {
val entry = DownloadEntry(Store.GOG, "restored-paused", "Paused")
val ran = CountDownLatch(1)
@@ -0,0 +1,37 @@
package com.droiddeck.launcher.stores.steam
import androidx.compose.runtime.State
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.runtime.snapshots.StateObject
import com.droiddeck.launcher.stores.StoresState
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import kotlin.concurrent.thread
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE)
class SteamPickingSnapshotTest {
@Test
fun theInstallPickerIsReadableInASnapshotOpenedBeforeTheSteamEngineStarts() {
StoresState.steamPicking = null
val snapshot = Snapshot.takeMutableSnapshot()
try {
thread { SteamStore.hashCode() }.join()
assertNull(snapshot.enter { StoresState.steamPicking })
} finally {
snapshot.dispose()
}
}
@Test
fun theSteamEngineHoldsNoComposeState() {
val stateFields = SteamStore::class.java.declaredFields.filter {
StateObject::class.java.isAssignableFrom(it.type) || State::class.java.isAssignableFrom(it.type)
}
assertTrue(stateFields.joinToString { it.name }, stateFields.isEmpty())
}
}
@@ -16,6 +16,34 @@ class XboxManifestTest {
java.io.File(root, "MicrosoftGame.Config").writeText("<Game><ExecutableList><Executable Name=\"bin\\GAME.EXE\" TargetDeviceFamily=\"PC\"/></ExecutableList></Game>")
assertEquals("Bin/Game.exe", XboxInstaller.executable(root))
}
@Test fun aListedExecutableThePackageDoesNotShipFallsThroughToTheNextOne() {
val root = temporary.newFolder()
java.io.File(root, "bin/x64_dx12").mkdirs()
java.io.File(root, "bin/x64_dx12/game.exe").writeText("encrypted")
java.io.File(root, "MicrosoftGame.config").writeText("<Game><ExecutableList>" +
"<Executable Name=\"bin\\x64\\game.exe\" TargetDeviceFamily=\"PC\"/>" +
"<Executable Name=\"Launcher\\start.exe\" TargetDeviceFamily=\"PC\"/>" +
"<Executable Name=\"bin\\x64_dx12\\game.exe\" TargetDeviceFamily=\"PC\"/></ExecutableList></Game>")
assertEquals("bin/x64_dx12/game.exe", XboxInstaller.executable(root))
}
@Test fun anAmbiguouslyCasedExecutableFallsThroughToTheNextOne() {
val root = temporary.newFolder()
java.io.File(root, "Game.exe").writeText("one")
java.io.File(root, "GAME.exe").writeText("two")
java.io.File(root, "Other.exe").writeText("three")
org.junit.Assume.assumeTrue(root.listFiles().orEmpty().count { it.name.equals("game.exe", true) } == 2)
java.io.File(root, "MicrosoftGame.config").writeText("<Game><ExecutableList>" +
"<Executable Name=\"game.exe\"/><Executable Name=\"Other.exe\"/></ExecutableList></Game>")
assertEquals("Other.exe", XboxInstaller.executable(root))
}
@Test fun aPackageWithNoneOfItsListedExecutablesStillFails() {
val root = temporary.newFolder()
java.io.File(root, "Unlisted.exe").writeText("encrypted")
java.io.File(root, "MicrosoftGame.config").writeText("<Game><ExecutableList>" +
"<Executable Name=\"bin\\Game.exe\"/><Executable Name=\"Game.exe\"/></ExecutableList></Game>")
val failure = assertThrows(IllegalArgumentException::class.java) { XboxInstaller.executable(root) }
assertEquals("Missing or ambiguous Xbox launch path.", failure.message)
}
@Test fun aLauncherMenuIsSkippedForTheProgramItNames() {
val root = temporary.newFolder()
java.io.File(root, "EmuMenu").mkdir()
@@ -9,6 +9,25 @@ import org.junit.Test
class XodusDiagnosticsTest {
private val rejected = Regex(Xodus.SIGN_IN_REJECTED)
@Test fun aDeviceLimitReachesTheInstallerWithoutBecomingASignInFailure() {
val line = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-limit 200"
val tail = listOf(line).filter { it.matches(Xodus.reportable) }
assertEquals(listOf(line), tail)
assertFalse(line.matches(rejected))
assertEquals(com.droiddeck.launcher.R.string.stores_xbox_device_group_full, XboxInstaller.licenseRefusal(tail))
}
@Test fun aLaterLicenseSuccessClearsTheDeviceLimitThroughTheDiagnosticFilter() {
val stderr = listOf(
"NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-limit 200",
"NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-parsed 200",
"NEXUS_EXTRACT_DIAGNOSTIC_V1 extract-failed"
)
val tail = stderr.filter { it.matches(Xodus.reportable) }
assertEquals(stderr, tail)
assertNull(XboxInstaller.licenseRefusal(tail))
}
@Test fun aContentLicenseRejectionIsRecognised() {
assertTrue("Microsoft content licensing rejected sign-in (HTTP 401). Sign in again in Settings.".matches(rejected))
}
@@ -122,6 +122,19 @@ class LibraryEntriesTest {
assertEquals(listOf("steam", "xbox", "itch", "gamejolt"), librarySources(entries, listOf("xbox", "itch", "gamejolt"), setOf("itch", "gamejolt")))
}
@Test fun everySignedInStoreKeepsItsTabWhenItsLibraryIsEmptyOrFailedToLoad() {
val entries = listOf(LibraryEntry("epic:1", "epic", "Game", null, null, true))
val order = listOf("epic", Store.ROCKSTAR.id, "gog")
val always = alwaysLibraryTabs(listOf(Store.STEAM, Store.ROCKSTAR), stores = true, soundMode = false)
assertEquals(listOf("steam", "epic", "rockstar", "battlenet", "added"), librarySources(entries, order, always))
}
@Test fun signedOutStoresAndSoundtrackModeDoNotGainEmptyTabs() {
assertEquals(setOf("added", "battlenet"), alwaysLibraryTabs(emptyList(), stores = true, soundMode = false))
assertEquals(setOf("added", "battlenet"), alwaysLibraryTabs(listOf(Store.STEAM, Store.ROCKSTAR), stores = true, soundMode = true))
assertEquals(emptySet<String>(), alwaysLibraryTabs(emptyList(), stores = false, soundMode = false))
}
@Test fun gameKeysNameEitherAnAppOrAStoreProduct() {
GameRef.parse("app:440").let { assertEquals(440, it.appId); assertNull(it.store) }
GameRef.parse("app:-12").let { assertEquals(-12, it.appId) }
+170
View File
@@ -0,0 +1,170 @@
# Battle.net China install, update and cleanup mapping
Last reviewed: 2026-11-16, against `main` `a20528c` with this change applied. The China
version rows were observed on 2026-11-06 at
`cn.version.battlenet.com.cn/v2/products/<product>/versions`; installs use
`cn.patch.battlenet.com.cn`. #1660 added the China uid aliases to the catalogue and #1661
made the Agent driver report Battle.net's own refusal reason instead of `exit 0`; #1705 was
closed in favour of this change. This document describes the merged state and supersedes the
earlier plan that treated #1705 as pending.
## Product mapping
| Game | Store uid | China uid | China product | China version | Handling |
|---|---|---|---|---|---|
| World of Warcraft | `wow` | same uid | `wow` | 12.1.5.70783 | none |
| World of Warcraft Classic | `wow_classic` | same uid | `wow_classic` | 5.5.4.70631 | none |
| World of Warcraft Classic Era | `wow_classic_era` | same uid | `wow_classic_era` | 1.15.9.70576 | none |
| World of Warcraft Classic Anniversary | `wow_classic_anniversary` | same uid | `wow_anniversary` | 2.5.6.70577 | none |
| World of Warcraft: Forever | `wow_forever` | same uid, or unknown uid with product `wowf` | `wowf` | 1.60.1.70790 | in `TITLES`, excluded from `STORE` |
| Diablo III | `diablo3` | `d3cn` | `d3cn` | 2.8.1.101167 | alias; install and update use `d3cn` |
| Diablo II: Resurrected | `osi` | `osic` | `osic` | 3.3.93854 | alias; install and update use `osic` |
| StarCraft II | `s2` | `s2_cn` | `s2c` | 5.0.17.98370 | alias; install maps uid to `s2_cn` and product to `s2c` |
| Diablo Immortal | `anbs` | `anbs_cn` | `anbs` | no `cn` row | uid alias only; unverified |
| Hearthstone | `hs_beta` | same uid | `hsb` | 37.0.2.256589.255790 | none |
| Heroes of the Storm | `heroes` | same uid | `hero` | 2.55.3.89566 | none |
| Overwatch 2 | `prometheus` | same uid | `pro` | 2.25.1.0.155284N | none |
| StarCraft: Remastered | `s1` | same uid | `s1` | 1.23.10.11269 | none |
| Warcraft III: Reforged | `w3` | same uid | `w3` | no `cn` row | none |
| `wow_classic_titan` | not in the catalogue | unconfirmed | `wow_classic_titan` | not checked | out of scope |
No separate China uid has been observed for `wow`, the Classic flavors, `hs_beta`,
`heroes`, `prometheus`, `s1` or `w3`; the client reports the store uid for those.
## What the change does
### Catalogue
`BattleNet.CN_UIDS` maps the China uids to the existing cards instead of adding titles of
their own:
- `d3cn` resolves to the `diablo3` card with launch code `D3CN` and product `d3cn`. The
standalone `d3cn` title and the `STORE`/`fetchCovers` filters for it are gone.
- `osic` resolves to `osi` with product `osic`; `s2_cn` resolves to `s2` with product
`s2c`; `anbs_cn` resolves to `anbs` with product `anbs`.
- Locale suffixes resolve through the base alias, so `osic_zhcn` and `s2_cn_zhcn` name the
same cards.
A `BattleNet.Game` keeps the store uid in `uid` and the Agent's uid in `installUid`. The
Library, the desktop shortcut, the store "installed" state, covers and the launch code
therefore agree; a China Diablo III install still lands on the `diablo3` card and launches
with `D3CN`.
### Install driver
On a China agent (`region == "cn"`) every install sends `account_country = CHN` and
`geo_ip_country = CN`, not only the remapped products. Products `osi`, `s2` and `diablo3`
become `osic`, `s2c` and `d3cn`; uids become `osic`, `s2_cn` and `d3cn` (`anbs` becomes
`anbs_cn`). Updates and uninstalls use the uid the Agent recorded, so they are not
remapped.
### Update checks
`BattleNetInstall.check()` reads `.build.info`. When its active branch is `cn`, the version
query uses the China product (`osic`, `s2c`, `d3cn`); other branches keep the store
product. `checkedAt` and `updates` are keyed by `id@folder` (`updateKey`), so an
international and a China copy of Diablo III neither suppress nor offer each other's
update. `anbs` has no China product mapping, so its China check still asks `anbs`, which
has no `cn` row.
### Install identity
Update and uninstall select the installed record by its exact folder and use the Agent uid
recorded for that folder. A folder with no matching registration is not retargeted to
another copy; a game detail opened from a shortcut passes its folder through, so two
Diablo III installs, or WoW flavors sharing one folder, do not act on each other.
### Cancellation ownership
Before an install starts, a raw `product.db` and `system.reg` query records whether the
target folder already has a registration. The query does not require the folder to exist
and does not deduplicate by launch code. The result is `PREEXISTING = pending | 0 | 1`; the
installer worker resolves it once, persists it through `SavedQueue`, and a shared
`Ownership` holder keeps the decision across pause and resume. `SavedQueue` only receives
the item after `DownloadQueue.enqueue()` accepts it (`onAccepted`), so a rejected enqueue
cannot leave ownership for a task that will not run.
Cancel uninstalls only a registration that appeared after the task recorded "no
registration"; a pre-existing registration is never removed. If either registration source
cannot be read, the decision stays conservative (no destructive cleanup) and is not
persisted as final. Cleanup is skipped when the worker has not stopped after the wait.
`clear()` and `cancel()` share one cleanup claim, and a new enqueue for the same game is
rejected while that cleanup runs.
## Why the version lines differ
| Product | Observed rows | Build | Note |
|---|---|---|---|
| `osi` | `us`, `eu`, `kr` | 3.3.93847 | no `cn` row |
| `osic` | `cn` | 3.3.93854 | China only |
| `s2` | `cn` | 5.0.14.93333 | older China line |
| `s2c` | `cn` | 5.0.17.98370 | current China line |
| `d3` | `us`, `eu`, `kr`, `tw` | 2.8.0.99920 | no `cn` row |
| `d3cn` | `cn` | 2.8.1.101167 | China only |
| `anbs` | no `cn` row | - | no separate `anbs_cn` product |
| `w3` | no `cn` row | - | keeps the global build |
### Products without a `cn` row
`osi`, `d3`, `anbs` and `w3` have no `cn` row, and `anbs_cn` has no product or repository
of its own. For `osi` and `d3`, an install made with the store product in a clean folder
misses the China line and the Agent falls back to the international build: for Diablo II:
Resurrected that is 3.3.93847 instead of the China 3.3.93854. The install succeeds, but
`.build.info` and `product.db` now follow the international line, and the BuildConfig
differs, so renaming the folder cannot migrate it. `w3` has no China line at all and keeps
the global build; `anbs` is unverified (see below).
### The two sides then disagree
When the wrong product is installed, `product.db` records `osi` while the China client
enumerates `osic`. DroidDeck shows the game as installed, the client shows it as missing,
and update, repair and uninstall each follow a different product. No error is reported,
which makes this state harder to notice than a visible failure. `s2` is the milder variant:
it does have a `cn` row, but that row is the older 5.0.14.93333 line, while `s2c` is the
current 5.0.17.98370.
### Error 800
Error 800 is not only a China-copy conflict. A folder registered in `product.db`, an empty
directory, a directory with residual files from an earlier attempt, or a path earlier
registered by a different product can trigger it. This change does not alter those triggers
and does not clean them automatically; #1661 now surfaces Battle.net's own refusal reason,
so the failure is reported instead of looking like `exit 0`.
## Automated coverage
- `BattleNetTest`: China uid aliases including locale suffixes, the `d3cn` alias on the
`diablo3` card, folder selection between two Diablo III installs, WoW flavors in one folder,
registrations for a missing folder, pre-existing registration protection,
created-registration cleanup, registration read failure, restored ownership, per-folder
update state, and the cancelled install's folder hold against uninstall.
- `BattleNetInstallTest`: `chinaProduct()`, the `s2c` version URL, the `osic`, `s2c` and
`anbs` version rows, and per-folder update keys.
- `DownloadQueueRetryTest`: double `clear()` single-flight, a rejected enqueue not running
its accepted callback, a rejected update preserving the saved ownership snapshot,
factoryless cleanup, client-download exclusion, a removal hold waiting for a cancelled
Battle.net cleanup, and the restore, install, enqueue chain.
- `tools/tests/test_battlenet.py`: the driver's China uid and product maps, the
install-only condition, and the `CHN`/`CN` request fields.
## Not covered
- Migration of existing wrong-product installs (`osi`, `d3`, `s2`): uninstall through
DroidDeck (it calls the Agent with the uid recorded for the folder) and install again;
renaming or deleting the folder alone leaves the `product.db` registration behind and can
hit 800 on the next attempt.
- Automatic cleanup of the wider 800 triggers; #1661 surfaces the reason, it does not
remove the registration or the folder.
- Diablo Immortal: `anbs` has no `cn` row and `anbs_cn` has no separate product, so whether
the Agent falls back to the international build and whether the client accepts `anbs_cn`
is unverified. This change does not claim to fix it.
- Store region filtering: the store is a static global catalogue and there is no separate
China "owned" feed.
- WoW Classic family cards and deduplication: `STORE` keeps one `WoWC` card and the game
list keeps one folder per launch code. This is an existing design, not a China uid issue.
- `wow_forever` (in `TITLES`, excluded from `STORE`) and `wow_classic_titan` (not in
`TITLES`) catalogue entries.
- Covers for titles without a Steam app id still depend on `us.shop.battle.net`.
- The Battle.net client installer's region; it is pinned to `downloader.battle.net`.
Refs: #1660, #1661, #1705 (closed).
+9
View File
@@ -193,6 +193,15 @@ A Unity game under FEX (`UnityPlayer.dll` for Windows builds under Proton,
turns it off: without TSO such games can deadlock or crash (seen with Megabonk
and Crab Game). A FEX preset chosen for the game itself still applies.
An Inno Setup installer added as a game runs with the Stability preset's FEX
settings (full TSO, full x87 precision, no multiblock). Under the default
Performance + TSO preset the 32-bit setup stub corrupts its own paths and stops
with Wine's "Path not fpund." dialog (#1277, #3067). The stub is found by the
setup loader's offset-table ID in its resources, or by the `Inno` marker that
loaders older than 5.1.5 keep at offset 0x30. GOG installs avoid the stub by
extracting natively. A FEX preset chosen for the installer's own entry still
applies.
Games launched through Proton get `vblank_mode=0`, so OpenGL does not wait for
each screen refresh. Wine asks for a swap interval of 1 on every OpenGL window, and WineD3D's front-buffer
drawing (DirectDraw, Direct3D 1–7) never lowers it, so those games ran at the
+13
View File
@@ -150,6 +150,19 @@ The SPIR-V version the driver gets:
- This is what Dawn ("Disable SPIR-V 1.4 on Android ARM"), ANGLE (`supportsSPIRV14`) and naga
(`AVOID_SPIRV_COPY_LOGICAL`) do for a proprietary compiler they cannot trust.
Geometry shaders:
- The Mali-G610's driver (r38p1) crashes compiling Zink's geometry shaders, always at the same
place (SIGSEGV at 0x40 in `cmpbe_v2_compile_multiple_shaders`): its shader for `GL_QUADS`, and
a GLSL geometry shader that only passes triangles on.
- A geometry shader that only passes triangles on, from a plain Vulkan program, does not crash it
but draws nothing, in SPIR-V 1.0, 1.3 and 1.6, with and without the layer.
- Zink writes them in SPIR-V 1.6 with the Vulkan memory model, which the version cap leaves alone.
Lowering them would not help, since the plain shader draws nothing at 1.0 and 1.3 either.
- On ARM GPUs the layer reports no `geometryShader` to Zink (engine name `mesa zink`). Mesa then
splits quads into triangles itself, and Zink still offers OpenGL 3.2. DXVK keeps the feature: it
needs it for D3D10 and 11.
- `DROIDDECK_MALI_COMPAT_NO_GS=0` keeps the feature for Zink, `=1` hides it from every application.
Files:
- `layer.c`: loader plumbing, feature and limit reporting, device creation, the hook table.
- `pipeline.c`: pipelines, shader modules, viewports.
@@ -1,9 +0,0 @@
[Desktop Entry]
Name=Return to Gaming Mode
Comment=Log out of the desktop and go back to Steam
Exec=dbus-send --session --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout
Icon=steamdeck-gaming-return
Terminal=false
Type=Application
StartupNotify=false
NoDisplay=true
+5 -1
View File
@@ -229,12 +229,16 @@ fi
if ! /usr/local/bin/droiddeck-pipewire start; then
echo "== pipewire: not running; screen capture has no picture"
fi
return_gaming=/run/droiddeck/return-gaming
mkdir -p /run/droiddeck
rm -f "$return_gaming"
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
dbus-run-session -- startplasma-wayland
rc=$?
/usr/local/bin/droiddeck-pipewire stop
echo "== droiddeck-desktop: Plasma ended ($rc)"
if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ]; then
if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ] && [ -e "$return_gaming" ]; then
rm -f "$return_gaming"
/usr/local/bin/droiddeck-steam-launch bigpicture
sleep 30
fi
@@ -0,0 +1,9 @@
[Desktop Entry]
Name=Return to Gaming Mode
Comment=Log out of the desktop and go back to Steam
Exec=sh -c ": > /run/droiddeck/return-gaming; dbus-send --session --print-reply --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout >/dev/null || rm -f /run/droiddeck/return-gaming"
Icon=steamdeck-gaming-return
Terminal=false
Type=Application
StartupNotify=false
NoDisplay=true
@@ -135,6 +135,9 @@ function job(text) {
return /"state"\s*:\s*\d+/.test(bare) || /"download_current"\s*:/.test(bare);
}
var CHINA = {osi: "osic", s2: "s2_cn", anbs: "anbs_cn", diablo3: "d3cn"};
var CHINA_PRODUCT = {osi: "osic", s2: "s2c", diablo3: "d3cn"};
function install() {
// Blizzard's China repository moved to cn.patch.battlenet.com.cn; cn.patch.battle.net only redirects away from it.
var patch = zone == "cn" ? "cn.patch.battlenet.com.cn" : zone + ".patch.battle.net";
@@ -193,6 +196,17 @@ try {
token = field(agent, "authorization");
zone = field(agent, "region") || "us";
if (!token) throw new Error("no authorization from the agent");
// The China client installs these under uids of its own. s2_cn is served from s2c; anbs_cn shares anbs.
if (zone == "cn" && action == "install") {
country = "CHN";
region = "CN";
if (CHINA[uid]) {
product = CHINA_PRODUCT[uid] || product;
uid = CHINA[uid];
}
}
// The app cancels an install by the uid the Agent really used; report the remapped one.
save(".uid", uid);
if (action == "install") install(); else if (action == "update") update(); else uninstall();
} catch (e) {
save(".error", e.message || "the agent stopped answering");
@@ -1501,6 +1515,17 @@ def read_status(path):
return None
def read_text(path):
try:
with open(path, "rb") as f:
data = f.read()
except OSError:
return None
if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
return data.decode("utf-16", "replace").strip()
return data.decode("utf-8", "replace").strip()
def summary(status):
out = {key: status[key] for key in REPORTED if key in status}
for key in ("download_current", "download_total"):
@@ -1553,7 +1578,7 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
emit("STATE", "starting")
base = os.path.join(CACHE, "agent-%s" % uid)
os.makedirs(CACHE, exist_ok=True)
for suffix in (".json", ".game", ".form", ".error"):
for suffix in (".json", ".game", ".form", ".error", ".uid"):
try:
os.unlink(base + suffix)
except OSError:
@@ -1571,10 +1596,15 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
return 1
seen = None
mark = None
effective = None
moved = time.monotonic()
stalled = False
while True:
done = child.poll() is not None
if effective is None:
effective = read_text(base + ".uid")
if effective:
emit("UID", effective)
status = read_status(base + ".json")
if status is not None and action != "uninstall":
brief = summary(status)
@@ -1620,8 +1650,13 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country="
if reason is None and action != "uninstall" and game.get("installed") is True \
and (game.get("playable") is True or status.get("state") == DONE_STATE):
binary = ((game.get("binaries") or {}).get("game") or {}).get("relative_path", "")
emit("DONE", json.dumps({"install_dir": game.get("install_dir", windows), "exe": binary,
"version": game.get("local_version", "")}, sort_keys=True))
if effective is None:
effective = read_text(base + ".uid")
result = {"install_dir": game.get("install_dir", windows), "exe": binary,
"version": game.get("local_version", "")}
if effective:
result["uid"] = effective
emit("DONE", json.dumps(result, sort_keys=True))
say("%s %s in %s" % (uid, "updated" if action == "update" else "installed", game.get("install_dir", windows)))
return 0
if reason is None and action == "uninstall" and (game.get("installed") is False or answer == {}):
@@ -66,6 +66,69 @@ DOTNET_FEX = {
"FEX_HALFBARRIERTSOENABLED": "1",
"FEX_X87REDUCEDPRECISION": "0",
}
STABILITY_FEX = dict(DOTNET_FEX, FEX_MULTIBLOCK="0")
# Setup loader offset-table IDs, as innoextract's known_setup_loader_versions lists them. Loaders
# from 5.1.5 keep the table in a resource; older ones also put "Inno" at file offset 0x30.
INNO_LOADER_IDS = (b"rDlPtS", b"nS5W7dT\x83\xaa\x1b\x0fj")
INNO_RESOURCE_LIMIT = 4 << 20
def is_inno_setup(path):
try:
with open(path, "rb") as exe:
head = exe.read(4096)
if head[:2] != b"MZ":
return False
if head[0x30:0x34] == b"Inno":
return True
pe = int.from_bytes(head[0x3C:0x40], "little")
if head[pe:pe + 4] != b"PE\0\0" or int.from_bytes(head[pe + 4:pe + 6], "little") != 0x14C:
return False
count = int.from_bytes(head[pe + 6:pe + 8], "little")
table = pe + 24 + int.from_bytes(head[pe + 20:pe + 22], "little")
for entry in range(table, table + 40 * count, 40):
if head[entry:entry + 8].rstrip(b"\0") == b".rsrc":
exe.seek(int.from_bytes(head[entry + 20:entry + 24], "little"))
size = int.from_bytes(head[entry + 16:entry + 20], "little")
resources = exe.read(min(size, INNO_RESOURCE_LIMIT))
return any(marker in resources for marker in INNO_LOADER_IDS)
except OSError:
pass
return False
STORE_LAUNCHER = ".droiddeck-launch.bat"
STORE_SIDECAR = ".droiddeck-store.json"
def store_game_exe(exe):
if os.path.basename(exe).lower() != STORE_LAUNCHER:
return exe
folder = os.path.dirname(exe)
try:
with open(os.path.join(folder, STORE_SIDECAR), encoding="utf-8") as source:
sidecar = json.load(source)
except (OSError, ValueError):
return exe
target = sidecar.get("exe") if isinstance(sidecar, dict) else None
if not isinstance(target, str) or not target.strip() or "\0" in target:
return exe
normalized = target.replace("\\", "/")
if ":" in normalized or normalized.startswith("/") or ".." in normalized.split("/"):
return exe
relative = os.path.normpath(normalized)
if os.path.isabs(relative) or relative in (".", "..") or relative.startswith(".." + os.sep):
return exe
candidate = os.path.join(folder, relative)
if not os.path.isfile(candidate):
return exe
root = os.path.realpath(folder)
try:
if os.path.commonpath((root, os.path.realpath(candidate))) != root:
return exe
except ValueError:
return exe
return candidate
def game_files(exe):
@@ -89,6 +152,7 @@ def game_files(exe):
class Game:
def __init__(self, exe, args, app_id=""):
exe = store_game_exe(exe)
self.exe = exe
self.args = args
self.app_id = app_id
@@ -191,6 +255,12 @@ def split_second_x87_fip(game):
return {"FEX_JITFEATURES": "enablex87fip"}, [], "Split/Second: FEX x87 FIP emulation on (its SecuROM stops with error 8016 without it)"
@fix
def inno_setup_stability(game):
if is_inno_setup(game.exe):
return STABILITY_FEX, [], "Inno Setup installer: FEX Stability settings (under Performance + TSO the 32-bit setup stub corrupts its own paths)"
@fix
def doom_2016_swapchain_images(game):
if "doomx64vk.exe" in game.files and game.stem in ("doomx64", "doomx64vk"):
@@ -273,7 +343,7 @@ def with_system_settings(text, settings):
# The game ignores -ini: overrides and deletes a writable Engine.ini after reading it, so this runs at every launch.
def dragon_quest_monsters_4_mesh_detail(exe, env):
project = Path(exe).stem.split("-", 1)[0]
project = Path(store_game_exe(exe)).stem.split("-", 1)[0]
if not project.lower().startswith("dragonquestmonsters4"):
return
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
@@ -398,7 +468,7 @@ def zomboid_rewrite(node):
def project_zomboid_jvm(command):
if len(command) <= 2:
return
exe = Path(command[2])
exe = Path(store_game_exe(command[2]))
if not exe.stem.lower().startswith("projectzomboid"):
return
settings = exe.with_suffix(".json")
@@ -721,12 +791,15 @@ def apply_config(env, config, app_id, fixes=None):
def render_path_defaults(command, env):
if len(command) < 3 or command[1] != "waitforexitandrun" or Path(command[2]).name.lower() != "spintires.exe":
if len(command) < 3 or command[1] != "waitforexitandrun":
return None
exe = Path(store_game_exe(command[2]))
if exe.name.lower() != "spintires.exe":
return None
own = env.get("DXVK_CONFIG", "")
if re.search(r"(?:^|;)\s*dxvk\.tilerMode\s*=", own) or env.get("DXVK_CONFIG_FILE"):
return None
if Path("dxvk.conf").is_file() or Path(command[2]).with_name("dxvk.conf").is_file():
if Path("dxvk.conf").is_file() or exe.with_name("dxvk.conf").is_file():
return None
driver = env.get("VK_DRIVER_FILES", env.get("VK_ICD_FILENAMES", ""))
if Path(driver).parent.name != "DD-Turnip_v0.4.0":
@@ -1290,7 +1363,7 @@ def dirt_ws2_wanted(command, env):
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if len(command) < 3 or not prefix or not os.path.isfile(DIRT_WS2):
return None
game = DIRT_GAMES.get(os.path.splitext(os.path.basename(command[2]))[0].lower())
game = DIRT_GAMES.get(os.path.splitext(os.path.basename(store_game_exe(command[2])))[0].lower())
if not game or not dirt_telemetry_on(prefix, game) or proton_has_dirt_fix(command[0]):
return None
return prefix if os.path.lexists(prefix_ws2(prefix)) else None
@@ -1347,7 +1420,7 @@ def ego_core_plan(command, env):
count = windows_core_count(env)
if not count or len(command) < 3:
return None
folder = Path(command[2]).parent
folder = Path(store_game_exe(command[2])).parent
path = folder / EGO_RESTRICTIONS
try:
raw = path.read_bytes()
@@ -1676,14 +1749,26 @@ def main():
if note:
print("droiddeck-game-env: " + note, file=sys.stderr)
else:
# An installer started with the run verb gets the same Stability settings as one started with
# waitforexitandrun; explicit game settings still win over them in apply_config.
installer = {}
if len(command) > 2 and command[1] == "run" and is_inno_setup(command[2]):
installer = dict(STABILITY_FEX)
print("droiddeck-game-env: Inno Setup installer: FEX Stability settings", file=sys.stderr)
path = Path.home() / ".config/droiddeck/game-environment.json"
try:
with path.open(encoding="utf-8") as source:
config = json.load(source)
env = apply_config(env, sync_config(config, app_id), app_id)
synced = sync_config(config, app_id)
if installer:
# A FEX preset chosen for the game itself still wins, as on every other launch path.
game = config.get("games", {}).get(app_id, {})
synced["games"][app_id].update({k: v for k, v in game.items() if k in STABILITY_FEX})
env = apply_config(env, synced, app_id, installer)
except FileNotFoundError:
pass
env = dict(env, **installer)
except (OSError, ValueError, TypeError, AttributeError):
env = dict(env, **installer)
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
if waiting:
before_debug = env
@@ -224,15 +224,23 @@ if [ -n "${DD_VK_DRIVER:-}" ]; then
unset dd_icd_lib
fi
dd_webhelper_layout() {
local layout
if [ -n "${DD_VKBRIDGE_WEBHELPER_ARGS:-}" ]; then
printf '%s\n' "$DD_VKBRIDGE_WEBHELPER_ARGS"
elif [ -z "${DD_VKBRIDGE_CEF_ANGLE:-}" ]; then
echo stock
elif [ "$DD_VKBRIDGE_CEF_ANGLE" = vulkan ] && [ "${DD_VKBRIDGE_CEF_VULKAN:-1}" != 0 ]; then
echo "--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan"
else
echo "--use-gl=angle --use-angle=$DD_VKBRIDGE_CEF_ANGLE"
return
fi
if [ -z "${DD_VKBRIDGE_CEF_ANGLE:-}" ]; then
echo stock
return
fi
# ANGLE switches must not replace the helper's stable single-process layout.
layout="--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
if [ "$DD_VKBRIDGE_CEF_ANGLE" = vulkan ] && [ "${DD_VKBRIDGE_CEF_VULKAN:-1}" != 0 ]; then
layout="$layout --use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan"
else
layout="$layout --use-gl=angle --use-angle=$DD_VKBRIDGE_CEF_ANGLE"
fi
printf '%s\n' "$layout"
}
dd_now_ms() {
if [ -n "${EPOCHREALTIME:-}" ]; then
@@ -1141,6 +1149,7 @@ case $mode in
droiddeck-steam-library "$steam_root" || true
step "setting up the ARM64 Proton compatibility tool"
steam-compatibility "$steam_root" || true
steam-compatibility "$steam_root" --seed-arm64-tools || true
if [ -z "${DD_DESKTOP:-}" ] && [ "${DD_STEAM_UI:-}" != desktop ]; then
droiddeck-steam-ui-scale "$steam_root" "${DD_WIDTH:-1280}" "${DD_HEIGHT:-720}" || true
fi
@@ -5,6 +5,7 @@ import re
import runpy
import shutil
import sys
import tempfile
TOOL = "droiddeck-proton-arm64"
TOOL_11 = "droiddeck-proton-11-arm64"
@@ -26,6 +27,8 @@ SNIPER_APPID = "1628350"
SLR4_APPID = "4183110"
FEX_DEPENDENCIES = (FEX_APPID, SNIPER_APPID, SLR4_APPID)
REQUIRED_TOOLS = (PROTON_ARM64_APPID,) + FEX_DEPENDENCIES
ARM64_TOOL_DEPENDENCIES = (("1826330", "Proton EasyAntiCheat Runtime"),
("1070560", "Steam Linux Runtime 1.0 (scout)"))
# "0" = the app's "Valve Proton only when needed": Valve's ARM64 Proton is fetched only for a title or
# default set to a tool built from it, or while no own Proton build is installed.
VALVE_PROTON_ENV = "DD_VALVE_PROTON"
@@ -1012,10 +1015,15 @@ def manifest_text(appid, name, installdir, bare=False):
return text[:-2] + ' "AutoUpdateBehavior" "1"\n}\n' if bare else text
def app_manifest(steam_root, app):
def manifest_paths(steam_root, app):
for library in libraries(steam_root):
yield os.path.join(library, "steamapps", "appmanifest_%s.acf" % app)
def app_manifest(steam_root, app):
for path in manifest_paths(steam_root, app):
try:
with open(os.path.join(library, "steamapps", "appmanifest_%s.acf" % app), encoding="utf-8", errors="replace") as f:
with open(path, encoding="utf-8", errors="replace") as f:
return tokenize(f.read())
except OSError:
continue
@@ -1030,6 +1038,57 @@ def manifest_flags(tokens):
return 0
def installed_manifest(path):
try:
with open(path, encoding="utf-8", errors="replace") as f:
return bool(manifest_flags(tokenize(f.read())) & FULLY_INSTALLED)
except OSError:
return False
def seed_unavailable_arm64_tools(steam_root):
entries = appinfo_entries(os.path.join(steam_root, "appcache", "appinfo.vdf"),
[app for app, _ in ARM64_TOOL_DEPENDENCIES])
steamapps = os.path.join(steam_root, "steamapps")
os.makedirs(steamapps, exist_ok=True)
seeded = []
for app, display in ARM64_TOOL_DEPENDENCIES:
entry = entries.get(app)
if entry is not None:
if entry["type"] not in ("", "tool"):
continue
if "arm64" in entry["osarch"] or "aarch64" in entry["osarch"]:
continue
existing = [p for p in manifest_paths(steam_root, app) if os.path.isfile(p)]
if any(installed_manifest(p) for p in existing):
continue
name = (entry or {}).get("name") or display
installdir = (entry or {}).get("installdir") or name
path = existing[0] if existing else os.path.join(steamapps, "appmanifest_%s.acf" % app)
temporary = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8",
dir=os.path.dirname(path),
prefix=".appmanifest_", delete=False) as f:
temporary = f.name
f.write(manifest_text(app, name, installdir, True))
if existing:
os.replace(temporary, path)
else:
os.link(temporary, path)
except OSError as e:
print("steam-compatibility: could not mark %s installed (%s)" % (app, e))
continue
finally:
if temporary is not None:
try:
os.unlink(temporary)
except OSError:
pass
seeded.append(app)
return seeded
def valve_proton_on_demand():
return os.environ.get(VALVE_PROTON_ENV) == "0"
@@ -1801,6 +1860,11 @@ def main():
steam_root = sys.argv[1]
if "--valve-proton-needed" in sys.argv[2:]:
sys.exit(0 if valve_proton_needed(steam_root) else 1)
if "--seed-arm64-tools" in sys.argv[2:]:
seeded = seed_unavailable_arm64_tools(steam_root)
if seeded:
print("steam-compatibility: marked unavailable ARM64 tool(s) installed: %s" % ", ".join(seeded))
return
if "--x64" in sys.argv[2:]:
x64_repoint(steam_root, os.environ.get("DD_COMPAT_TOOL"), "--live" in sys.argv[2:])
return
+112 -8
View File
@@ -6,6 +6,7 @@
#include <dlfcn.h>
#include <errno.h>
#include <limits.h>
#include <link.h>
#include <linux/input.h>
#include <pthread.h>
#include <stdatomic.h>
@@ -15,6 +16,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <unistd.h>
@@ -34,6 +36,9 @@
"NAME=\"Xbox 360 Controller (%d)\"\n" \
"PHYS=\"usb-fakeinput/input%d\"\n"
#define STEAM_VIRTUAL_VENDOR 0x28de
#define STEAM_VIRTUAL_PRODUCT 0x11ff
#define PARENT_NAME "droiddeck-input"
#define PARENT_SYSPATH_FORMAT "/sys/devices/droiddeck%d/" PARENT_NAME "%d"
#define EVENT_SYSPATH_FORMAT PARENT_SYSPATH_FORMAT "/event%d"
@@ -49,6 +54,8 @@ struct pad {
int live;
};
static const char *ring_uevent_format(void);
static struct pad pads[PAD_MAX];
static struct pad parents[PAD_MAX];
static int pad_count;
@@ -89,7 +96,7 @@ static void discover_pads(void) {
snprintf(pad->syspath, sizeof(pad->syspath), EVENT_SYSPATH_FORMAT, (int)slot, (int)slot,
(int)slot);
snprintf(pad->devnode, sizeof(pad->devnode), "/dev/input/event%ld", slot);
snprintf(pad->uevent, sizeof(pad->uevent), PAD_UEVENT_FORMAT, (int)slot, (int)slot);
snprintf(pad->uevent, sizeof(pad->uevent), ring_uevent_format(), (int)slot, (int)slot);
pad->devnum = makedev(13, EVENT_MINOR_BASE + (unsigned int)slot);
pad->node = (int)slot;
pad->live = 1;
@@ -137,6 +144,10 @@ static int any_virtual_pad(void) {
return 0;
}
static const char *ring_uevent_format(void) {
return uinput_enabled() && any_virtual_pad() ? PAD_PHYSICAL_UEVENT_FORMAT : PAD_UEVENT_FORMAT;
}
static void refresh_locked(int node) {
struct pad *pad = &pads[node];
@@ -167,9 +178,7 @@ static void refresh_locked(int node) {
} else {
snprintf(pad->devnode, sizeof(pad->devnode), "/dev/input/event%d", node);
pad->live = 1;
if (uinput_enabled())
snprintf(pad->uevent, sizeof(pad->uevent),
any_virtual_pad() ? PAD_PHYSICAL_UEVENT_FORMAT : PAD_UEVENT_FORMAT, node, node);
snprintf(pad->uevent, sizeof(pad->uevent), ring_uevent_format(), node, node);
}
}
sync_parent(node);
@@ -441,11 +450,102 @@ static void *next_symbol(const char *name) {
char *dd_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *))
__attribute__((visibility("hidden")));
static int caller_is_winebus(void *caller) {
static int caller_in_library(void *caller, const char *library) {
Dl_info info;
if (dladdr(caller, &info) == 0 || info.dli_fname == NULL) return 0;
return strstr(info.dli_fname, "winebus.so") != NULL;
return strstr(info.dli_fname, library) != NULL;
}
static int caller_is_winebus(void *caller) { return caller_in_library(caller, "winebus.so"); }
static int note_winebus(struct dl_phdr_info *info, size_t size, void *data) {
(void)size;
if (info->dlpi_name == NULL || strstr(info->dlpi_name, "winebus.so") == NULL) return 0;
*(int *)data = 1;
return 1;
}
static int winebus_reads_udev(void) {
const char *x360 = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
int loaded = 0;
if (x360 != NULL && atoi(x360) != 0) return 0;
dl_iterate_phdr(note_winebus, &loaded);
return loaded;
}
static int ring_pad_fd(int fd) {
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
const char *entry;
struct stat opened;
struct stat ring;
char path[PATH_MAX];
if (spec == NULL || fstat(fd, &opened) != 0) return 0;
for (entry = spec; *entry != '\0';) {
char *end;
long slot = strtol(entry, &end, 10);
const char *next = strchr(entry, ';');
size_t length;
if (end != entry && *end == '=' && slot >= 0 && slot < RING_MAX) {
length = next != NULL ? (size_t)(next - end - 1) : strlen(end + 1);
if (length < sizeof(path)) {
memcpy(path, end + 1, length);
path[length] = '\0';
if (stat(path, &ring) == 0 && ring.st_dev == opened.st_dev && ring.st_ino == opened.st_ino) return 1;
}
}
if (next == NULL) break;
entry = next + 1;
}
return 0;
}
__attribute__((visibility("hidden"))) void dd_ring_pad_sdl_id(int fd, unsigned long request, void *arg,
void *caller, int rc) {
struct input_id *id = arg;
if (rc != 0 || request != EVIOCGID || id == NULL) return;
if (!caller_in_library(caller, "libSDL") || !winebus_reads_udev() || !ring_pad_fd(fd)) return;
id->vendor = STEAM_VIRTUAL_VENDOR;
id->product = STEAM_VIRTUAL_PRODUCT;
}
typedef int (*sdl_rumble_fn)(void *, uint16_t, uint16_t, uint32_t);
static _Atomic(sdl_rumble_fn) real_sdl_rumble;
static __thread int winebus_sdl_call;
static int winebus_sdl_rumble(void *joystick, uint16_t low, uint16_t high, uint32_t duration) {
sdl_rumble_fn real = atomic_load_explicit(&real_sdl_rumble, memory_order_acquire);
int result;
if (!caller_is_winebus(__builtin_return_address(0))) return real(joystick, low, high, duration);
if (low != 0 || high != 0) duration = 0;
winebus_sdl_call = 1;
result = real(joystick, low, high, duration);
winebus_sdl_call = 0;
return result;
}
static void *winebus_sdl_rumble_dlsym(void *handle, const char *name) {
(void)handle;
(void)name;
return (void *)winebus_sdl_rumble;
}
static void *sdl_rumble_target(void *handle, void *(*forward)(void *, const char *)) {
sdl_rumble_fn expected = NULL;
sdl_rumble_fn found;
if (handle == RTLD_NEXT || handle == RTLD_DEFAULT) return NULL;
found = (sdl_rumble_fn)forward(handle, "SDL_JoystickRumble");
if (found == NULL) return NULL;
atomic_compare_exchange_strong_explicit(&real_sdl_rumble, &expected, found, memory_order_acq_rel,
memory_order_acquire);
if (atomic_load_explicit(&real_sdl_rumble, memory_order_acquire) != found) return NULL;
return (void *)winebus_sdl_rumble_dlsym;
}
__attribute__((visibility("hidden"))) int dd_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd,
@@ -454,7 +554,8 @@ __attribute__((visibility("hidden"))) int dd_winebus_rumble_ioctl(int (*real)(in
struct ff_effect *effect = arg;
__u16 length;
if (request != EVIOCSFF || effect == NULL || effect->type != FF_RUMBLE || !caller_is_winebus(caller)) return 0;
if (request != EVIOCSFF || effect == NULL || effect->type != FF_RUMBLE) return 0;
if (!caller_is_winebus(caller) && !(winebus_sdl_call && caller_in_library(caller, "libSDL"))) return 0;
length = effect->replay.length;
effect->replay.length = 0;
*rc = real(fd, request, arg);
@@ -1195,7 +1296,10 @@ static void *own_dlsym(void *handle, const char *name) {
__attribute__((visibility("hidden"), used)) void *inputudev_dlsym_target(void *handle, const char *name) {
void *forward = real_dlsym();
(void)handle;
if (forward != NULL && name != NULL && strcmp(name, "SDL_JoystickRumble") == 0) {
void *rumble = sdl_rumble_target(handle, forward);
if (rumble != NULL) return rumble;
}
if (name != NULL && strncmp(name, "udev_", 5) == 0 && own_udev_symbol(name) != NULL &&
!steam_client_process())
return (void *)own_dlsym;
+3
View File
@@ -424,6 +424,8 @@ int dd_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute
int dd_vdec_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int dd_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
void *arg, void *caller, int *rc) __attribute__((visibility("hidden")));
void dd_ring_pad_sdl_id(int fd, unsigned long request, void *arg, void *caller, int rc)
__attribute__((visibility("hidden")));
int dd_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg,
int *rc) __attribute__((visibility("hidden")));
@@ -444,6 +446,7 @@ int ioctl(int fd, unsigned long request, ...) {
if (dd_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc;
if (dd_writewatch_ioctl(real, fd, request, arg, &rc)) return rc;
if (!dd_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg);
dd_ring_pad_sdl_id(fd, request, arg, __builtin_return_address(0), rc);
dd_kgsl_track(real, fd, request, arg, &rc);
dd_kgsl_chip_id_fixup(request, arg, rc);
if (arg == NULL || !is_link_query(request)) return rc;
+4 -2
View File
@@ -452,7 +452,8 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
char resolved_target[PATH_MAX];
// Only intercept binaries/scripts within DDNATV_ROOT
if ((g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(filename)) {
if ((g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(filename) ||
is_bound_guest_program(target)) {
struct exec_probe probe;
const char *elf_target = select_exec_target(target, resolved_target, sizeof(resolved_target), &probe);
if (probe.is_elf && !probe.is_dynamic) static_elf = elf_target;
@@ -969,7 +970,8 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path,
}
char *const *orig_ep = envp ? envp : environ;
int in_root = (g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(path);
int in_root = (g_ddnatv_root[0] != '\0' && strncmp(target, g_ddnatv_root, g_ddnatv_root_len) == 0) || is_mapped_guest_path(path) ||
is_bound_guest_program(target);
struct exec_probe probe;
char resolved_target[PATH_MAX];
+8
View File
@@ -983,6 +983,14 @@ static int is_host_interpreter(const char *interp, const char *rewritten) {
return probe.android_interp;
}
static int is_bound_guest_program(const char *path) {
if (g_ddnatv_root[0] == '\0' || !is_identity_bound_path(path)) return 0;
struct exec_probe probe;
probe_exec_file(path, &probe);
if (probe.is_elf) return probe.is_dynamic && !probe.android_interp;
return probe.n >= 2 && probe.hdr[0] == '#' && probe.hdr[1] == '!';
}
// argv for running `script` with its interpreter: interp [arg] script args... (the script's own
// argv[0] is dropped, as the kernel does). free() the result.
static char **build_script_argv(const char *interp, const char *interp_arg, const char *script, char *const argv[]) {
+7
View File
@@ -234,6 +234,13 @@ static int is_mapped_guest_path(const char *path) {
return 0;
}
static int is_identity_bound_path(const char *path) {
if (!path || path[0] != '/') return 0;
for (int i = 0; i < g_nbinds; i++)
if (g_binds[i].identity && is_path_prefix(path, g_binds[i].dst, g_binds[i].dst_len)) return 1;
return 0;
}
// Android's own mounts and files, which must never be redirected into the rootfs.
// `path` starts with '/'; a prefix can only match when its second character does.
static int is_android_host_path(const char *path) {
+1
View File
@@ -32,6 +32,7 @@ def source_assets(overlay=OVERLAY):
result[desktop / name] = 'assets/linuxfs/usr/local/bin/' + name
result[desktop / 'firefox-droiddeck.js'] = 'assets/linuxfs/usr/lib/firefox/defaults/pref/droiddeck.js'
result[desktop / 'droiddeck-clipboard.desktop'] = 'assets/linuxfs/etc/xdg/autostart/droiddeck-clipboard.desktop'
result[desktop / 'droiddeck-return-gaming.desktop'] = 'assets/linuxfs/usr/share/applications/droiddeck-return-gaming.desktop'
result[desktop / 'fastfetch.jsonc'] = 'assets/linuxfs/etc/xdg/fastfetch/config.jsonc'
result[overlay.parent.parent / 'mangoapp/mangoapp'] = 'assets/linuxfs/usr/local/bin/mangoapp'
return result
+57 -1
View File
@@ -203,10 +203,17 @@ static void test_handle_map_null_key(void)
map_free(&map);
}
static int zink_instance_table;
static struct object mock_zink_instance = {&zink_instance_table};
static struct object mock_arm = {&instance_table};
static struct object mock_zink_arm = {&zink_instance_table}, mock_zink_other = {&zink_instance_table};
static VkResult VKAPI_CALL mock_create_instance(const VkInstanceCreateInfo *info, const VkAllocationCallbacks *allocator,
VkInstance *instance)
{
*instance = (VkInstance)&mock_instance;
const VkApplicationInfo *app = info->pApplicationInfo;
bool zink = app && app->pEngineName && !strcmp(app->pEngineName, "mesa zink");
*instance = (VkInstance)(zink ? &mock_zink_instance : &mock_instance);
return VK_SUCCESS;
}
@@ -223,6 +230,7 @@ static void VKAPI_CALL mock_features(VkPhysicalDevice physical, VkPhysicalDevice
{
memset(features, 0, sizeof(*features));
features->dualSrcBlend = physical == (VkPhysicalDevice)&mock_capable;
features->geometryShader = VK_TRUE;
}
static void VKAPI_CALL mock_features2(VkPhysicalDevice physical, VkPhysicalDeviceFeatures2 *features)
@@ -234,6 +242,8 @@ static void VKAPI_CALL mock_properties(VkPhysicalDevice physical, VkPhysicalDevi
{
memset(properties, 0, sizeof(*properties));
strcpy(properties->deviceName, "mock");
bool arm = physical == (VkPhysicalDevice)&mock_arm || physical == (VkPhysicalDevice)&mock_zink_arm;
properties->vendorID = arm ? 0x13b5 : 0;
properties->limits.maxFragmentDualSrcAttachments = physical == (VkPhysicalDevice)&mock_capable;
}
@@ -385,6 +395,50 @@ static void destroy_device(VkDevice device)
((PFN_vkDestroyDevice)layer_gdpa(device, "vkDestroyDevice"))(device, NULL);
}
static void test_geometry_shader_hidden_from_zink(void)
{
VkPhysicalDeviceFeatures features;
PFN_vkGetPhysicalDeviceFeatures plain_features =
(PFN_vkGetPhysicalDeviceFeatures)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures");
PFN_vkGetPhysicalDeviceFeatures2 plain_features2 =
(PFN_vkGetPhysicalDeviceFeatures2)layer_gipa((VkInstance)&mock_instance, "vkGetPhysicalDeviceFeatures2");
VkPhysicalDeviceFeatures2 queried = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
plain_features((VkPhysicalDevice)&mock_lacking, &features);
assert(features.geometryShader);
plain_features((VkPhysicalDevice)&mock_arm, &features);
assert(features.geometryShader);
plain_features2((VkPhysicalDevice)&mock_arm, &queried);
assert(queried.features.geometryShader);
VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pEngineName = "mesa zink"};
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,
.pApplicationInfo = &app};
VkInstance zink;
assert(((PFN_vkCreateInstance)layer_gipa(NULL, "vkCreateInstance"))(&info, NULL, &zink) == VK_SUCCESS);
assert(zink == (VkInstance)&mock_zink_instance);
PFN_vkGetPhysicalDeviceFeatures zink_features =
(PFN_vkGetPhysicalDeviceFeatures)layer_gipa(zink, "vkGetPhysicalDeviceFeatures");
PFN_vkGetPhysicalDeviceFeatures2 zink_features2 =
(PFN_vkGetPhysicalDeviceFeatures2)layer_gipa(zink, "vkGetPhysicalDeviceFeatures2");
zink_features((VkPhysicalDevice)&mock_zink_arm, &features);
assert(!features.geometryShader && features.dualSrcBlend);
zink_features2((VkPhysicalDevice)&mock_zink_arm, &queried);
assert(!queried.features.geometryShader && queried.features.dualSrcBlend);
zink_features((VkPhysicalDevice)&mock_zink_other, &features);
assert(features.geometryShader);
setenv("DROIDDECK_MALI_COMPAT_NO_GS", "0", 1);
zink_features((VkPhysicalDevice)&mock_zink_arm, &features);
assert(features.geometryShader);
setenv("DROIDDECK_MALI_COMPAT_NO_GS", "1", 1);
plain_features((VkPhysicalDevice)&mock_lacking, &features);
assert(!features.geometryShader);
unsetenv("DROIDDECK_MALI_COMPAT_NO_GS");
((PFN_vkDestroyInstance)layer_gipa(zink, "vkDestroyInstance"))(zink, 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,
@@ -575,6 +629,7 @@ int main(int argc, char **argv)
setenv("WINEPREFIX", "/nonexistent", 1);
unsetenv("DROIDDECK_MALI_COMPAT");
unsetenv("DROIDDECK_MALI_COMPAT_TRACE");
unsetenv("DROIDDECK_MALI_COMPAT_NO_GS");
VkNegotiateLayerInterface negotiate = {LAYER_NEGOTIATE_INTERFACE_STRUCT, NULL, 2, NULL, NULL, NULL};
assert(vkNegotiateLoaderLayerInterfaceVersion(&negotiate) == VK_SUCCESS);
layer_gipa = negotiate.pfnGetInstanceProcAddr;
@@ -587,6 +642,7 @@ int main(int argc, char **argv)
PFN_vkCreateInstance create_instance = (PFN_vkCreateInstance)layer_gipa(NULL, "vkCreateInstance");
assert(create_instance(&info, NULL, &instance) == VK_SUCCESS);
test_geometry_shader_hidden_from_zink();
test_lacking_device();
test_capable_device();
test_depth_compare_op();
+46
View File
@@ -1493,6 +1493,19 @@ class AgentTest(Temp):
self.assertIn('var patch = zone == "cn" ? "cn.patch.battlenet.com.cn" : zone + ".patch.battle.net";', script)
self.assertIn("+ patch + ':1119/'", script)
def test_the_driver_installs_chinas_products_under_their_own_uids(self):
script = BNET["AGENT_SCRIPT"]
self.assertIn('var CHINA = {osi: "osic", s2: "s2_cn", anbs: "anbs_cn", diablo3: "d3cn"};', script)
self.assertIn('var CHINA_PRODUCT = {osi: "osic", s2: "s2c", diablo3: "d3cn"};', script)
self.assertIn('if (zone == "cn" && action == "install") {', script)
self.assertIn('country = "CHN";', script)
self.assertIn('region = "CN";', script)
def test_the_driver_reports_the_uid_the_agent_really_uses(self):
script = BNET["AGENT_SCRIPT"]
self.assertIn(' save(".uid", uid);', script)
self.assertLess(script.index('save(".uid", uid);'), script.index('if (action == "install") install();'))
class AgentJobTest(Harness):
def setUp(self):
@@ -1547,6 +1560,39 @@ class AgentJobTest(Harness):
self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"])
self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"})
def test_the_uid_the_agent_installed_under_is_reported(self):
self.install()
folder = str(self.tmp / "Games/Battle.net/Diablo III")
self.files = {
".json": json.dumps({"progress": 1.0, "download_complete": True, "state": 1004}),
".game": json.dumps({"installed": True, "playable": True, "install_dir": "Z:" + folder, "local_version": "2.8.1",
"binaries": {"game": {"relative_path": "Diablo III.exe"}}}),
".uid": "d3cn",
}
self.assertEqual(BNET["agent_job"](self.root, "install", "diablo3", "d3cn", folder, "enUS", "CHN", "CN", poll=0), 0)
self.assertIn(("UID", "d3cn"), self.lines)
self.assertEqual(self.lines[-1][0], "DONE")
self.assertEqual(json.loads(self.lines[-1][1])["uid"], "d3cn")
def test_a_job_that_never_reported_its_uid_reports_none(self):
self.install()
folder = str(self.tmp / "Games/Battle.net/Warcraft Rumble")
self.files = {
".json": json.dumps({"progress": 1.0, "download_complete": True, "state": 1004}),
".game": json.dumps({"installed": True, "playable": True, "install_dir": "Z:" + folder, "local_version": "1"}),
}
self.assertEqual(BNET["agent_job"](self.root, "install", "gryphon", "gryphon", folder, "enUS", "USA", "US", poll=0), 0)
self.assertNotIn("UID", [kind for kind, _ in self.lines])
self.assertNotIn("uid", json.loads(self.lines[-1][1]))
def test_a_job_file_is_read_as_text_in_either_encoding(self):
path = self.tmp / "uid"
path.write_bytes("d3cn".encode("utf-16"))
self.assertEqual(BNET["read_text"](str(path)), "d3cn")
path.write_bytes(b"d3cn")
self.assertEqual(BNET["read_text"](str(path)), "d3cn")
self.assertIsNone(BNET["read_text"](str(self.tmp / "missing")))
def test_an_install_on_another_volume_is_handed_over_by_its_drive_once_the_prefix_is_stopped(self):
self.install()
card = self.tmp / "card"
+22
View File
@@ -24,6 +24,28 @@ class CiChecksTest(unittest.TestCase):
gradle = (ROOT / 'app/build.gradle').read_text()
self.assertIn("gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit])", gradle)
def test_robolectric_cache_saves_and_restores_the_same_absolute_path(self):
steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']
caches = [step['with'] for step in steps if step.get('uses', '').startswith('actions/cache')]
for cache in caches:
for path in cache['path'].split('\n'):
self.assertNotIn('..', path.split('/'))
robolectric = [cache['path'] for cache in caches if cache['key'].startswith('robolectric-')]
self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2)
def test_unit_test_retry_requires_maven_exception(self):
steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']
run = next(step['run'] for step in steps if step.get('id') == 'unit-tests')
line = next(line for line in run.splitlines() if 'grep -Eq' in line)
pattern = shlex.split(line)[shlex.split(line).index('-Eq') + 1]
for log, expected in (
("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo.maven.apache.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0),
("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo.maven.apache.org/maven2/a.jar", 0),
("SomeTest > test FAILED: Too Many Requests", 1),
("Caused by: java.lang.AssertionError: HTTP 429", 1),
):
self.assertEqual(subprocess.run(['grep', '-Eq', pattern], input=log, text=True).returncode, expected)
def test_report_comment_lookup_ignores_human_marker(self):
if not shutil.which('jq'):
self.skipTest('jq required to execute comment selection')
@@ -0,0 +1,293 @@
"""A commit whose dma-buf the client's GPU is still writing is held until the buffer polls readable.
The compiled functions come from compositor.c; libwayland's lists and event loop, poll and the clock are faked.
"""
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[2] / 'app/src/main/cpp/waylandcomp/src/compositor.c'
def function(text, name):
match = re.search(r'^(?:static )?[^\n;]+\b' + name + r'\([^;]*?\)\s*\{', text, re.M)
if not match:
raise AssertionError('Production function not found: ' + name)
pos = text.index('{', match.start())
depth, end = 1, pos + 1
while depth:
depth += (text[end] == '{') - (text[end] == '}')
end += 1
return text[match.start():end]
def block(text, start):
begin = text.index(start)
return text[begin:text.index('\n};\n', begin) + 4]
HARNESS = r'''
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#define DAMAGE_RECTS 4
#define POLLIN 1
#define F_DUPFD_CLOEXEC 1030
#define WL_EVENT_READABLE 1
struct pollfd { int fd; short events, revents; };
struct wl_list { struct wl_list *prev, *next; };
struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); };
static void wl_list_init(struct wl_list *l) { l->prev = l->next = l; }
static void wl_list_remove(struct wl_list *l) { l->prev->next = l->next; l->next->prev = l->prev; l->prev = l->next = NULL; }
static void wl_list_insert(struct wl_list *list, struct wl_list *elm) {
elm->prev = list; elm->next = list->next; list->next = elm; elm->next->prev = elm;
}
static void wl_list_insert_list(struct wl_list *list, struct wl_list *other) {
if (other->next == other) return;
other->next->prev = list; other->prev->next = list->next; list->next->prev = other->prev; list->next = other->next;
}
static int wl_list_length(const struct wl_list *l) { int n = 0; for (struct wl_list *e = l->next; e != l; e = e->next) n++; return n; }
#define wl_container_of(ptr, sample, member) (__typeof__(sample))((char *)(ptr) - offsetof(__typeof__(*sample), member))
struct dmabuf_buffer { int fd[4]; int n_planes; int ahb; };
struct wl_resource { struct wl_list link; struct wl_listener *listener; struct dmabuf_buffer *db; int released, destroyed; };
static struct wl_resource *from_link(struct wl_list *l) { return wl_container_of(l, (struct wl_resource *)0, link); }
#define wl_resource_for_each_safe(r, t, list) \
for (r = from_link((list)->next), t = from_link(r->link.next); &r->link != (list); r = t, t = from_link(t->link.next))
static void wl_resource_destroy(struct wl_resource *r) { wl_list_remove(&r->link); r->destroyed = 1; }
static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) { r->listener = l; wl_list_init(&l->link); }
static void client_destroys(struct wl_resource *r) {
if (r->listener) { struct wl_listener *l = r->listener; r->listener = NULL; l->notify(l, r); }
}
static int ready[64], dup_of[64], next_dup = 40, closed[64];
static int poll(struct pollfd *p, unsigned n, int timeout) {
if (n != 1 || timeout != 0 || p->events != POLLIN) { puts("FAIL poll args"); exit(1); }
return ready[p->fd] ? 1 : 0;
}
static int fcntl(int fd, int cmd, int arg) { (void)cmd; (void)arg; dup_of[next_dup] = fd; return next_dup++; }
static int close(int fd) { closed[fd]++; return 0; }
struct wl_event_source { int fd; int (*fd_cb)(int, uint32_t, void *); int (*timer_cb)(void *); void *data; int armed_ms, removed; };
struct wl_event_loop;
struct wl_display;
static struct wl_display *g_display;
static struct wl_event_source sources[32];
static int n_sources;
static struct wl_event_loop *wl_display_get_event_loop(struct wl_display *d) { (void)d; return NULL; }
static struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *l, int fd, uint32_t mask,
int (*cb)(int, uint32_t, void *), void *data) {
(void)l; (void)mask; struct wl_event_source *s = &sources[n_sources++]; memset(s, 0, sizeof(*s));
s->fd = fd; s->fd_cb = cb; s->data = data; return s;
}
static struct wl_event_source *wl_event_loop_add_timer(struct wl_event_loop *l, int (*cb)(void *), void *data) {
(void)l; struct wl_event_source *s = &sources[n_sources++]; memset(s, 0, sizeof(*s));
s->fd = -1; s->timer_cb = cb; s->data = data; return s;
}
static int wl_event_source_timer_update(struct wl_event_source *s, int ms) { s->armed_ms = ms; return 0; }
static int wl_event_source_remove(struct wl_event_source *s) { s->removed = 1; return 0; }
static void dispatch(int timers_expire) {
for (int i = 0; i < n_sources; i++) {
struct wl_event_source *s = &sources[i];
if (s->removed) continue;
if (s->fd_cb && ready[dup_of[s->fd]]) s->fd_cb(s->fd, WL_EVENT_READABLE, s->data);
else if (s->timer_cb && s->armed_ms && timers_expire) { s->armed_ms = 0; s->timer_cb(s->data); }
}
}
static int64_t clock_ns;
static int64_t now_ns(void) { return clock_ns; }
static struct { unsigned replaced; } g_pace;
static struct { unsigned commit_waits, commit_wait_limits; int64_t commit_wait_ns, commit_wait_max_ns; } g_perf;
static int logged;
static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; logged++; }
static void send_buffer_release(struct wl_resource *r) { r->released++; }
static unsigned feedback_discard_all(struct wl_list *list) {
unsigned n = 0; struct wl_resource *r, *t; wl_resource_for_each_safe(r, t, list) { wl_resource_destroy(r); n++; } return n;
}
static struct dmabuf_buffer *get_dmabuf(struct wl_resource *r) { return r ? r->db : NULL; }
static int ahb_swapchain_has_ahb(const struct dmabuf_buffer *b) { return b->ahb; }
static int64_t rect_area(const int32_t *r, int bw, int bh) { (void)bw; (void)bh; return (int64_t)r[2] * r[3]; }
struct damage_list { int32_t r[DAMAGE_RECTS][4]; int n; };
struct surface {
struct wl_resource *resource, *xdg_toplevel;
int toplevel_committed;
struct wl_resource *pending_buffer;
struct wl_listener pending_buffer_destroy;
int pending_attach, pending_src_set, pending_dst_set, pending_opaque_set;
float pending_src[4];
int pending_dst[2], pending_opaque[4];
struct damage_list pending_damage_buf, pending_damage_local;
struct wl_list pending_frames, pending_feedback;
struct surface_state *waiting;
struct wl_event_source *waiting_source, *waiting_timer;
int waiting_fd;
int64_t waiting_since_ns;
};
static void send_toplevel_configure(struct surface *s) { (void)s; }
struct wl_client;
static struct surface surf;
STATE_STRUCT
static int applies, applied_attach, applied_frames, applied_opaque, applied_damage;
static struct wl_resource *applied_buffer;
static void surface_state_apply(struct surface *s, struct surface_state *st);
FUNCTIONS
static void surface_state_apply(struct surface *s, struct surface_state *st) {
(void)s;
applies++;
applied_attach = st->attach;
applied_buffer = st->attach ? st->buffer : NULL;
applied_frames = wl_list_length(&st->frames);
applied_opaque = st->opaque_set ? st->opaque[2] : -1;
applied_damage = st->damage_buf.n;
if (st->attach) { wl_list_remove(&st->buffer_destroy.link); wl_list_init(&st->buffer_destroy.link); }
struct wl_resource *r, *t;
wl_resource_for_each_safe(r, t, &st->frames) wl_resource_destroy(r);
feedback_discard_all(&st->feedback);
}
static struct wl_resource frame_res[16];
static int n_frames;
static void attach(struct wl_resource *b) {
if (surf.pending_buffer) wl_list_remove(&surf.pending_buffer_destroy.link);
wl_list_init(&surf.pending_buffer_destroy.link);
surf.pending_buffer = b; surf.pending_attach = 1;
}
static void frame(void) { struct wl_resource *f = &frame_res[n_frames++]; wl_list_insert(surf.pending_frames.prev, &f->link); }
static void damage(int w) { surf.pending_damage_buf.r[surf.pending_damage_buf.n][2] = w;
surf.pending_damage_buf.r[surf.pending_damage_buf.n][3] = 1; surf.pending_damage_buf.n++; }
static void commit(void) { surface_commit(NULL, NULL); }
#define CHECK(c, what) do { if (!(c)) { printf("FAIL %s (line %d)\n", what, __LINE__); return 1; } } while (0)
int main(void) {
wl_list_init(&surf.pending_frames); wl_list_init(&surf.pending_feedback);
wl_list_init(&surf.pending_buffer_destroy.link);
surf.waiting_fd = -1;
struct dmabuf_buffer d1 = {{10, -1}, 1, 0}, d2 = {{11, -1}, 1, 0}, d3 = {{12, -1}, 1, 0}, dz = {{13, -1}, 1, 1};
struct wl_resource b1 = {.db = &d1}, b2 = {.db = &d2}, b3 = {.db = &d3}, bz = {.db = &dz};
ready[10] = 1;
attach(&b1); frame(); commit();
CHECK(applies == 1 && applied_buffer == &b1 && applied_frames == 1 && !surf.waiting && n_sources == 0, "ready buffer");
ready[11] = 0;
clock_ns = 1000000;
attach(&b2); frame(); damage(5); commit();
CHECK(applies == 1 && surf.waiting && surf.waiting_fd >= 40 && dup_of[surf.waiting_fd] == 11, "held");
CHECK(sources[0].armed_ms == 0 && sources[1].armed_ms == 1000, "waits on the buffer with a 1 s limit");
dispatch(0);
CHECK(applies == 1, "nothing before the writes end");
clock_ns = 4000000;
ready[11] = 1;
dispatch(0);
CHECK(applies == 2 && applied_buffer == &b2 && applied_frames == 1 && applied_damage == 1 && !surf.waiting, "applied once ready");
CHECK(closed[40] == 1 && sources[0].removed && sources[1].removed, "wait cleaned up");
CHECK(g_perf.commit_waits == 1 && g_perf.commit_wait_max_ns == 3000000, "wait counted");
ready[11] = 0; ready[12] = 0;
attach(&b2); frame(); damage(7); commit();
attach(&b3); frame(); damage(9); commit();
CHECK(applies == 2 && b2.released == 1 && dup_of[surf.waiting_fd] == 12, "replaced while waiting");
ready[12] = 1;
dispatch(0);
CHECK(applies == 3 && applied_buffer == &b3 && applied_frames == 2 && applied_damage == 2, "newest shown with both callbacks");
CHECK(g_perf.commit_waits == 2, "merged wait counted once");
ready[11] = 0;
attach(&b2); commit();
surf.pending_opaque[2] = 640; surf.pending_opaque_set = 1; frame(); commit();
CHECK(applies == 3 && b2.released == 1 && dup_of[surf.waiting_fd] == 11, "the waiting buffer is not released");
ready[11] = 1;
dispatch(0);
CHECK(applies == 4 && applied_buffer == &b2 && applied_opaque == 640 && applied_frames == 1, "buffer kept, opaque applied");
g_zero_copy_shown = &surf;
attach(&bz); commit();
CHECK(applies == 5 && applied_buffer == &bz && !surf.waiting && g_unwaited == &surf, "zero-copy buffer");
g_zero_copy_shown = NULL;
ready[13] = 0;
attach(&bz); commit();
CHECK(applies == 5 && surf.waiting, "a droiddeck-ahb buffer not shown zero-copy waits");
ready[13] = 1;
dispatch(0);
CHECK(applies == 6 && !g_unwaited, "waited buffer clears the mark");
ready[13] = 0;
ready[10] = 0;
attach(&b1); frame(); commit();
client_destroys(&b1);
ready[10] = 1;
dispatch(0);
CHECK(applies == 7 && !applied_attach && applied_frames == 1, "destroyed buffer dropped from the commit");
ready[11] = 0;
attach(&b2); commit();
dispatch(1);
CHECK(applies == 8 && applied_buffer == &b2 && g_perf.commit_wait_limits == 1 && logged == 1 && !surf.waiting, "limit");
ready[11] = 0; ready[12] = 0;
clock_ns = 10000000000;
attach(&b2); commit();
CHECK(applies == 8 && sources[n_sources - 1].armed_ms == 1000, "held again");
clock_ns += 600000000;
attach(&b3); commit();
CHECK(applies == 8 && surf.waiting && sources[n_sources - 1].armed_ms == 400, "a newer commit keeps the first deadline");
clock_ns += 500000000;
attach(&b2); commit();
CHECK(applies == 9 && applied_buffer == &b2 && g_perf.commit_wait_limits == 2 && !surf.waiting, "commits past the deadline are applied at once");
puts("PASS");
return 0;
}
'''
class CommitWaitsForClientWritesTest(unittest.TestCase):
def test_commits_wait_for_the_clients_gpu_writes(self):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if not compiler:
self.skipTest('A host C compiler is required')
source = SOURCE.read_text()
functions = '\n'.join(re.search(pattern, source, re.M).group(0) for pattern in
(r'^#define COMMIT_WAIT_LIMIT_MS .*$', r'^static struct surface \*g_zero_copy_shown, \*g_unwaited;$')) + '\n' + '\n'.join(
function(source, name) for name in
('note_damage', 'on_state_buffer_destroyed', 'surface_state_take', 'state_unfinished_fd',
'surface_state_discard', 'surface_state_merge', 'surface_wait_stop', 'surface_wait_end', 'on_commit_ready',
'on_commit_wait_limit', 'surface_wait_start', 'surface_commit'))
probe = HARNESS.replace('STATE_STRUCT', block(source, 'struct surface_state {')).replace('FUNCTIONS', functions)
probe = probe.replace('struct surface *s = wl_resource_get_user_data(r);', 'struct surface *s = &surf; (void)r;')
with tempfile.TemporaryDirectory(prefix='droiddeck-commit-wait-') as temp:
folder = Path(temp)
(folder / 'probe.c').write_text(probe)
built = subprocess.run([compiler, '-std=gnu11', '-Wall', '-Wextra', '-Wno-unused-parameter', '-Wno-unused-function',
str(folder / 'probe.c'), '-o', str(folder / 'probe')],
capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
run = subprocess.run([str(folder / 'probe')], capture_output=True, text=True, timeout=10)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
self.assertEqual(run.stdout.strip(), 'PASS')
def test_scenes_settle_an_unwaited_buffer_before_copying_it(self):
body = function(SOURCE.read_text(), 'render_scene').splitlines()
copies = [i for i, line in enumerate(body) if 'vkp_render(w, h, dl.d, dl.n)' in line]
self.assertGreaterEqual(len(copies), 4)
for i in copies:
self.assertTrue(any('settle_unwaited();' in line for line in body[max(0, i - 3):i]), body[i])
text = '\n'.join(body)
self.assertIn('if (hdr_route == 1 || hdr_route == 2) settle_unwaited();', text)
self.assertIn('settle_unwaited();\n render_stream();', text)
self.assertIn('if (r == 0 && !fg_pass) g_zero_copy_shown = ls;\n else settle_unwaited();', text)
if __name__ == '__main__':
unittest.main()
+75
View File
@@ -0,0 +1,75 @@
import os
import re
import shlex
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DESKTOP = ROOT / "tools/linuxfs/desktop"
SCRIPT = (DESKTOP / "droiddeck-desktop").read_text()
ENTRY = (DESKTOP / "droiddeck-return-gaming.desktop").read_text()
class DesktopReturnGamingTest(unittest.TestCase):
def session(self, logout, rc=0, bottom=False):
with tempfile.TemporaryDirectory() as tmp:
run = Path(tmp, "run")
launched = Path(tmp, "launched")
exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1)
inner = shlex.split(exec_line)[2].replace("dbus-send", "true")
plasma = Path(tmp, "plasma")
plasma.write_text("#!/bin/sh\n%s\nexit %d\n" % (inner if logout == "return" else ":", rc))
plasma.chmod(0o755)
steam = Path(tmp, "steam-launch")
steam.write_text('#!/bin/sh\necho "$*" > %s\n' % launched)
steam.chmod(0o755)
tail = SCRIPT[SCRIPT.index("return_gaming="):]
tail = tail.replace("dbus-run-session -- startplasma-wayland", str(plasma))
tail = tail.replace("/usr/local/bin/droiddeck-pipewire stop", ":")
tail = tail.replace("/usr/local/bin/droiddeck-steam-launch", str(steam))
tail = tail.replace("sleep 30", ":")
tail = tail.replace("/run/droiddeck", str(run))
plasma.write_text(plasma.read_text().replace("/run/droiddeck", str(run)))
env = {k: v for k, v in os.environ.items() if k != "DD_BOTTOM_DESKTOP"}
if bottom:
env["DD_BOTTOM_DESKTOP"] = "1"
run.mkdir()
(run / "return-gaming").write_text("")
status = subprocess.run(["sh", "-c", tail], env=env, capture_output=True, text=True).returncode
return status, launched.read_text().strip() if launched.exists() else None, (run / "return-gaming").exists()
def test_return_to_gaming_mode_opens_steam(self):
self.assertEqual(self.session("return"), (0, "bigpicture", False))
def test_log_out_goes_back_without_steam_even_after_an_earlier_request(self):
self.assertEqual(self.session("logout"), (0, None, False))
def test_a_failed_session_and_the_bottom_desktop_never_open_steam(self):
self.assertEqual(self.session("return", rc=1)[:2], (1, None))
self.assertEqual(self.session("return", bottom=True)[:2], (0, None))
def test_the_logout_request_outlives_starting_the_shutdown_service(self):
exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1)
call = shlex.split(shlex.split(exec_line)[2].split(";")[-1])
self.assertEqual(call[0], "dbus-send")
self.assertIn("--print-reply", call)
def test_a_rejected_logout_request_forgets_the_return_to_gaming_mode(self):
exec_line = re.search(r"^Exec=(.*)$", ENTRY, re.M).group(1)
with tempfile.TemporaryDirectory() as tmp:
inner = shlex.split(exec_line)[2].replace("/run/droiddeck", tmp)
for sender, kept in (("true", True), ("false", False)):
subprocess.run(["sh", "-c", inner.replace("dbus-send", sender, 1)], check=False)
self.assertEqual(Path(tmp, "return-gaming").exists(), kept)
def test_the_app_ships_the_shortcut_with_the_script(self):
source = (ROOT / "app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt").read_text()
self.assertIn('"usr/share/applications/droiddeck-return-gaming.desktop" to '
'"usr/share/applications/droiddeck-return-gaming.desktop"', source)
self.assertIn("droiddeck-return-gaming.desktop", (ROOT / "tools/release/check_session_assets.py").read_text())
if __name__ == "__main__":
unittest.main()
+21 -3
View File
@@ -29,14 +29,21 @@ PAD_TYPE_STEAM = 1
READER = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <poll.h>
#include <stdio.h>
#include <sys/uio.h>
#include <unistd.h>
ssize_t __read_chk(int fd, void *buffer, size_t size, size_t buffer_size);
int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fds_size);
static int vector_count;
static int fortified;
static ssize_t controller_read(int fd, void *buffer, size_t size)
{
if (fortified)
return __read_chk(fd, buffer, size, size);
if (!vector_count)
return read(fd, buffer, size);
struct iovec vectors[3] = {
@@ -53,7 +60,8 @@ static ssize_t controller_read(int fd, void *buffer, size_t size)
int main(int argc, char **argv)
{
vector_count = argc > 1 ? (argv[1][0] == '1' ? 1 : 3) : 0;
fortified = argc > 1 && argv[1][0] == 'f';
vector_count = argc > 1 && !fortified ? (argv[1][0] == '1' ? 1 : 3) : 0;
struct input_event events[64];
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
if (fd < 0) {
@@ -62,11 +70,17 @@ int main(int argc, char **argv)
}
while (controller_read(fd, events, sizeof(events)) > 0)
;
struct pollfd idle = {fd, POLLIN, 0};
if (fortified && __poll_chk(&idle, 1, 0, sizeof(idle)) != 0)
return 3;
puts("ready");
fflush(stdout);
char go;
if (read(0, &go, 1) != 1)
return 1;
struct pollfd ready = {fd, POLLIN, 0};
if (fortified && (__poll_chk(&ready, 1, 1000, sizeof(ready)) != 1 || !(ready.revents & POLLIN)))
return 2;
ssize_t got = controller_read(fd, events, sizeof(events));
for (ssize_t i = 0; i < got / (ssize_t)sizeof(events[0]); i++)
printf("%ld.%06ld %u %u %d\n", (long)events[i].time.tv_sec, (long)events[i].time.tv_usec, events[i].type,
@@ -345,7 +359,7 @@ class FakeinputRingTest(unittest.TestCase):
subprocess.run(["gcc", bits, "-o", str(binary), str(self.tmp / (name + ".c"))], check=True)
return library, binary
def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER):
def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER, fortified=False):
if not virtual:
program = program.replace("event16", "event0")
library, reader = self.build(bits, program, "reader")
@@ -359,7 +373,7 @@ class FakeinputRingTest(unittest.TestCase):
overlay_library = self.tmp / "overlay.so"
subprocess.run(["gcc", bits, "-shared", "-fPIC", "-o", str(overlay_library), str(source)], check=True)
env["LD_PRELOAD"] = str(overlay_library) + ":" + str(library)
command = [str(reader)] + ([str(vectors)] if vectors else [])
command = [str(reader)] + (["fortified"] if fortified else [str(vectors)] if vectors else [])
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
self.addCleanup(process.kill)
self.assertEqual(process.stdout.readline(), "ready\n")
@@ -381,6 +395,10 @@ class FakeinputRingTest(unittest.TestCase):
self.assertEqual(self.read_through("-m64"),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_a_fortified_guest_polls_and_reads_the_ring(self):
self.assertEqual(self.read_through("-m64", virtual=False, fortified=True),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_readv_reads_events_instead_of_the_backing_file(self):
self.assertEqual(self.read_through("-m64", vectors=1),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
+158
View File
@@ -1741,6 +1741,94 @@ class GameEnvironmentTest(unittest.TestCase):
(asylum / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], []))
def test_store_launcher_resolves_the_game_executable_from_the_sidecar(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "BatmanArkhamCity"
bin_dir = root / "Binaries/Win32"
bin_dir.mkdir(parents=True)
for name in ("Batman2.exe", "BatmanAC.exe"):
(bin_dir / name).touch()
launcher = root / ".droiddeck-launch.bat"
launcher.touch()
(root / ".droiddeck-store.json").write_text(json.dumps({
"store": "epic", "id": "Egret", "title": "Batman Arkham City",
"exe": "Binaries/Win32/Batman2.exe", "launcher": ".droiddeck-launch.bat",
}))
env, extra, notes = MODULE["engine_fixes"](str(launcher), [])
self.assertEqual((env, extra), ({"FEX_X87REDUCEDPRECISION": "0"}, []))
self.assertTrue(notes)
home = Path(tmp) / "home"
config = home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
config.write_text(json.dumps({"version": 1, "shared": {"FEX_X87REDUCEDPRECISION": "1"}}))
probe = home / "proton"
probe.write_text("#!" + sys.executable + "\nimport os, sys\n"
"print(os.environ.get('FEX_X87REDUCEDPRECISION', ''))\n"
"print(sys.argv[2])\n")
probe.chmod(0o755)
base = {k: v for k, v in os.environ.items() if not k.startswith(("FEX_", "WINE", "PROTON", "DROIDDECK", "DD_", "STEAM"))}
base.update(HOME=str(home), STEAM_COMPAT_DATA_PATH=str(home / "compatdata/3648205350"))
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun", str(launcher)],
env=base, text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.splitlines(), ["0", str(launcher)])
self.assertIn("Batman: Arkham City: FEX with full x87 precision", result.stderr)
rebirth = Path(tmp) / "FF7Rebirth"
rebirth_exe = rebirth / "End/Binaries/Win64/ff7rebirth_.exe"
rebirth_exe.parent.mkdir(parents=True)
rebirth_exe.touch()
rebirth_launcher = rebirth / ".droiddeck-launch.bat"
rebirth_launcher.touch()
(rebirth / ".droiddeck-store.json").write_text(json.dumps({
"store": "epic", "id": "ff7", "title": "FF7 Rebirth",
"exe": r"End\Binaries\Win64\ff7rebirth_.exe", "launcher": ".droiddeck-launch.bat",
}))
self.assertEqual(MODULE["engine_fixes"](str(rebirth_launcher), [])[0], {"VKD3D_FEATURE_LEVEL": "12_2"})
def test_store_launcher_ignores_missing_invalid_or_escaping_sidecar_paths(self):
with tempfile.TemporaryDirectory() as tmp:
outside = Path(tmp) / "Outside"
outside.mkdir()
outside_exe = outside / "BatmanAC.exe"
outside_exe.touch()
root = Path(tmp) / "Game"
sub = root / "sub"
sub.mkdir(parents=True)
(root / "real.exe").touch()
(sub / "nested.exe").touch()
(root / "escape.exe").symlink_to(outside_exe)
(root / "linkdir").symlink_to(outside)
launcher = root / ".droiddeck-launch.bat"
launcher.touch()
sidecar = root / ".droiddeck-store.json"
resolve = MODULE["store_game_exe"]
self.assertEqual(resolve(str(launcher)), str(launcher))
for payload in ("not-json", "[]", json.dumps({"exe": ""}), json.dumps({"exe": 123}),
json.dumps({"exe": "missing.exe"}), json.dumps({"exe": "sub"}),
json.dumps({"exe": "../Outside/BatmanAC.exe"}),
json.dumps({"exe": "sub/../real.exe"}),
json.dumps({"exe": r"sub\..\real.exe"}),
json.dumps({"exe": "linkdir/../real.exe"}),
json.dumps({"exe": "sub/../../Outside/BatmanAC.exe"}),
json.dumps({"exe": str(outside_exe)}),
json.dumps({"exe": r"C:\Windows\notepad.exe"}),
json.dumps({"exe": "escape.exe"})):
with self.subTest(payload=payload):
sidecar.write_text(payload)
self.assertEqual(resolve(str(launcher)), str(launcher))
sidecar.write_text(json.dumps({"exe": "real.exe"}))
self.assertEqual(resolve(str(launcher)), str(root / "real.exe"))
sidecar.write_text(json.dumps({"exe": "sub/nested.exe"}))
self.assertEqual(resolve(str(launcher)), str(sub / "nested.exe"))
other_bat = root / "custom.bat"
other_bat.touch()
self.assertEqual(resolve(str(other_bat)), str(other_bat))
def test_split_second_gets_x87_fip_unless_the_game_sets_jit_features(self):
with tempfile.TemporaryDirectory() as tmp:
game = Path(tmp) / "SplitSecond"
@@ -1762,6 +1850,76 @@ class GameEnvironmentTest(unittest.TestCase):
config["games"] = {"297860": {"FEX_JITFEATURES": "off"}}
self.assertEqual(MODULE["apply_config"]({}, config, "297860", env)["FEX_JITFEATURES"], "off")
def test_inno_setup_installers_get_the_stability_preset_over_the_default(self):
stability = {"FEX_TSOENABLED": "1", "FEX_VECTORTSOENABLED": "1", "FEX_MEMCPYSETTSOENABLED": "1",
"FEX_HALFBARRIERTSOENABLED": "1", "FEX_X87REDUCEDPRECISION": "0", "FEX_MULTIBLOCK": "0"}
performance_tso = {"FEX_TSOENABLED": "1", "FEX_VECTORTSOENABLED": "0", "FEX_MEMCPYSETTSOENABLED": "0",
"FEX_HALFBARRIERTSOENABLED": "0", "FEX_X87REDUCEDPRECISION": "1", "FEX_MULTIBLOCK": "1"}
def loader(path, resources=b"", machine=0x14C, section=b".rsrc", legacy=False):
dos = bytearray(0x80)
dos[:2] = b"MZ"
dos[0x3C:0x40] = (0x80).to_bytes(4, "little")
if legacy:
dos[0x30:0x34] = b"Inno"
header = b"PE\0\0" + machine.to_bytes(2, "little") + (1).to_bytes(2, "little") + bytes(12) \
+ (0xE0).to_bytes(2, "little") + bytes(2)
entry = section.ljust(8, b"\0") + bytes(8) + len(resources).to_bytes(4, "little") \
+ (0x400).to_bytes(4, "little") + bytes(16)
path.write_bytes((bytes(dos) + header + bytes(0xE0) + entry).ljust(0x400, b"\0") + resources)
return str(path)
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
table = bytes(64) + b"rDlPtS\xcd\xe6\xd7{\x0b*" + bytes(64)
installers = [
loader(folder / "setup.exe", table),
loader(folder / "setup_game_1.0.exe", bytes(64) + b"nS5W7dT\x83\xaa\x1b\x0fj"),
loader(folder / "old_setup.exe", legacy=True),
]
for installer in installers:
env, extra, notes = MODULE["engine_fixes"](installer, [])
self.assertEqual((env, extra), (stability, []), installer)
self.assertTrue(notes)
config = {"version": 1, "shared": performance_tso}
self.assertEqual({k: v for k, v in MODULE["apply_config"]({}, config, "42", env).items() if k in stability},
stability)
config["games"] = {"42": {"FEX_MULTIBLOCK": "1"}}
self.assertEqual(MODULE["apply_config"]({}, config, "42", env)["FEX_MULTIBLOCK"], "1")
not_installers = [
loader(folder / "Game.exe", bytes(256)),
loader(folder / "Game64.exe", table, machine=0x8664),
loader(folder / "Data.exe", table, section=b".data"),
folder / "missing.exe",
]
(folder / "notes.exe").write_bytes(b"rDlPtS\xcd\xe6\xd7{\x0b*")
not_installers.append(folder / "notes.exe")
for other in not_installers:
self.assertEqual(MODULE["engine_fixes"](str(other), []), ({}, [], []), other)
# The run verb skips engine_fixes; an installer started that way still gets Stability.
probe = folder / "proton"
probe.write_text("#!" + sys.executable + "\nimport json, os\nprint(json.dumps(dict(os.environ)))\n")
probe.chmod(0o755)
base = {**os.environ, **performance_tso, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": str(folder / "compatdata/42")}
def run_verb(program):
out = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "run", program],
env=base, text=True, capture_output=True, check=True).stdout
return {name: value for name, value in json.loads(out).items() if name in stability}
self.assertEqual(run_verb(installers[0]), stability)
self.assertEqual(run_verb(str(folder / "Game.exe")), performance_tso)
config_path = folder / ".config/droiddeck/game-environment.json"
config_path.parent.mkdir(parents=True)
config_path.write_text(json.dumps({"version": 1, "shared": {"WINEESYNC": "1"}}))
self.assertEqual(run_verb(installers[0]), stability)
config_path.write_text(json.dumps({"version": 1, "games": {"42": {"FEX_MULTIBLOCK": "1"}}}))
self.assertEqual(run_verb(installers[0]), {**stability, "FEX_MULTIBLOCK": "1"})
config_path.write_text(json.dumps({"version": 1, "games": {"42": {"FEX_MULTIBLOCK": None}}}))
self.assertNotIn("FEX_MULTIBLOCK", run_verb(installers[0]))
def test_d3dgear_capture_hook_beside_the_game_is_turned_off(self):
with tempfile.TemporaryDirectory() as tmp:
game = Path(tmp) / "The Crew 2"
+43 -2
View File
@@ -260,6 +260,7 @@ static void *(*next)(void *);
static void *(*by_name)(void *, const char *);
static const char *(*name)(void *);
static const char *(*value)(void *);
static const char *(*sysattr)(void *, const char *);
static void *sym(const char *symbol) { return dlsym(lib, symbol); }
@@ -463,6 +464,20 @@ static void run_every(int count, char **entries) {
printf("pad %d real calls %d\n", pad != NULL, real_calls != NULL ? *real_calls : -1);
}
static void print_product(const char *label, void *device) {
const char *uevent = device != NULL ? sysattr(device, "uevent") : NULL;
printf("%s %.*s\n", label, uevent != NULL ? (int)strcspn(uevent, "\n") : 4, uevent != NULL ? uevent : "none");
}
static void run_identity(void) {
int udev;
void *device = new_device(&udev, PAD);
print_product("pad", device);
print_product("parent", device != NULL ? get_parent(device) : NULL);
}
static void run_probe(void) {
int udev;
@@ -539,7 +554,9 @@ int main(int argc, char **argv) {
by_name = sym("udev_list_entry_get_by_name");
name = sym("udev_list_entry_get_name");
value = sym("udev_list_entry_get_value");
sysattr = sym("udev_device_get_sysattr_value");
if (strcmp(argv[1], "probe") == 0) run_probe();
else if (strcmp(argv[1], "identity") == 0) run_identity();
else if (strcmp(argv[1], "every") == 0) run_every(argc - 3, argv + 3);
else if (strcmp(argv[1], "stable") == 0) run_stable();
else if (strcmp(argv[1], "enumerate") == 0) run_enumerate();
@@ -597,10 +614,13 @@ class InputUdevPreloadTest(unittest.TestCase):
(pads / node).write_text("")
return pads
def run_program(self, mode, *preloads, pads=None, slots="0=/pad", program=None, args=()):
def run_program(self, mode, *preloads, pads=None, slots="0=/pad", program=None, args=(), extra=None):
env = dict(os.environ, LD_PRELOAD=":".join(str(self.dir / name) for name in ("libddsession.so", *preloads)),
FAKE_EVDEV_MEMFD_PATHS=slots, FAKE_EVDEV_DIR=str(pads or self.pads))
env.pop("FAKE_EVDEV_UINPUT", None)
for key in ("FAKE_EVDEV_UINPUT", "FAKE_EVDEV_STEAM_VIRTUAL", "SDL_GAMECONTROLLER_IGNORE_DEVICES",
"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT"):
env.pop(key, None)
env.update(extra or {})
result = subprocess.run([str(program or self.program), mode, str(self.udev), *args], env=env, capture_output=True, text=True,
timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
@@ -684,6 +704,27 @@ class InputUdevPreloadTest(unittest.TestCase):
"nothing added scan -1",
])
def identity(self, pads=None, **extra):
return self.run_program("identity", pads=pads, extra=extra)
def test_a_ring_pad_keeps_the_steam_input_identity_whatever_sdl_is_told(self):
steam = ["pad PRODUCT=6/28de/11ff/110", "parent PRODUCT=6/28de/11ff/110"]
for extra in ({}, {"FAKE_EVDEV_UINPUT": "1"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "0"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "1"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142,0x045E/0x028E"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x045e/0x028e"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x28de/0x11ff"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": ""},
{"FAKE_EVDEV_UINPUT": "1", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028e"}):
with self.subTest(**extra):
self.assertEqual(self.identity(**extra), steam)
def test_a_pad_under_steam_inputs_own_virtual_pad_stays_an_xbox_pad(self):
pads = self.pad_dir("under-virtual", "event0", "event16")
(pads / ".uinput-event16.uevent").write_text('PRODUCT=6/28de/11ff/1\nNAME="Microsoft X-Box 360 pad 0"\n')
self.assertEqual(self.identity(pads, FAKE_EVDEV_UINPUT="1", SDL_GAMECONTROLLER_IGNORE_DEVICES="0x045e/0x028e"),
["pad PRODUCT=3/45e/28e/110", "parent PRODUCT=3/45e/28e/110"])
def test_a_program_that_closes_and_reopens_libudev_keeps_working(self):
self.assertEqual(self.run_program("reload"), ["reload real0 real1"])
@@ -120,6 +120,14 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
script.parent.mkdir(exist_ok=True)
script.write_text(f"#!{interpreter}\n")
script.chmod(0o755)
cls.app_files = tmp / "app-files"
cls.app_files.mkdir()
shutil.copy(cls.probe, cls.app_files / "tool")
shutil.copy(cls.android / "sh", cls.app_files / "android-tool")
for name, interpreter in (("guest.py", GUEST_TOOL), ("android.sh", f"{ANDROID_DIR}/sh")):
(cls.app_files / name).write_text(f"#!{interpreter}\n")
for entry in cls.app_files.iterdir():
entry.chmod(0o755)
@classmethod
def tearDownClass(cls):
@@ -220,6 +228,32 @@ class NativeHookLdsoSpawnTest(unittest.TestCase):
call = self.call(how, "/opt/host.sh", "x", binds=f"{self.runtime}:{BOUND_DIR}")
self.assertEqual([HOST_SHELL, HOST_SHELL, str(self.root / "opt/host.sh"), "x"], call)
def test_a_script_on_a_mount_at_its_host_path_runs_with_the_guest_interpreter(self):
script = str(self.app_files / "guest.py")
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, script, "x", binds=f"{self.app_files}:{self.app_files}")
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
self.assertEqual([str(self.root / GUEST_TOOL.lstrip("/")), script, "x"], call[-3:])
def test_a_glibc_program_on_a_mount_at_its_host_path_starts_through_the_guest_ldso(self):
tool = str(self.app_files / "tool")
for how in ("exec", "spawn"):
with self.subTest(how=how):
call = self.call(how, tool, "x", binds=f"{self.app_files}:{self.app_files}")
self.assertEqual(str(self.root / GUEST_LDSO.lstrip("/")), call[0])
self.assertEqual([tool, "x"], call[-2:])
def test_android_programs_on_a_mount_at_its_host_path_stay_on_the_host(self):
tool = str(self.app_files / "android-tool")
script = str(self.app_files / "android.sh")
sh = str(self.android / "sh")
binds = f"{self.app_files}:{self.app_files}|{self.android}:{ANDROID_DIR}"
for how in ("exec", "spawn"):
with self.subTest(how=how):
self.assertEqual([tool, tool, "x"], self.call(how, tool, "x", binds=binds))
self.assertEqual([sh, sh, script, "x"], self.call(how, script, "x", binds=binds))
def test_an_android_interpreter_reached_through_a_bind_stays_on_the_host(self):
sh = str(self.android / "sh")
for how in ("exec", "spawn"):
+125
View File
@@ -0,0 +1,125 @@
from pathlib import Path
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
SHIM = r"""
#include <linux/input.h>
#include <stdarg.h>
#include <string.h>
int ioctl(int fd, unsigned long request, ...) {
va_list ap;
va_start(ap, request);
struct input_id *id = va_arg(ap, struct input_id *);
va_end(ap);
(void)fd;
if (request != EVIOCGID) return -1;
memset(id, 0, sizeof(*id));
id->bustype = 3;
id->vendor = 0x045e;
id->product = 0x028e;
return 0;
}
"""
QUERY = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
void query(const char *path) {
struct input_id id;
int fd = open(path, O_RDONLY | O_CLOEXEC);
int rc = ioctl(fd, EVIOCGID, &id);
printf("%d %04x:%04x\n", rc, id.vendor, id.product);
close(fd);
}
"""
PROGRAM = r"""
#include <dlfcn.h>
#include <stdio.h>
#include <string.h>
void query(const char *path);
int main(int argc, char **argv) {
(void)argc;
if (strcmp(argv[1], "-") != 0) dlopen(argv[1], RTLD_NOW);
if (strcmp(argv[2], "program") == 0) {
query(argv[3]);
} else {
void *sdl = dlopen(argv[2], RTLD_NOW | RTLD_LOCAL);
void (*sdl_query)(const char *) = (void (*)(const char *))dlsym(sdl, "query");
sdl_query(argv[3]);
}
fflush(stdout);
return 0;
}
"""
@unittest.skipUnless(sys.platform == "linux" and shutil.which("cc"), "needs Linux and cc")
class RingPadSdlIdentityTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
build = cls.dir / "build"
build.mkdir()
for name, text in (("shim.c", SHIM), ("query.c", QUERY), ("program.c", PROGRAM), ("empty.c", "int bus;\n")):
(build / name).write_text(text)
cls.lib = cls.dir / "libddsession.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
cls.shim = cls.dir / "libshim.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.shim), str(build / "shim.c")], check=True)
cls.winebus = cls.dir / "winebus.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.winebus), str(build / "empty.c")], check=True)
cls.sdl_library = cls.dir / "libSDL2-2.0.so.0"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.sdl_library), str(build / "query.c")], check=True)
cls.program = cls.dir / "program"
subprocess.run(["cc", "-O2", "-o", str(cls.program), str(build / "program.c"), str(build / "query.c"), "-ldl"],
check=True)
cls.ring = cls.dir / "ring0"
cls.ring.write_text("")
cls.virtual = cls.dir / "ring16"
cls.virtual.write_text("")
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, True)
def query(self, winebus=True, caller="sdl", path=None, **extra):
env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.lib, self.shim),
FAKE_EVDEV_MEMFD_PATHS="0=%s;16=%s" % (self.ring, self.virtual))
env.pop("FAKE_EVDEV_STEAM_PAD_AS_X360", None)
env.update(extra)
result = subprocess.run([str(self.program), str(self.winebus) if winebus else "-",
str(self.sdl_library) if caller == "sdl" else "program", str(path or self.ring)],
env=env, capture_output=True, text=True, timeout=10, check=True)
return result.stdout.strip()
def test_sdl_in_a_winebus_process_sees_a_ring_pad_as_the_steam_input_pad(self):
self.assertEqual(self.query(), "0 28de:11ff")
def test_sdl_outside_winebus_keeps_the_pad_identity(self):
self.assertEqual(self.query(winebus=False), "0 045e:028e")
def test_other_callers_and_devices_keep_their_identity(self):
self.assertEqual(self.query(caller="program"), "0 045e:028e")
self.assertEqual(self.query(path=self.virtual), "0 045e:028e")
def test_a_winebus_without_a_udev_bus_keeps_the_pad_for_sdl(self):
self.assertEqual(self.query(FAKE_EVDEV_STEAM_PAD_AS_X360="1"), "0 045e:028e")
if __name__ == "__main__":
unittest.main()
+9 -8
View File
@@ -6,6 +6,7 @@ from pathlib import Path
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
KEYS = ("DD_VKBRIDGE_WEBHELPER_ARGS", "DD_VKBRIDGE_CEF_ANGLE", "DD_VKBRIDGE_CEF_VULKAN")
BASE = "--no-zygote --in-process-gpu -AudioServiceOutOfProcess"
def layout_function():
@@ -27,14 +28,14 @@ class WebhelperLayoutTest(unittest.TestCase):
def test_angle_on_vulkan_brings_chromiums_vulkan_compositing(self):
self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="vulkan"),
"--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
BASE + " --use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
def test_vulkan_compositing_can_be_left_off(self):
def test_vulkan_compositing_can_be_left_off_without_zygotes(self):
self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="vulkan", DD_VKBRIDGE_CEF_VULKAN="0"),
"--use-gl=angle --use-angle=vulkan")
BASE + " --use-gl=angle --use-angle=vulkan")
def test_other_angle_backends_get_only_the_angle_switches(self):
self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="gl"), "--use-gl=angle --use-angle=gl")
self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="gl"), BASE + " --use-gl=angle --use-angle=gl")
def test_explicit_layout_wins(self):
self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="vulkan", DD_VKBRIDGE_WEBHELPER_ARGS="--x +Y"),
@@ -57,10 +58,10 @@ class WebhelperLayoutTest(unittest.TestCase):
env = {k: v for k, v in os.environ.items() if k not in KEYS}
run = lambda **s: subprocess.run(["bash", "-c", "set -u\n" + script], env={**env, **s},
capture_output=True, text=True, check=True).stdout.strip()
self.assertEqual(run(), "--use-gl=angle --use-angle=vulkan")
self.assertEqual(run(), BASE + " --use-gl=angle --use-angle=vulkan")
self.assertEqual(run(DD_VKBRIDGE_CEF_VULKAN="1"),
"--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
self.assertEqual(run(DD_VKBRIDGE_CEF_ANGLE="gl"), "--use-gl=angle --use-angle=gl")
BASE + " --use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
self.assertEqual(run(DD_VKBRIDGE_CEF_ANGLE="gl"), BASE + " --use-gl=angle --use-angle=gl")
def test_empty_settings_are_kept_as_set(self):
script = ': "${DD_VKBRIDGE_CEF_ANGLE=vulkan}" "${DD_VKBRIDGE_CEF_VULKAN=0}"\n' + layout_function() + "dd_webhelper_layout\n"
@@ -69,7 +70,7 @@ class WebhelperLayoutTest(unittest.TestCase):
capture_output=True, text=True, check=True).stdout.strip()
self.assertEqual(run(DD_VKBRIDGE_CEF_ANGLE=""), "stock")
self.assertEqual(run(DD_VKBRIDGE_CEF_VULKAN=""),
"--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
BASE + " --use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan")
if __name__ == "__main__":
@@ -0,0 +1,205 @@
import runpy
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from tools.tests.test_droiddeck_fex import AppInfoTest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
SESSION = BIN / "droiddeck-session"
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
EAC = 1826330
SCOUT = 1070560
EAC_ID = str(EAC)
SCOUT_ID = str(SCOUT)
EAC_NAME = "Proton EasyAntiCheat Runtime"
SCOUT_NAME = "Steam Linux Runtime 1.0 (scout)"
def tool(name, osarch="", kind="tool", installdir=None):
return {
"common": {"name": name, "oslist": "linux", "osarch": osarch, "type": kind},
"config": {"installdir": installdir or name},
}
class SteamToolManifestSeedTest(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name)
self.steam = self.root / "Steam"
(self.steam / "appcache").mkdir(parents=True)
(self.steam / "steamapps").mkdir()
self.entries = {EAC: tool(EAC_NAME), SCOUT: tool(SCOUT_NAME)}
self.write_appinfo()
def write_appinfo(self, entries=None):
COMPAT["APPINFO_CACHE"].clear()
(self.steam / "appcache/appinfo.vdf").write_bytes(
AppInfoTest.appinfo(self.entries if entries is None else entries))
def manifest(self, app, root=None):
return (root or self.steam) / ("steamapps/appmanifest_%s.acf" % app)
def seed(self):
return COMPAT["seed_unavailable_arm64_tools"](str(self.steam))
def test_seeds_bare_manifests_for_unavailable_tool_dependencies(self):
self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID])
for app, name in ((EAC_ID, EAC_NAME), (SCOUT_ID, SCOUT_NAME)):
text = self.manifest(app).read_text()
for expected in ('"appid" "%s"' % app, '"Universe" "1"', '"StateFlags" "4"',
'"name" "%s"' % name, '"installdir" "%s"' % name,
'"AutoUpdateBehavior" "1"'):
self.assertIn(expected, text)
self.assertFalse(self.manifest("976730").exists())
def test_seeding_is_idempotent(self):
self.seed()
first = {app: self.manifest(app).read_text() for app in (EAC_ID, SCOUT_ID)}
self.assertEqual(self.seed(), [])
self.assertEqual({app: self.manifest(app).read_text() for app in first}, first)
def test_a_real_install_in_another_library_is_never_overwritten(self):
other = self.root / "SD"
(other / "steamapps").mkdir(parents=True)
existing = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"4"\n}\n' % SCOUT_ID
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(existing)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other)
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertEqual((other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text(), existing)
def test_a_partial_install_in_another_library_is_completed_in_place(self):
other = self.root / "SD"
(other / "steamapps").mkdir(parents=True)
partial = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"2"\n}\n' % SCOUT_ID
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(partial)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other)
self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertIn('"StateFlags" "4"',
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text())
def test_a_real_install_in_any_library_wins_over_a_partial_one(self):
other = self.root / "SD"
(other / "steamapps").mkdir(parents=True)
partial = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"2"\n}\n' % SCOUT_ID
installed = '"AppState"\n{\n\t"appid"\t"%s"\n\t"StateFlags"\t"4"\n}\n' % SCOUT_ID
self.manifest(SCOUT_ID).write_text(partial)
(other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).write_text(installed)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other)
self.assertEqual(self.seed(), [EAC_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(), partial)
self.assertEqual((other / ("steamapps/appmanifest_%s.acf" % SCOUT_ID)).read_text(), installed)
def test_a_failed_write_leaves_no_manifest_behind(self):
real_link = COMPAT["os"].link
def fail_for_scout(source, target):
if SCOUT_ID in str(target):
raise OSError("disk full")
return real_link(source, target)
with mock.patch.object(COMPAT["os"], "link", side_effect=fail_for_scout):
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertEqual(sorted(p.name for p in (self.steam / "steamapps").iterdir()),
["appmanifest_%s.acf" % EAC_ID])
self.assertEqual(self.seed(), [SCOUT_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(),
COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True))
def test_new_manifest_publication_preserves_a_concurrent_install(self):
real_link = COMPAT["os"].link
installed = COMPAT["manifest_text"](SCOUT_ID, "Existing tool", "Existing", False)
def publish(source, target):
if SCOUT_ID in str(target):
Path(target).write_text(installed)
return real_link(source, target)
with mock.patch.object(COMPAT["os"], "link", side_effect=publish):
self.assertEqual(self.seed(), [EAC_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(), installed)
self.assertEqual(self.seed(), [])
self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*")))
def test_partial_staged_write_is_not_published_and_retry_repairs(self):
real_temporary = COMPAT["tempfile"].NamedTemporaryFile
def temporary(*args, **kwargs):
output = real_temporary(*args, **kwargs)
real_write = output.write
def write(text):
if SCOUT_ID in text:
real_write(text[:text.index(' "installdir"')])
output.flush()
raise OSError("disk full")
return real_write(text)
output.write = write
return output
with mock.patch.object(COMPAT["tempfile"], "NamedTemporaryFile", side_effect=temporary):
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*")))
self.assertEqual(self.seed(), [SCOUT_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(),
COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True))
def test_failed_replacement_preserves_partial_manifest_and_retry_repairs(self):
partial = '"AppState" { "appid" "%s" "StateFlags" "2" }' % SCOUT_ID
self.manifest(SCOUT_ID).write_text(partial)
with mock.patch.object(COMPAT["os"], "replace", side_effect=OSError("disk full")):
self.assertEqual(self.seed(), [EAC_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(), partial)
self.assertFalse(list((self.steam / "steamapps").glob(".appmanifest_*")))
self.assertEqual(self.seed(), [SCOUT_ID])
self.assertEqual(self.manifest(SCOUT_ID).read_text(),
COMPAT["manifest_text"](SCOUT_ID, SCOUT_NAME, SCOUT_NAME, True))
def test_tools_with_an_arm64_depot_are_skipped(self):
entries = dict(self.entries)
entries[SCOUT] = tool(SCOUT_NAME, osarch="arm64")
self.write_appinfo(entries)
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
def test_an_app_that_is_not_a_tool_is_skipped(self):
entries = dict(self.entries)
entries[SCOUT] = tool(SCOUT_NAME, kind="game")
self.write_appinfo(entries)
self.assertEqual(self.seed(), [EAC_ID])
self.assertFalse(self.manifest(SCOUT_ID).exists())
def test_missing_appinfo_uses_the_display_names(self):
(self.steam / "appcache/appinfo.vdf").unlink()
COMPAT["APPINFO_CACHE"].clear()
self.assertEqual(self.seed(), [EAC_ID, SCOUT_ID])
self.assertIn('"name" "%s"' % SCOUT_NAME, self.manifest(SCOUT_ID).read_text())
def test_flag_seeds_without_running_full_compatibility_setup(self):
with mock.patch.object(COMPAT["sys"], "argv",
["steam-compatibility", str(self.steam), "--seed-arm64-tools"]):
COMPAT["main"]()
self.assertTrue(self.manifest(EAC_ID).is_file())
self.assertTrue(self.manifest(SCOUT_ID).is_file())
self.assertFalse((self.steam / "compatibilitytools.d").exists())
def test_session_seeds_only_on_the_arm64_client_path(self):
arm64, x64 = SESSION.read_text().split(
" else\n _dd_x64_tool=$(droiddeck-steam-x64 --default-tool)", 1)
self.assertIn('steam-compatibility "$steam_root" --seed-arm64-tools', arm64)
self.assertNotIn("--seed-arm64-tools", x64)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -95,7 +95,7 @@ class SubsurfaceReleaseTest(unittest.TestCase):
def test_compositor_attach_and_commit_use_the_release_hold(self):
self.assertIn('pending_releases_cancel(buffer);', function_body(self.source, 'take_dmabuf'))
commit = function_body(self.source, 'surface_commit')
commit = function_body(self.source, 'surface_state_apply')
self.assertIn('pending_releases_apply(s);', commit)
self.assertLess(commit.index('take_dmabuf(s, db, buffer);'), commit.index('pending_releases_apply(s);'))
self.assertLess(commit.index('buf_trace_attach(buffer);'), commit.index('if (s->role == ROLE_CURSOR)'))
+17 -5
View File
@@ -47,13 +47,18 @@ static int g_dev_state, g_base_black;
static uintptr_t g_dev = 1;
static struct { int64_t wait_ns, wait_max_ns; unsigned waits; } g_perf;
static VkResult answer;
static unsigned timeouts, wait_calls;
static unsigned destroyed, unmapped, freed_memory, forgotten, errors;
static int64_t perf_now(void) { return 10; }
static void perf_add(int64_t *s, int64_t *m, unsigned *c, int64_t d) { *s+=d; *m=d; ++*c; }
static void __attribute__((unused)) droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; ++errors; }
#define LOGE(...) droiddeck_log("error", __VA_ARGS__)
static VkResult wait_fn(uintptr_t dev, unsigned n, const VkFence *f, int all, uint64_t timeout) {
(void)dev; (void)n; (void)f; (void)all; (void)timeout; return answer;
(void)dev; (void)n; (void)f; (void)all;
++wait_calls;
if (wait_calls > 1) assert(timeout == UINT64_MAX);
if (timeouts) { --timeouts; return VK_TIMEOUT; }
return answer;
}
static void unmap_fn(uintptr_t dev, uintptr_t mem) { (void)dev; (void)mem; ++unmapped; }
static void destroy_fn(uintptr_t dev, uintptr_t img, void *allocator) { (void)dev; (void)img; (void)allocator; ++destroyed; }
@@ -104,8 +109,15 @@ int main(void) {
vkp_image_destroy(image());
assert(destroyed==1 && unmapped==1 && freed_memory==1 && forgotten==1);
g_dev_state=1; g_base_black=1; answer=VK_TIMEOUT;
assert(timed_wait(1, 1000)==VK_TIMEOUT);
for (unsigned delays=1; delays<=3; ++delays) {
g_dev_state=1; g_base_black=1; answer=VK_SUCCESS;
timeouts=delays; wait_calls=0;
assert(timed_wait(1, 1000)==VK_SUCCESS);
assert(g_dev_state==1 && g_base_black==1 && wait_calls==delays+1);
}
g_dev_state=1; g_base_black=1; answer=VK_ERROR_UNKNOWN; wait_calls=0;
assert(timed_wait(1, 1000)==VK_ERROR_UNKNOWN);
assert(g_dev_state!=1 && g_dev_state!=-2); /* pending work is not DEVICE_LOST */
struct vkp_image *pending=image();
vkp_image_destroy(pending);
@@ -116,14 +128,14 @@ int main(void) {
assert(errors==first_errors); /* one terminal diagnostic, no repeated recovery */
free(pending); /* fake GPU exists only in this test */
g_dev_state=1; answer=VK_ERROR_OUT_OF_HOST_MEMORY;
g_dev_state=1; answer=VK_ERROR_OUT_OF_HOST_MEMORY; wait_calls=0; timeouts=1;
assert(timed_wait(1, 1000)==VK_ERROR_OUT_OF_HOST_MEMORY);
assert(g_dev_state!=1 && g_dev_state!=-2);
pending=image(); vkp_image_destroy(pending);
assert(destroyed==1 && unmapped==1 && freed_memory==1 && forgotten==1);
free(pending);
g_dev_state=1; answer=VK_ERROR_DEVICE_LOST;
g_dev_state=1; answer=VK_ERROR_DEVICE_LOST; wait_calls=0; timeouts=2;
assert(timed_wait(1, 1000)==VK_ERROR_DEVICE_LOST);
assert(g_dev_state==1); /* existing caller performs genuine device-loss cleanup */
return 0;
+7 -4
View File
@@ -111,15 +111,18 @@ int __android_log_print(int, const char *, const char *, ...);
def test_later_framegen_surface_lost_idle_failure(self):
self.run_scenario('later-surface-lost')
def test_finite_blit_timeout_same_size_shm_upload(self):
self.run_scenario('shm-timeout')
def test_blit_wait_error_same_size_shm_upload(self):
self.run_scenario('shm-wait-error')
def test_finite_blit_timeout_same_size_pixel_upload(self):
self.run_scenario('pixel-timeout')
def test_blit_wait_error_same_size_pixel_upload(self):
self.run_scenario('pixel-wait-error')
def test_lost_device_shm_upload_keeps_cpu_snapshot(self):
self.run_scenario('lost-shm-upload')
def test_delayed_blit_completes_and_next_frame_renders(self):
self.run_scenario('blit-delayed')
def test_normal_present(self):
self.run_scenario('normal')
+69 -4
View File
@@ -40,6 +40,39 @@ void upload(unsigned short type, unsigned short length) {
}
"""
SDL = r"""
#include <linux/input.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
int SDL_JoystickRumble(void *joystick, uint16_t low, uint16_t high, uint32_t duration) {
struct ff_effect effect;
(void)joystick;
printf("sdl %u %u duration %u\n", low, high, duration);
memset(&effect, 0, sizeof(effect));
effect.id = -1;
effect.type = FF_RUMBLE;
effect.replay.length = 0xffff;
effect.u.rumble.strong_magnitude = low;
effect.u.rumble.weak_magnitude = high;
return ioctl(3, EVIOCSFF, &effect);
}
"""
SDL_CALLER = r"""
#include <dlfcn.h>
#include <stdint.h>
int rumble(const char *library, uint16_t low, uint16_t high, uint32_t duration) {
void *sdl = dlopen(library, RTLD_NOW | RTLD_LOCAL);
int (*call)(void *, uint16_t, uint16_t, uint32_t) = (int (*)(void *, uint16_t, uint16_t, uint32_t))dlsym(sdl, "SDL_JoystickRumble");
call(0, low, high, duration);
return 0;
}
"""
PROGRAM = r"""
#include <dlfcn.h>
#include <linux/input.h>
@@ -47,8 +80,21 @@ PROGRAM = r"""
void upload(unsigned short type, unsigned short length);
int rumble(const char *library, unsigned short low, unsigned short high, unsigned int duration);
int main(int argc, char **argv) {
void *winebus = dlopen(argv[1], RTLD_NOW);
if (argv[2][0] == 's') {
int (*from_winebus)(const char *, unsigned short, unsigned short, unsigned int) =
(int (*)(const char *, unsigned short, unsigned short, unsigned int))dlsym(winebus, "rumble");
for (const char *step = argv[3]; *step; step++) {
if (*step == 'w') from_winebus(argv[4], 65535, 32768, 1000);
if (*step == 'z') from_winebus(argv[4], 0, 0, 0);
if (*step == 'p') rumble(argv[4], 65535, 32768, 1000);
}
fflush(stdout);
return 0;
}
void (*from_winebus)(unsigned short, unsigned short) = (void (*)(unsigned short, unsigned short))dlsym(winebus, "upload");
if (argv[2][0] == 'w') from_winebus(argv[3][0] == 'r' ? FF_RUMBLE : FF_PERIODIC, 1000);
else upload(FF_RUMBLE, 1000);
@@ -65,7 +111,8 @@ class WinebusRumblePreloadTest(unittest.TestCase):
cls.dir = Path(tempfile.mkdtemp())
build = cls.dir / "build"
build.mkdir()
for name, text in (("shim.c", SHIM), ("upload.c", UPLOAD), ("program.c", PROGRAM)):
for name, text in (("shim.c", SHIM), ("upload.c", UPLOAD), ("program.c", PROGRAM), ("sdl.c", SDL),
("sdl_caller.c", SDL_CALLER)):
(build / name).write_text(text)
cls.lib = cls.dir / "libddsession.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib),
@@ -73,10 +120,13 @@ class WinebusRumblePreloadTest(unittest.TestCase):
cls.shim = cls.dir / "libshim.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.shim), str(build / "shim.c")], check=True)
cls.winebus = cls.dir / "winebus.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.winebus), str(build / "upload.c")], check=True)
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.winebus), str(build / "upload.c"),
str(build / "sdl_caller.c"), "-ldl"], check=True)
cls.sdl_library = cls.dir / "libSDL2-2.0.so.0"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.sdl_library), str(build / "sdl.c")], check=True)
cls.program = cls.dir / "program"
subprocess.run(["cc", "-O2", "-o", str(cls.program), str(build / "program.c"), str(build / "upload.c"), "-ldl"],
check=True)
subprocess.run(["cc", "-O2", "-o", str(cls.program), str(build / "program.c"), str(build / "upload.c"),
str(build / "sdl_caller.c"), "-ldl"], check=True)
@classmethod
def tearDownClass(cls):
@@ -88,6 +138,21 @@ class WinebusRumblePreloadTest(unittest.TestCase):
capture_output=True, text=True, timeout=10, check=True)
return result.stdout.splitlines()
def sdl(self, steps):
env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.lib, self.shim))
result = subprocess.run([str(self.program), str(self.winebus), "sdl", steps, str(self.sdl_library)], env=env,
capture_output=True, text=True, timeout=10, check=True)
return result.stdout.splitlines()
def test_rumble_winebus_starts_through_sdl_is_held_until_the_next_update(self):
self.assertEqual(self.sdl("wz"), ["sdl 65535 32768 duration 0", "shim type %d length 0" % 0x50,
"sdl 0 0 duration 0", "shim type %d length 0" % 0x50])
def test_sdl_rumble_from_other_code_keeps_its_duration_and_length(self):
self.assertEqual(self.sdl("p"), ["sdl 65535 32768 duration 1000", "shim type %d length 65535" % 0x50])
self.assertEqual(self.sdl("wp"), ["sdl 65535 32768 duration 0", "shim type %d length 0" % 0x50,
"sdl 65535 32768 duration 1000", "shim type %d length 65535" % 0x50])
def test_winebus_rumble_reaches_the_shim_held_and_comes_back_unchanged(self):
self.assertEqual(self.upload("winebus"), ["shim type %d length 0" % 0x50, "caller length 1000"])
+19 -6
View File
@@ -7,7 +7,7 @@ struct vk_api g_vk;
static unsigned operations, acquires, submits, markers, waits, idle_calls, resets;
static unsigned destroys, releases, lost_notifications, presented_notifications;
static VkResult idle_answer, fence_answer, acquire_answer, present_answer;
static unsigned fail_acquire_at;
static unsigned fail_acquire_at, fence_timeouts;
static int generated;
/* Every work-issuing callback is an oracle: no GPU operation after a terminal
@@ -19,7 +19,9 @@ static VkResult acquire(VkDevice d, VkSwapchainKHR s, uint64_t t, VkSemaphore a,
}
static VkResult idle(VkDevice d) { live(); ++idle_calls; return idle_answer; }
static VkResult wait_fences(VkDevice d, uint32_t n, const VkFence *f, VkBool32 all, uint64_t t) {
live(); ++waits; return fence_answer;
live(); ++waits;
if (fence_timeouts) { --fence_timeouts; return VK_TIMEOUT; }
return fence_answer;
}
static VkResult submit(VkQueue q, uint32_t n, const VkSubmitInfo *s, VkFence f) {
live(); ++submits; if (!s->commandBufferCount) ++markers; return VK_SUCCESS;
@@ -235,7 +237,7 @@ static void acquire_failure(int later, VkResult result) {
free(g_images); /* test-owned fake resources only */
}
static void upload_timeout(int single_pixel) {
static void upload_wait_error(int single_pixel) {
setup(0);
uint8_t bytes[48], saved[48], data[16];
memset(bytes, 0xa5, sizeof(bytes)); memset(data, 0x3c, sizeof(data));
@@ -251,7 +253,7 @@ static void upload_timeout(int single_pixel) {
assert(bytes[3] == 0x3c && bytes[0] == 0xa5 && releases == 1);
memcpy(saved, bytes, sizeof(saved));
struct vkp_image dst = {.image = (VkImage)(uintptr_t)9, .blit_dst = 1, .w = img->w, .h = img->h};
fence_answer = VK_TIMEOUT;
fence_answer = VK_ERROR_OUT_OF_HOST_MEMORY;
assert(vkp_blit_image(img, &dst, -1) == -1);
assert(g_dev_state == -3 && submits == 1 && waits == 1);
memset(data, 0x7e, sizeof(data));
@@ -279,8 +281,8 @@ int main(int argc, char **argv) {
else if (!strcmp(name, "first-surface-lost")) acquire_failure(0, VK_ERROR_SURFACE_LOST_KHR);
else if (!strcmp(name, "later-out-of-date")) acquire_failure(1, VK_ERROR_OUT_OF_DATE_KHR);
else if (!strcmp(name, "later-surface-lost")) acquire_failure(1, VK_ERROR_SURFACE_LOST_KHR);
else if (!strcmp(name, "shm-timeout")) upload_timeout(0);
else if (!strcmp(name, "pixel-timeout")) upload_timeout(1);
else if (!strcmp(name, "shm-wait-error")) upload_wait_error(0);
else if (!strcmp(name, "pixel-wait-error")) upload_wait_error(1);
else if (!strcmp(name, "lost-shm-upload")) {
setup(0);
uint8_t bytes[64], data[16];
@@ -295,6 +297,17 @@ int main(int argc, char **argv) {
free(img.recovery_pixels);
free(g_images);
} else if (!strcmp(name, "pass-terminal")) { setup(0); g_dev_state = -3; assert_stopped(); free(g_images); }
else if (!strcmp(name, "blit-delayed")) {
setup(0);
struct vkp_image src = {.image = (VkImage)(uintptr_t)7, .w = 1, .h = 1};
struct vkp_image dst = {.image = (VkImage)(uintptr_t)8, .w = 1, .h = 1, .blit_dst = 1};
fence_timeouts = 3;
assert(vkp_blit_image(&src, &dst, -1) == 0);
assert(g_dev_state == 1 && submits == 1 && waits == 4 && destroys == 0);
assert(vkp_blit_image(&src, &dst, -1) == 0);
assert(g_dev_state == 1 && submits == 2 && waits == 5 && destroys == 0);
free(g_images);
}
else if (!strcmp(name, "normal") || !strcmp(name, "framegen")) {
int extra = !strcmp(name, "framegen"); setup(extra);
assert(vkp_render(64, 64, NULL, 0) == 0 && g_dev_state == 1);
@@ -1,9 +0,0 @@
[Desktop Entry]
Name=Return to Gaming Mode
Comment=Log out of the desktop and go back to Steam
Exec=dbus-send --session --type=method_call --dest=org.kde.Shutdown /Shutdown org.kde.Shutdown.logout
Icon=steamdeck-gaming-return
Terminal=false
Type=Application
StartupNotify=false
NoDisplay=true
+26
View File
@@ -344,12 +344,31 @@ static void report_limits(VkPhysicalDeviceLimits *limits, uint32_t gaps)
}
}
/* Mali's driver crashes compiling Zink's geometry shaders (SIGSEGV at 0x40 in
* cmpbe_v2_compile_multiple_shaders) and takes the render server and the application with it; a plain
* one draws nothing. Zink draws GL_QUADS through one; without the feature Mesa splits quads into
* triangles itself. DXVK needs the feature for D3D10 and 11, so only Zink loses it.
* DROIDDECK_MALI_COMPAT_NO_GS=0 keeps it for Zink, =1 hides it from every application. */
static bool hide_geometry_shader(struct instance *inst, VkPhysicalDevice physical_device)
{
const char *setting = getenv("DROIDDECK_MALI_COMPAT_NO_GS");
if (setting && *setting)
return strcmp(setting, "1") == 0;
if (!inst->zink)
return false;
VkPhysicalDeviceProperties properties;
inst->GetPhysicalDeviceProperties(physical_device, &properties);
return properties.vendorID == 0x13b5; /* ARM */
}
static VKAPI_ATTR void VKAPI_CALL GetPhysicalDeviceFeatures(VkPhysicalDevice physical_device,
VkPhysicalDeviceFeatures *features)
{
struct instance *inst = instance_from_handle(physical_device);
inst->GetPhysicalDeviceFeatures(physical_device, features);
report_features(features, physical_device_gaps(inst, physical_device));
if (hide_geometry_shader(inst, physical_device))
features->geometryShader = VK_FALSE;
}
static VKAPI_ATTR void VKAPI_CALL GetPhysicalDeviceFeatures2(VkPhysicalDevice physical_device,
@@ -363,6 +382,8 @@ static VKAPI_ATTR void VKAPI_CALL GetPhysicalDeviceFeatures2(VkPhysicalDevice ph
inst->GetPhysicalDeviceFeatures2(physical_device, features);
relink(dropped, dropped_count);
report_features(&features->features, gaps);
if (hide_geometry_shader(inst, physical_device))
features->features.geometryShader = VK_FALSE;
if (tracing()) {
char chain[512] = "";
size_t used = 0;
@@ -463,6 +484,8 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo
inst->key = dispatch_key(*instance);
inst->handle = *instance;
inst->active = wanted();
const char *engine = info->pApplicationInfo ? info->pApplicationInfo->pEngineName : NULL;
inst->zink = engine && strcmp(engine, "mesa zink") == 0;
inst->gipa = gipa;
pthread_mutex_init(&inst->lock, NULL);
#define LOAD(name) inst->name = (PFN_vk##name)gipa(*instance, "vk" #name);
@@ -624,6 +647,9 @@ static VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice physical_dev
if (properties.limits.maxFragmentInputComponents < components)
components = properties.limits.maxFragmentInputComponents;
dev->max_varying_locations = components / 4;
if (inst->active && hide_geometry_shader(inst, physical_device))
layer_log("geometryShader is hidden from %s: the driver crashes compiling geometry shaders",
inst->zink ? "Zink" : "every application");
pthread_mutex_lock(&global_lock);
dev->next = devices;
+1
View File
@@ -63,6 +63,7 @@ struct instance {
void *key;
VkInstance handle;
bool active;
bool zink; /* the engine is Mesa's Zink */
PFN_vkGetInstanceProcAddr gipa;
PFN_vkDestroyInstance DestroyInstance;
PFN_vkEnumerateDeviceExtensionProperties EnumerateDeviceExtensionProperties;