Compare commits

...
Author SHA1 Message Date
Kurt Himebauch a6984e495a fix(xbox): repair the patch hunk for the pretty-printed manifest test 2026-11-24 19:01:09 -05:00
Kurt Himebauch 56b0559a85 fix(xbox): an application element with attributes on the next line still counts 2026-11-24 18:58:12 -05:00
The412Banner 9e6f81540f feat(bionic): DroidDeck-Bionic compatibility tool (Wine on Android's libc, no proot) (#3037)
DroidDeck-Bionic: a Steam compatibility tool that runs the game itself on Android's libc (bionic) instead of glibc inside proot. Steam, the stores and the session stay on DroidDeck's Linux side; only the game process leaves proot.

- Listed in the Proton list only when Run without proot is on, in its own row. Its builds are pre-releases on Droid-Deck/DroidDeck-Proton (DroidDeck-Bionic-12.8-rNN, runtime built by .github/workflows/build-bionic-runtime.yml from tools/bionic-runtime); the app installs and updates them like the other extra tools and never makes one the default unless the user picks it.
- With proot on, a launch sent to a bionic tool goes to the newest DroidDeck-Proton (picks stay as set).
- ProtonExtras / ProtonMenu / ExperimentalProtons / droiddeck-proton-extra: bionic pre-releases checked and listed only without proot; updates carry the default and per-game picks over; deleting a tool never follows links out of it. ProtonDefault: picks left on an older bionic build move to the installed one.
- Components: FEX builds for bionic (bionic-stable on DroidDeck-Components); each tool is offered only the FEX builds that fit it.
- Session logs: the bionic game log and its graphics logs are part of Share logs.

Synced with main twice before the merge (latest sync fbed69ce on main 67b82ad9; Build APK and validation green); a local trial merge on main 3e1fc3e6 had no conflicts and the game-environment, Proton-extra and store-launch tests pass.
2026-11-24 23:39:23 +00:00
Kurt Himebauch 3e1fc3e60e fix(xbox): a bundle with resource packages installs from its application package (#3172)
* fix(xbox): a bundle with resource packages installs from its application package

* fix(xbox): repair the patch hunk for the hoist tests
2026-11-24 18:32:38 -05:00
MaxsTechReview 826853fff5 fix(desktop): package updates that set file capabilities finish without proot (#3151) 2026-11-24 18:25:05 -05:00
MaxsTechReview 9be131cf6d fix(native): a trailing slash after a program keeps the hook's exe name like the kernel (#3171) 2026-11-24 18:24:41 -05:00
Kurt Himebauchandmaxjivi05 5ed97915c7 fix(session): report the CPU cache sizes the x86 CPUID reports to Windows programs (#2705)
* fix(session): report the CPU cache sizes the x86 CPUID reports to Windows programs

* fix(session): clear the staged core caches without following links

* fix(session): stage CPU cache binds per session generation and per core

* fix(session): keep every start's staged CPU caches until the process ends

* fix(session): give every start its own CPU cache staging folder

* test(session): a delayed worker from a recreated service keeps its own cache folder

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-24 18:18:14 -05:00
Kurt Himebauch d8654ae1be fix(retroarch): use the packaged assets, cores and core info paths (#2451)
* fix(retroarch): use the packaged assets, cores and core info paths

* fix(retroarch): migrate incomplete configs

* fix(retroarch): preserve configured core directories

* fix(retroarch): replace empty path settings in place

* fix(retroarch): keep installed core directory when repairing a blank libretro_directory
2026-11-24 18:15:35 -05:00
Kurt Himebauch 8f4744398d fix(ea): a failed touchup is retried and its output reaches the store log (#2505)
* fix(ea): a failed touchup is retried and its output reaches the store log

* fix(ea): bound the touchup output kept for the store log

The output goes to a temporary file and only its last 64 KiB are read back. The timeout test now checks the output is logged and the next launch retries.

* fix(ea): a touchup still runs when its output cannot be captured
2026-11-24 18:15:30 -05:00
The412BannerandKurt Himebauch 8f4cefd3bd fix(game-env): turn on FEX x87 FIP emulation for the SecuROM racing title that needs it (#3092)
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 18:13:22 -05:00
Kurt Himebauch 01dc415f10 fix(gog): check space for the extracted install before downloading an offline installer (#2419)
* fix(gog): bind every store root for installer extraction and log its error

* fix(gog): count the extracted size before downloading an offline installer

The installer fallback only checked free space for the download, so a
game that needs the download plus its extracted files failed after
every part was fetched, with innoextract's stream error. The failure
reason now drops innoextract's warnings and bug-report trailer.

* fix(gog): keep the internal store root visible to installer extraction

* fix(games): never give an added folder the internal store guest path

An added folder named Stores was bound at /root/Games/Stores, over the
internal store install root. legacyRoots, used by bindFolder and the
games-folder migration, now gives such a folder a suffixed guest path,
so guestBinds mounts every added root again, matching guestPath and the
session binds.

* fix(games): re-path saved folder binds that hold the internal store guest path

* test(games): verify extractor binds after migrating a saved internal-guest bind

* fix(gog): keep innoextract output in the log and leave the install failure message unchanged

* fix(gog): count known installer part sizes in the free-space check when some part has no size
2026-11-24 18:13:16 -05:00
Tushar GandheandKurt Himebauch af1fe6c61c fix(launcher): LT and RT keep the focus ring on the tab rail (#3039)
* fix(launcher): LT and RT keep the focus ring on the tab rail

A trigger step selected the tab like a tap on the rail, which also sent focus into the new page, and each page put it somewhere different. The step now shows the page and focuses its rail item, and for a second puts focus back on the rail if the page takes it, until another key is pressed. Dual screens, which have no rail on the main screen, keep focusing the page.

* fix(launcher): end the trigger step's rail hold when another navigation changes the page

A navigation that changed the selected page during the hold, such as opening a game from a link, was undone: the hold focused the stepped tab's rail item, and that focus switched the page back. The hold now stops as soon as the selection is no longer the one the step made.

* fix(launcher): end the trigger step's rail hold when another navigation opens a page

Opening the Components page does not change the selected tab, so a navigation there during the hold kept it running and the hold could pull focus from Components back to the rail. The hold now also tracks the page key: once the page its own step opened is showing, any other page ends the hold.

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 18:13:10 -05:00
The412BannerandKurt Himebauch 7bf75af8a1 fix(input): only an on-screen left mouse button stops screen taps from clicking (#3008)
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 18:13:05 -05:00
TapuukandTapuuk c08952dff9 perf(input): throttle on-screen stick knob redraws to about 30 fps (#2842)
The unified input surface redrew the overlay on every stick move. Knob-only
moves now redraw through ThrottledRedraw at 33 ms and skip sub-pixel moves
away from the rim. Pad updates still go out on every event; touch down, touch
up and reaching the rim still redraw immediately.

Co-authored-by: Tapuuk <177422350+Tapuuk@users.noreply.github.com>
2026-11-24 17:50:20 -05:00
MaxsTechReview 58430cd393 fix(library): persist explicitly selected executables in discovered folders (#2818)
fix(library): keep re-selected executables and store launchers across scans
2026-11-24 17:50:14 -05:00
Kurt Himebauch 46d42f9ca9 fix(library): keep another program of a Steam install out of the Steam app's route (#2742)
* fix(library): keep another program of a Steam install out of the Steam app's route

* fix(library): cover a Steam-edited target in the unrouted-program test and docs

* fix(library): keep Steam-edited targets routed and release stale Spacewar imports for other programs

* fix(library): keep Steam-edited targets adopted before the marker existed routed

A saved executable and seen revision without the adoption marker are recognised
from the Steam shortcut record (its target is the current executable and differs
from the one the app asked for), and the marker is stored.
2026-11-24 17:50:09 -05:00
The412Banner 43ff1db06b fix(appimage): DwarFS AppImages unpack without proot (#3161) 2026-11-24 17:50:04 -05:00
The412Banner f934feb457 fix(input): Remote Play connects again after the controls revert (#2968)
#2958 reverted the controller redesign and its follow-ups, and #2946 was
in that list, so streaming_client lost the real libudev again. #2963
brought back #2942 but not #2946. With the session's udev answers,
SDL3 in streaming_client hands a virtual pad's handle to the real
udev_device_get_driver and crashes about a second after it starts.

streaming_client in steamrtarm64/steamrt64 keeps the real libudev again,
like the Steam client. The no-driver answer for pads that #2946 also
added is left to #2915, which covers every device call.
2026-11-24 17:49:59 -05:00
xlulx 79d41b29ad fix(gamescope): the nested mouse moves the pointer while touch is Disabled (#2961)
The nested Wayland pointer reaches wlserver as touch 0, and in the Disabled
touch click mode wlserver_touchmotion returned before moving anything.
Buttons go through wlserver_mousebutton, so they still arrived, at an X
pointer that stayed at (0,0). Steam picks Disabled for Don't Starve
Together: DroidDeck's cursor followed the mouse while every click landed
in the top-left corner. The nested pointer now warps the X pointer in
Disabled as in the other modes; real fingers are still ignored.
2026-11-24 17:49:54 -05:00
Kurt Himebauch bb6523cd9c fix(display): keep the 16:9 stretch size on the game screen after Steam resizes it (#2738) 2026-11-24 17:49:49 -05:00
Albert Carreras 925e9743a8 fix(game-env): draw Dragon Quest Monsters 4 slime bodies (#2847)
At the game's default monster mesh detail, slimes show only their tips.
Set the two skeletal mesh detail values in Engine.ini before each launch,
in the prefix the game profile selects, and keep the file's permissions.
The game ignores -ini: overrides and deletes a writable Engine.ini after
reading it, so a launch argument or a one-time write does not work.
2026-11-24 17:49:44 -05:00
JM LamboandJacob Lambert 049c4be6e5 fix(desktop): Plasma draws on the system PowerVR driver (#2836)
* fix(desktop): Plasma draws on the system PowerVR driver

KWin lacks the Android-buffer Wayland protocol the system PowerVR driver's
swapchain needs, so every Plasma client failed with "zink: could not create
swapchain" and the desktop stayed black under the cursor. Plasma's clients now
present through DRI on that path, as the Steam session already does.

* test(desktop): the kopper override reaches Plasma's child processes

* test(desktop): check the kopper override where Plasma launches

---------

Co-authored-by: Jacob Lambert <183008808+JMLambo@users.noreply.github.com>
2026-11-24 17:49:39 -05:00
e36cf24ba9 fix(guest): use /usr/bin/python3 in the payload shebangs, not /usr/bin/env (#2930)
PRoot's link2symlink resolves /usr/bin/env to a `.l2s.env….` stub and the
guest's uutils coreutils multicall refuses that name:

  Security violation: Requested utility 'env' does not match executable
  name: /usr/lib/cargo/bin/coreutils/.l2s.env0001.0116

Every exec of these five scripts therefore dies with GUEST_EXIT 1 before
Python starts, 20-60 ms into the session. They are droiddeck-diagnostic-
inventory (the session's first child), droiddeck-desktop-bookmarks (the
desktop's bookmarks refresh), droiddeck-ime, droiddeck-steam-games and
droiddeck-steam-shortcuts.

The absolute interpreter is what the other payload scripts already use,
and the guest runtime installs the python3 package (tools/ubuntu/
packages-runtime.txt), so /usr/bin/python3 exists in the rootfs.

Only the tracked overlay copies change: app/src/main/assets/linuxfs is
generated by the stageSessionScripts Gradle task, so the asset copies
follow from the overlay.

Co-authored-by: Pablo González <pgm1207@users.noreply.github.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 17:49:33 -05:00
The412BannerandKurt Himebauch 1772291da7 fix(native): programs started through the rootfs loader show their own command line (#3055)
* fix(native): programs started through the rootfs loader show their own command line

Without proot every dynamic guest program runs as "ld.so --preload <hook>
--library-path <dirs> --argv0 <name> <program> <args>", and the kernel's
/proc/<pid>/cmdline kept all of it. Launchers and the session match programs
by their command line, and Wine only moves its Windows command line over its
loader's name when its arguments follow each other, so the Battle.net launcher
never saw Battle.net.exe, gave up after five minutes and ended the session
with the game still running.

The hook now moves the program's own arguments to the front of that area at
start, as an exec of the program would have laid them out.

* fix(native): programs the app starts natively keep their path for /proc/<pid>/exe

* fix(native): the rewritten command line keeps AT_EXECFN naming the program

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 17:48:17 -05:00
The412Banner 3c4ac03656 fix(display): layer buffers are imported as AHardwareBuffers only on the phone's own Vulkan driver (#3076)
* fix(display): layer buffers are imported as AHardwareBuffers only on the phone's own Vulkan driver

* fix(display): a failed 10-bit layer pool still falls back to 8-bit linear buffers
2026-11-24 17:33:21 -05:00
The412Banner 7248d01b1b fix(storage): the Add game picker lists every card the file manager can open (#3123) 2026-11-24 17:30:41 -05:00
The412Banner f1f98c3bab fix(graphics): let Auto-installed display drivers fall back to the system driver (#2977) 2026-11-24 17:30:36 -05:00
The412Banner 4405e2a389 fix(graphics): the Mali bridge switch works on GPUs without a Mali kernel node (#3164) 2026-11-24 17:30:32 -05:00
Kurt Himebauch 67b82ad9b4 fix(epic): hand Epic's terms step to the browser instead of looping the sign-in (#2421)
* fix(epic): hand Epic's terms step to the browser instead of looping the sign-in

When Epic's redirect page answers corrective_action_required (privacy policy or EULA
acceptance, e.g. for a newly created account), open Epic's account sign-in in the Android
browser, where the step is shown, and tell the user to finish it there and retry, instead
of failing verification and reloading the sign-in.

* test(epic): remove live response identifiers from fixture

* test(epic): cover browser step selection

* fix(epic): ignore a stale sign-in page read after the login was reloaded

* fix(epic): hold the browser handoff until the sign-in screen is started
2026-11-24 17:20:00 -05:00
The412Banner 33bdc75a99 fix(logs): Share logs includes RPCS3's own log from the session (#3130) 2026-11-24 17:19:54 -05:00
The412Banner a573f8b14f fix(session): a fixed portrait resolution applies when landscape is set to Follow screen (#3124) 2026-11-24 17:19:50 -05:00
MaxsTechReviewandKurt Himebauch 7630173b24 fix(ddsession): keep path and status buffers off the wrapper fast path (#3071)
dd_descriptor_unlink, dd_descriptor_rmdir and dd_descriptor_rename put
one or two PATH_MAX buffers on their own frame (12 KB, 24 KB), and
dd_status_without_tracer put its 16 KB status buffer there, even on the
common path that only calls through to libc. Threads with small stacks,
such as .NET or Wine threads near their guard page, could overflow in
an otherwise plain unlink, rename or open.

The wrappers now do only the cheap checks and call the real function;
the buffers live in noinline helpers that run only when the descriptor
store or the status rewrite is actually needed. A test compiles both
sources with -fstack-usage and keeps each wrapper frame under 1 KB.

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 17:19:24 -05:00
DeathKhan 7d942367fd fix(apps): Up and Down in the app grid follow fast presses and keep the row in view (#2906)
* fix(apps): Up and Down in the app grid follow fast presses and keep the row in view

The grid composes rows ahead of the view without placing them. Down focused a tile there directly, so focus moved into
rows that never scrolled in, and the next Down searched from a tile with no place on screen and landed on the first
tile, sending the list back to the top. Up used the grid's own search, which works from where tiles are drawn at that
moment: with presses faster than the scroll it skipped the first row or drifted a column. And presses aimed from the
last settled focus, so fast ones were lost.

Up and Down now aim from the tile a move is already heading to, scroll that row fully into view, then focus it. At the
first or last row a press leaves the grid as before, unless a move has not landed yet, in which case it waits.

* fix(apps): a newer Up/Down move cancels the one still on its way, and a cancelled reveal frees the edge rows

A move whose target was not yet attached kept retrying its focus after a newer press, so the older tile could take
focus back. Each press now cancels the move before it. The pending target is also cleared when the reveal scroll is
cancelled (for example by a touch scroll), so Down on the last row and Up on the first no longer stay blocked.

* Apps: an Up/Down move holds its target tile by id and clears it only if it is still the latest move

A list update that shifts the tiles no longer leaves the next press aiming from the old index, and a
target that left the list drops its move. A cancelled move finishing late no longer clears the target
of a newer move to the same tile.
2026-11-24 17:14:45 -05:00
The412Banner da0a01a25b fix(input): pace stick-only pad reports to the guest at 250 Hz (#2902)
* fix(input): pace stick-only pad reports to the guest at 250 Hz

* fix(input): drop stale paced pad callbacks and time the interval from the flush
2026-11-24 17:14:40 -05:00
visail 9a7cb70969 fix(session): serialize launch requests in a coordinator (#3044)
* fix(session): serialize launch requests in a coordinator

Replace the gameLaunchRequest counter and the single pendingGameLink field
with a LaunchCoordinator. A launch is now identified by a ticket, so a stale
callback can only act on its own request, and a game link is superseded by
any newer launch. Launching is also refused while a package install stage
is in progress.

* fix(frontend): a replacement intent supersedes uncommitted launch state

A game link that resolved while the launcher was not resumed stayed pending, so
opening Settings, following a notification or picking a shortcut left it in the
coordinator and the next library refresh launched the old game over the new
screen. The same gap let an ACTION_SETUP intent leave an accepted launch current,
so a late Xbox manifest check could start the game after the user had moved on.

A replacement activity intent now cancels every ticket this activity has not
dispatched, and the refresh path may only finish a link owned by the intent the
activity shows. The toast for a superseded store lookup is gated on its ticket,
and the coordinator test now proves cancelAll() invalidates a link ticket.

The deferred Proton-compat launch is untouched: its ordering still predates this
change and has its own follow-up.
2026-11-24 17:14:35 -05:00
181 changed files with 7342 additions and 331 deletions

No files matched your search

@@ -0,0 +1,35 @@
name: Build bionic runtime pack and DroidDeck-Bionic tool
on:
push:
paths:
- 'tools/bionic-runtime/**'
- 'tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch'
- 'tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch'
- 'app/src/main/cpp/fakeinput_steam.cpp'
- 'tools/gpuload/**'
- '.github/workflows/build-bionic-runtime.yml'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- name: Host tools
run: |
set -euo pipefail
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev \
libxcb1-dev libxcb-composite0-dev libglm-dev zstd
- name: Build
run: |
set -euo pipefail
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
export BUILD_NUMBER=${{ github.run_number }}
tools/bionic-runtime/build.sh "$RUNNER_TEMP/bionic-runtime" "$PWD/out"
- uses: actions/upload-artifact@v4
with:
name: droiddeck-bionic-runtime-${{ github.sha }}
path: out/*
+1
View File
@@ -72,6 +72,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
- Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim.
+32 -1
View File
@@ -205,6 +205,11 @@ static void controller_fork_prepare();
static void controller_fork_parent();
static void controller_fork_child();
// bionic: libc's own start-up calls hooked functions (access) before environ is set. Settings read
// then would be empty and cached for good, so until environ exists hooks see defaults, uncached.
extern "C" char **environ;
static bool env_ready() { return environ != nullptr; }
struct FakeConfig {
const char *hook_dir;
const char *udev_data_dir;
@@ -218,6 +223,10 @@ struct FakeConfig {
// would throw a recursive-init error there, so the fields are filled without allocating, and a
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
static FakeConfig &config() {
if (!env_ready()) {
static FakeConfig early = {"/data/data/com.termux/files/home/fake-input", nullptr, false, false, false};
return early;
}
static FakeConfig cfg;
static std::atomic<int> state{0};
static __thread bool initializing __attribute__((tls_model("initial-exec")));
@@ -587,7 +596,7 @@ get_fake_input_rdev(const char *event) {
__attribute__((visibility("hidden"))) static void load_ring_paths() {
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
if (ring_paths_loaded)
if (ring_paths_loaded || !env_ready())
return;
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
@@ -807,12 +816,25 @@ __attribute__((visibility("hidden"))) static bool is_steam_client() {
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
// The bionic Proton layer's winebus has no udev bus, and its SDL bus skips 28de:11ff (Proton reads Steam's virtual
// pad through udev/evdev), so with FAKE_EVDEV_STEAM_PAD_AS_X360=1 other processes see that pad as a plain Xbox 360 pad.
__attribute__((visibility("hidden"))) static bool steam_pad_as_x360() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *v = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
known = v && atoi(v) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
__attribute__((visibility("hidden"))) static bool
presents_xbox_triggers(const FakeController &fake) {
return fake.uinput || !is_steam_client();
@@ -1391,6 +1413,7 @@ static std::unordered_map<int, std::shared_ptr<DeckHidraw>> &deck_map() {
static bool fake_deck_enabled() {
static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
return enabled == 1;
}
@@ -1398,6 +1421,7 @@ static bool fake_deck_enabled() {
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
static int type = -1;
if (type < 0) {
if (!env_ready()) return PAD_TYPE_DECK;
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
@@ -1470,6 +1494,7 @@ __attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
static bool fake_triton_enabled() {
static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0)
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
return enabled == 1;
@@ -2091,6 +2116,7 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
static TouchRingFile *ring = nullptr;
if (!env_ready()) return nullptr;
static std::once_flag once;
std::call_once(once, [] {
const char *path = getenv("FAKE_TOUCHCTL_RING");
@@ -2434,6 +2460,7 @@ __attribute__((constructor)) static void start_touch_controller() {
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
if (!env_ready()) return nullptr;
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
return dir && *dir ? dir : nullptr;
}
@@ -3689,6 +3716,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
id.bustype = 0x03;
if (made) {
id = made->id;
if (steam_pad_as_x360() && id.vendor == STEAM_VIRTUAL_VENDOR_ID && id.product == STEAM_VIRTUAL_PRODUCT_ID) {
id.vendor = X360_VENDOR_ID;
id.product = X360_PRODUCT_ID;
}
} else if (presents_steam_virtual()) {
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
id.product = STEAM_VIRTUAL_PRODUCT_ID;
+4 -1
View File
@@ -163,6 +163,7 @@ struct layer {
ARect geo_src, geo_dst;
int geo_valid;
int alloc_tier;
unsigned import_failed_fmts;
uint64_t pool_modifier;
int first_logged;
int64_t drop_logged_ns;
@@ -487,7 +488,8 @@ static const char *tier_name(int tier) {
static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fmt) {
g_alloc_failed = 0;
while (l->alloc_tier <= TIER_LINEAR) {
const unsigned fmt_bit = fmt == AHB_RGB10A2 ? 2u : 1u;
while (l->alloc_tier <= TIER_LINEAR && !(l->import_failed_fmts & fmt_bit)) {
const int tier = l->alloc_tier;
AHardwareBuffer_Desc d = {
.width = (uint32_t)w, .height = (uint32_t)h, .layers = 1,
@@ -560,6 +562,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd);
AHardwareBuffer_release(ahb);
if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; }
l->import_failed_fmts |= fmt_bit;
g_alloc_failed = 1;
return -1;
}
@@ -1494,7 +1494,7 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
}
int vkp_can_import_ahb(void) {
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && g_ahb_import &&
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && !g_library_name && g_ahb_import &&
g_vk.GetAndroidHardwareBufferPropertiesANDROID;
}
@@ -53,6 +53,8 @@ import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.session.LaunchCoordinator
import com.droiddeck.launcher.session.LaunchTicket
import com.droiddeck.launcher.core.CpuCores
import com.droiddeck.launcher.core.DownloadSource
import com.droiddeck.launcher.core.PhantomProcessLimit
@@ -215,7 +217,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var soundtracksLoaded by mutableStateOf(false)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var navRequest by mutableStateOf<String?>(null)
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
private val launchCoordinator = LaunchCoordinator<Intent, com.droiddeck.launcher.frontend.GameRequest>()
private var preparingGames by mutableStateOf(emptySet<String>())
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
@@ -897,7 +899,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
}, "components-restore").start()
}
private var pendingGameLink: com.droiddeck.launcher.frontend.GameRequest? = null
private var gameLinkReading = false
private var gameLinkTried = false
private var gameSyncFolder by mutableStateOf<String?>(null)
@@ -951,7 +952,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key
request.data = null
gameLinkReading = false
pendingGameLink = null
syncDualPanel()
return
}
@@ -964,7 +964,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
steamGames = emptyList()
shortcutLibraryScanning = true
} else shortcutLibraryScanning = false
pendingGameLink = null
gameLinkReading = false
gameLinkTried = false
soundtrackLaunch = false
@@ -977,6 +976,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
return
}
if (GameLaunchIntent.accepts(request.action)) {
val ticket = launchCoordinator.beginLink(request)
gameLinkReading = true
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
val copy = Intent(request)
@@ -985,12 +985,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
ui.post {
if (intent === request && !isDestroyed) {
gameLinkReading = false
pendingGameLink = game
if (!launchCoordinator.resolve(ticket, game)) {
clearGameLinkIntent(request)
syncDualPanel()
return@post
}
if (game == null) {
launchCoordinator.consume(ticket)
syncDualPanel()
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
} else {
handleGameLink(steamGames, scanned = false)
handleGameLink(steamGames, scanned = false, ticket = ticket)
refresh()
}
}
@@ -999,37 +1004,66 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
}
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) {
val request = gameLaunchRequest.incrementAndGet()
private fun beginUiLaunch(): LaunchTicket {
val dropped = launchCoordinator.pendingLink()
val ticket = launchCoordinator.beginLaunch()
dropped?.let { if (intent === it.owner) clearGameLinkIntent(it.owner) }
return ticket
}
private fun clearGameLinkIntent(link: Intent) {
link.data = null
link.action = Intent.ACTION_MAIN
link.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
}
private fun launchGame(
game: Library.SteamGame,
returnHome: Boolean = false,
onHandled: () -> Unit = {},
onSettled: () -> Unit = {},
ticket: LaunchTicket? = null,
) {
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
if (pkgStage != null) {
ticket?.let(launchCoordinator::releaseHandling)
onHandled()
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return
}
val request = ticket ?: beginUiLaunch()
if (!launchCoordinator.isCurrent(request)) {
onHandled()
return
}
val files = game.gameFiles
if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) {
if (startGame(game, returnHome, onHandled)) onSettled()
if (startGame(game, returnHome, onHandled, request)) onSettled()
else launchCoordinator.releaseHandling(request)
return
}
Thread({
val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files)
ui.post {
when {
request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled()
!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed -> {
launchCoordinator.releaseHandling(request)
onHandled()
}
refused -> {
onHandled()
android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show()
onSettled()
}
startGame(game, returnHome, onHandled) -> onSettled()
startGame(game, returnHome, onHandled, request) -> onSettled()
else -> launchCoordinator.releaseHandling(request)
}
}
}, "xbox-app-model").start()
}
private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean {
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit, ticket: LaunchTicket): Boolean {
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled, ticket)
onHandled()
if (SessionState.running) {
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
@@ -1074,15 +1108,34 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
}
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit = {}): Boolean {
private fun launchWithoutSteam(
game: Library.SteamGame,
returnHome: Boolean,
onHandled: () -> Unit = {},
ticket: LaunchTicket? = null,
): Boolean {
if (pkgStage != null) {
onHandled()
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return false
}
val app = applicationContext
val request = ticket ?: beginUiLaunch()
if (!launchCoordinator.isCurrent(request)) {
onHandled()
return false
}
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)
ui.post {
onHandled()
if (isDestroyed) return@post
if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) {
launchCoordinator.releaseHandling(request)
return@post
}
if (command == null) {
launchCoordinator.releaseHandling(request)
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
return@post
}
@@ -1234,22 +1287,27 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
ui.postDelayed(poll, SESSION_SWITCH_POLL_MS)
}
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) {
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true, ticket: LaunchTicket? = null) {
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
val request = pendingGameLink ?: return
val link = launchCoordinator.pendingLink() ?: return
if (ticket != null && link.ticket !== ticket) return
val request = link.request ?: return
if (launchCoordinator.isHandling(link.ticket)) return
if (ticket == null && !link.ownedBy(intent)) {
// A refresh may only finish the link that belongs to the intent this activity shows.
launchCoordinator.consume(link.ticket)
return
}
val game = request.find(games, byTitle = scanned)
if (!scanned && game == null) return
gameLinkTried = true
ui.postDelayed({
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
}, LINK_PANEL_MS)
val link = intent
val linkIntent = link.owner
fun consume() {
if (intent !== link || pendingGameLink !== request) return
pendingGameLink = null
link.data = null
link.action = Intent.ACTION_MAIN
link.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
if (!launchCoordinator.consume(link.ticket)) return
if (intent === linkIntent) clearGameLinkIntent(linkIntent)
}
if (game == null) {
consume()
@@ -1257,7 +1315,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
android.widget.Toast.makeText(this,
if (request.program != null) R.string.game_link_program_unknown else R.string.game_link_missing,
android.widget.Toast.LENGTH_LONG).show()
} else launchGame(game, returnHome = true, onSettled = ::consume)
} else {
if (!launchCoordinator.beginHandling(link.ticket)) return
launchGame(game, returnHome = true, onSettled = ::consume, ticket = link.ticket)
}
}
private fun chooseGameShortcut(game: Library.SteamGame) {
@@ -1448,16 +1509,20 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
},
onStoreGame = { store, id ->
val key = "${store.id}:$id"
if (key !in preparingGames) {
if (pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
} else if (key !in preparingGames) {
preparingGames = preparingGames + key
val ticket = beginUiLaunch()
val app = applicationContext
Thread({
val g = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull()
runOnUiThread {
if (g != null && !isFinishing && !isDestroyed) prepareAndLaunch(g, key)
else {
if (g != null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) {
prepareAndLaunch(g, key, ticket)
} else {
preparingGames = preparingGames - key
if (g == null && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
if (g == null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
}
}
}, "store-play").start()
@@ -1960,10 +2025,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
gameLaunchRequest.incrementAndGet()
supersedeUncommittedLaunch()
if (intent.action == SteamIntegration.ACTION_SETUP) {
gameLinkReading = false
pendingGameLink = null
syncDualPanel()
readIntegrationIntent(intent)
return
@@ -1973,6 +2037,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
startSteamAtStartupIfEnabled()
}
/** A replacement activity intent supersedes anything this activity has not dispatched yet. */
private fun supersedeUncommittedLaunch() {
launchCoordinator.cancelAll()
}
private var soundtrackLaunch = false
// A restarted launcher starts before the old one stops, so each clears the hooks only if they are still its own.
@@ -2101,6 +2170,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!triggerKeys.synthesizing && triggerKeys.nativeKey(event)) return true
val tabStep = com.droiddeck.launcher.ui.dualPageStep(event)
val tabs = com.droiddeck.launcher.ui.MainTabSteps.handler
if (tabStep == null && event.action == KeyEvent.ACTION_DOWN) com.droiddeck.launcher.ui.MainTabSteps.otherKeys++
if (tabStep != null && tabs != null) {
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) tabs(tabStep)
@@ -2251,13 +2321,22 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (Build.VERSION.SDK_INT >= 33) state.getParcelable(key, Intent::class.java)
else @Suppress("DEPRECATION") state.getParcelable(key)
private fun prepareAndLaunch(g: Library.SteamGame, key: String) {
val request = gameLaunchRequest.incrementAndGet()
private fun prepareAndLaunch(g: Library.SteamGame, key: String, ticket: LaunchTicket? = null) {
if (pkgStage != null) {
preparingGames = preparingGames - key
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return
}
val request = ticket ?: beginUiLaunch()
if (!launchCoordinator.isCurrent(request)) {
preparingGames = preparingGames - key
return
}
val done = { preparingGames = preparingGames - key }
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) {
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch }
if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) { done(); return@beforeLaunch }
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g, onHandled = done)
if (launchCoordinator.isCurrent(request) && !isFinishing && !isDestroyed) launchGame(g, onHandled = done, ticket = request)
else done()
}
}
@@ -2267,7 +2346,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
// The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too.
queuedLaunchRunner.destroy()
triggerKeys.cancel()
gameLaunchRequest.incrementAndGet()
launchCoordinator.cancelAll()
cancelCompatLaunch()
updates.unregister()
runCatching { unregisterReceiver(shortcutsInstallStatus) }
@@ -2346,7 +2425,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
}
private fun launchPending(): Boolean = gameLinkReading || (pendingGameLink != null && !gameLinkTried)
private fun launchPending(): Boolean = gameLinkReading || (launchCoordinator.hasPending() && !gameLinkTried)
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY)
@@ -156,7 +156,7 @@ internal class ProtonMenu(
fun refreshProtons() {
refreshExperimental()
protonRows = ProtonExtras.tools.map {
protonRows = ProtonExtras.offered(activity).map {
val all = ProtonExtras.installedAll(activity, it)
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
}
@@ -875,9 +875,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
cornerTap = SessionPrefs.drawerCornerTap(this)
applyOutputPacing()
if (!SessionState.running) {
SessionState.followScreen = followChoice()
SessionState.followScale = followScale()
SessionState.followScales = SessionPrefs.followScales(this, displayMode(),
com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
}
applyFollowChoice()
applyFollowOrientation(resources.configuration)
goFullscreen()
volumeControlStream = android.media.AudioManager.STREAM_MUSIC
@@ -2995,16 +2996,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
private fun followScale(): Float {
val mode = displayMode()
val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait())
return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f
}
private fun followChoice(): Boolean {
val mode = displayMode()
return com.droiddeck.launcher.session.SessionDisplay.isFollow(
SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait()))
private fun applyFollowChoice() {
val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first }
SessionState.followScreen = scale != null
SessionState.followScale = scale ?: 1f
}
private fun applyFollowOrientation(config: android.content.res.Configuration) {
@@ -3018,6 +3013,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
}
cancelTouchGestures()
applyFollowChoice()
applyFollowOrientation(newConfig)
applyNotchInset()
applyUnfoldedControls()
@@ -5162,10 +5158,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var sessionTouchDown = false
private var screenTapsClick = true
private fun onScreenMouseButtonShown(): Boolean = listOfNotNull(
private fun onScreenLeftMouseButtonShown(): Boolean = listOfNotNull(
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface,
secondScreenPresentation?.controlsView, swappedInputSurface,
).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
).any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) }
@@ -5201,7 +5197,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val snapshot = fingerTouchSnapshot(uiBlocking)
val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot)
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
screenTapsClick = !onScreenMouseButtonShown()
screenTapsClick = !onScreenLeftMouseButtonShown()
if (::touchpad.isInitialized) touchpad.clicks = screenTapsClick
if (::scrollTouch.isInitialized) scrollTouch.clicks = screenTapsClick
}
@@ -28,7 +28,9 @@ object DeviceSupport {
com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
}
fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists()
fun bridgeUsable(): Boolean = bridgeUsable(adreno(), SystemVulkanDriver.isAvailable())
internal fun bridgeUsable(adreno: Boolean, systemDriverReady: Boolean): Boolean = !adreno && !systemDriverReady
fun openDriverActive(context: Context): Boolean {
if (adreno()) return false
@@ -31,6 +31,7 @@ object AddedGames {
val exeUncertain: Boolean = false,
val launchOptions: String = "",
val single: Boolean = false,
val steamProgram: Boolean = true,
) {
fun folderName(): String = folder.name
}
@@ -336,7 +337,10 @@ object AddedGames {
val owner = ownerFolder(app, exe)
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let {
if (guestPath(app, exe) != null) AddedExes.put(app, AddedExes.Entry(owner.path, exe.path))
if (guestPath(app, it.exe) != null) {
SessionPrefs.setAddedGameExe(app, owner.path, it.exe.path)
AddedExes.put(app, AddedExes.Entry(owner.path, it.exe.path))
}
return AddResult.Existing(it)
}
}
@@ -442,9 +446,9 @@ object AddedGames {
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile }
val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return
val epicLauncher = sidecar?.takeIf { it.store == Store.EPIC && (chosen == null || canonical(chosen) == canonical(it.exeFile(folder))) }
val storeLauncher = sidecar?.takeIf { chosen == null || canonical(chosen) == canonical(it.exeFile(folder)) }
?.launcherFile(folder)?.takeIf { it.isFile }
val launch = epicLauncher ?: if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found
val launch = storeLauncher ?: found
val foundGuest = guestPath(context, launch)
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
@@ -470,7 +474,13 @@ object AddedGames {
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
?: sidecarDir
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
val steamId = config?.let { steamRoute(it, appId) }
if (adopted == null && SessionPrefs.addedGameAdopted(context, folder.path, "Exe") == null &&
guestPath(context, folder)?.let { steamEditedTo(it, record, guestExe) } == true) {
SessionPrefs.setAddedGameAdopted(context, folder.path, "Exe", exe.path)
}
val steamProgram = candidates.firstOrNull()?.let { canonical(it) == canonical(exe) } ?: true ||
SessionPrefs.addedGameAdopted(context, folder.path, "Exe")?.let { canonical(File(it)) == canonical(exe) } == true
val steamId = config?.takeIf { steamProgram }?.let { steamRoute(it, appId) }
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
@@ -480,7 +490,7 @@ object AddedGames {
sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context)
else -> ""
},
single = single != null))
single = single != null, steamProgram = steamProgram))
}
}
@@ -520,6 +530,11 @@ object AddedGames {
return file.takeIf { inside && it.isFile }
}
internal fun steamEditedTo(folderGuest: String, record: JSONObject?, guestExe: String): Boolean {
val steam = unquote(record?.optJSONObject("steam")?.optString("Exe"))
return steam == guestExe && steam != unquote(record?.optJSONObject("app")?.optString("Exe")) && steam.startsWith("$folderGuest/")
}
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) {
@@ -568,6 +583,7 @@ object AddedGames {
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions))
if (g.source != Library.ADDED) json.append(",\"store\":").append(quote(g.source))
if (!g.steamProgram) json.append(",\"route\":false")
val art = AddedGameArt.resolve(context, g)
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
@@ -13,6 +13,7 @@ object GamesFolderMigration {
@Synchronized
fun run(context: Context) {
repathInternalGuest(context)
val dirs = SessionPrefs.addedGamesDirs(context)
if (dirs.isEmpty()) return
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
@@ -58,12 +59,30 @@ object GamesFolderMigration {
SessionPrefs.setGamesFoldersMigrated(context)
}
private fun repathInternalGuest(context: Context) {
val binds = SessionPrefs.gameFolderBinds(context)
if (binds.none { it.second == StoreInstallRoot.INTERNAL_GUEST }) return
val hosts = binds.map { it.first }
val roots = legacyRoots(hosts).associateBy { it.host.path }
val taken = binds.map { it.second }.filter { it != StoreInstallRoot.INTERNAL_GUEST }.toMutableSet()
SessionPrefs.setGameFolderBinds(context, binds.map { (host, guest) ->
if (guest != StoreInstallRoot.INTERNAL_GUEST) return@map host to guest
val base = roots.getValue(host).guest
var next = base
var n = 2
while (next in taken) next = "$base-${n++}"
taken.add(next)
host to next
})
}
internal fun legacyRoots(paths: List<String>): List<AddedGames.Root> {
val hosts = paths.distinct().map { File(it) }
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
return hosts.map { host ->
val name = host.name.ifEmpty { "games" }
val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
val clash = (names[name.lowercase()] ?: 0) > 1 || "${AddedGames.GUEST_DIR}/$name" == StoreInstallRoot.INTERNAL_GUEST
val guestName = if (clash) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
AddedGames.Root(host, "${AddedGames.GUEST_DIR}/$guestName")
}
}
@@ -308,8 +308,7 @@ public final class TurnipDriver {
}
}
if (chosen != null && !chosen.isEmpty()) {
if (SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))
&& SessionPrefs.INSTANCE.gpuAutoInstalled(context).contains(chosen)
if (SessionPrefs.INSTANCE.displayDriverFromAuto(context)
&& gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) {
Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system");
return null;
@@ -0,0 +1,39 @@
package com.droiddeck.launcher.input
internal class AxisPacing(private val intervalMs: Long) {
private var lastWriteAt = 0L
private var written = false
private var heldUntil = NOT_HELD
fun dueAt(now: Long, axesOnly: Boolean): Long =
if (axesOnly && written && now - lastWriteAt < intervalMs) lastWriteAt + intervalMs else now
fun wrote(at: Long) {
lastWriteAt = at
written = true
}
fun hold(due: Long): Boolean {
if (heldUntil != NOT_HELD) return false
heldUntil = due
return true
}
fun release(now: Long): Boolean {
if (heldUntil == NOT_HELD || now < heldUntil) return false
heldUntil = NOT_HELD
return true
}
fun cancel(): Boolean {
if (heldUntil == NOT_HELD) return false
heldUntil = NOT_HELD
return true
}
companion object {
private const val NOT_HELD = Long.MIN_VALUE
@JvmStatic fun keepsMoving(before: Int, after: Int): Boolean = before == after || (before != 0 && after != 0)
}
}
@@ -1,5 +1,9 @@
package com.droiddeck.launcher.input;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import android.os.SystemClock;
import android.util.Log;
import java.io.File;
@@ -128,6 +132,16 @@ public class FakeInputWriter {
private static final Object RING_LOCK = new Object();
private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS];
private static final long AXIS_REPORT_INTERVAL_MS = 4;
private static final class Pacing {
static final Handler HANDLER;
static {
HandlerThread thread = new HandlerThread("pad-pacing", Process.THREAD_PRIORITY_DISPLAY);
thread.start();
HANDLER = new Handler(thread.getLooper());
}
}
static {
System.loadLibrary("sdnative");
@@ -156,6 +170,9 @@ public class FakeInputWriter {
private boolean hasChanges = false;
private boolean pendingFullResend = false;
private boolean forceResend = false;
private final AxisPacing axisPacing = new AxisPacing(AXIS_REPORT_INTERVAL_MS);
private final PadState pacedPad = new PadState();
private final Runnable pacedWrite = this::writePacedPad;
public FakeInputWriter(String fakeInputPath, int slot) {
this.slot = slot;
@@ -711,10 +728,12 @@ public class FakeInputWriter {
}
public synchronized void close() {
cancelPacedWrite();
isOpen = false;
}
public synchronized void reset() {
cancelPacedWrite();
if (!isOpen && !open())
return;
@@ -822,6 +841,53 @@ public class FakeInputWriter {
}
public synchronized void writePad(PadState state) {
long now = SystemClock.uptimeMillis();
long due = axisPacing.dueAt(now, !pendingFullResend && onlyAxesMove(state));
if (due > now) {
pacedPad.copyFrom(state);
if (axisPacing.hold(due))
Pacing.HANDLER.postAtTime(pacedWrite, due);
return;
}
cancelPacedWrite();
writePadNow(state);
}
private synchronized void writePacedPad() {
if (axisPacing.release(SystemClock.uptimeMillis()))
writePadNow(pacedPad);
}
private void cancelPacedWrite() {
if (axisPacing.cancel())
Pacing.HANDLER.removeCallbacks(pacedWrite);
}
private boolean onlyAxesMove(PadState state) {
for (int i = 0; i < 10; i++) {
if (prevButtonStates[i] != state.isDown(i))
return false;
}
return prevButtonStates[SNAPSHOT_IDX_MODE] == state.isDown(PadState.GUIDE)
&& prevQam == state.isDown(PadState.QAM)
&& prevHatX == state.hatX() && prevHatY == state.hatY()
&& AxisPacing.keepsMoving(prevThumbLX, stickValue(state.leftX))
&& AxisPacing.keepsMoving(prevThumbLY, stickValue(state.leftY))
&& AxisPacing.keepsMoving(prevThumbRX, stickValue(state.rightX))
&& AxisPacing.keepsMoving(prevThumbRY, stickValue(state.rightY))
&& AxisPacing.keepsMoving(prevTriggerL, triggerValue(state.leftTrigger))
&& AxisPacing.keepsMoving(prevTriggerR, triggerValue(state.rightTrigger));
}
private static int stickValue(float value) {
return (int) (value * 32767);
}
private static int triggerValue(float value) {
return (int) (value * 255);
}
private void writePadNow(PadState state) {
if (!isOpen && !open())
return;
@@ -845,10 +911,10 @@ public class FakeInputWriter {
hasChanges = true;
}
int lx = (int) (state.leftX * 32767);
int ly = (int) (state.leftY * 32767);
int rx = (int) (state.rightX * 32767);
int ry = (int) (state.rightY * 32767);
int lx = stickValue(state.leftX);
int ly = stickValue(state.leftY);
int rx = stickValue(state.rightX);
int ry = stickValue(state.rightY);
if (forceResend || lx != prevThumbLX) {
prevThumbLX = lx;
@@ -867,8 +933,8 @@ public class FakeInputWriter {
writeEvent(EV_ABS, ABS_RY, ry);
}
int tl = (int) (state.leftTrigger * 255);
int tr = (int) (state.rightTrigger * 255);
int tl = triggerValue(state.leftTrigger);
int tr = triggerValue(state.rightTrigger);
if (forceResend || tl != prevTriggerL) {
prevTriggerL = tl;
writeEvent(EV_ABS, ABS_BRAKE, tl);
@@ -895,6 +961,8 @@ public class FakeInputWriter {
if (!flushBuffer()) {
Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable");
pendingFullResend = true;
} else {
axisPacing.wrote(SystemClock.uptimeMillis());
}
}
forceResend = false;
@@ -53,14 +53,14 @@ data class InputProfile(
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
fun showsMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
fun showsLeftMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
val action = elementAction(role, element.id, element.control).takeIf {
elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control)
}
val click = elementClickAction(role, element).takeIf {
clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element)
}
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.validFor(element.control) }
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.code == PointerGestures.BTN_LEFT }
}
companion object {
@@ -436,6 +436,7 @@ object BwrapSpawner {
"DDNATV_ROOT" to sandbox,
"DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(),
"DDNATV_LINK_ROOT" to rootfs.path,
"DDNATV_REAL_EXE" to program.path,
"DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" },
"DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context),
"LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path },
@@ -73,9 +73,10 @@ object NativeGuest {
fun libraryPath(root: File): String = LIB_DIRS.joinToString(":") { File(root, it).path }
/** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
fun environment(root: File, program: String, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
"DDNATV_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(),
"DDNATV_REAL_EXE" to hostProgram(root, program).path,
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
).filterValues { it.isNotEmpty() }
@@ -85,17 +86,20 @@ object NativeGuest {
*/
fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> {
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
val host = File(root, program.removePrefix("/"))
val host = hostProgram(root, program)
val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
}
private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/"))
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
fun sessionEnvironment(root: File, binds: List<String>, hostname: String? = null): Map<String, String> {
fun sessionEnvironment(root: File, binds: List<String>, program: String, hostname: String? = null): Map<String, String> {
val preload = preloadList(root)
return linkedMapOf(
"DDNATV_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(),
"DDNATV_REAL_EXE" to hostProgram(root, program).path,
"DDNATV_HOSTNAME" to hostname.orEmpty(),
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
"DDNATV_PRELOAD" to preload.joinToString(":"),
@@ -114,7 +118,7 @@ object NativeGuest {
.also { builder ->
builder.environment().apply {
remove("LD_AUDIT")
putAll(sessionEnvironment(root, binds, SessionPrefs.guestHostname(context)))
putAll(sessionEnvironment(root, binds, guest.first(), SessionPrefs.guestHostname(context)))
}
}
@@ -278,7 +282,7 @@ object NativeGuest {
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
builder.environment().apply {
clear()
putAll(environment(root, preload))
putAll(environment(root, program, preload))
putAll(env)
}
return builder
@@ -328,7 +328,7 @@ object BottomDesktop {
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
}
val environment = if (current.nativeUserland) {
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, SessionPrefs.guestHostname(context))
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
.map { (k, v) -> "$k=$v" }.toTypedArray()
} else current.hostEnvironment
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
@@ -88,8 +88,8 @@ object ComponentUpdater {
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
if (!ComponentUpdates.follows(p) || !ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.line("fex", false)
if (!ComponentUpdates.autoFollows(p, comp) || !ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.fexLine(p)
val key = "${p.id}|${p.version}"
val flavors = state.obj("flavors").obj(key)
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
@@ -13,7 +13,7 @@ object ComponentUpdates {
const val BOOTED_SECONDS = 60L
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
data class Line(val key: String, val comp: String, val prefix: String)
data class Line(val key: String, val comp: String, val prefix: String, val release: String = ComponentsManager.DD_NIGHTLY)
val LINES = listOf(
Line("dxvk", "dxvk", "DD-dxvk-"),
@@ -21,12 +21,19 @@ object ComponentUpdates {
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
Line("fex", "fex", "DD-FEXCore-"),
Line("fex-bionic", "fex", "FEXCore-", ComponentsManager.DD_BIONIC),
)
private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix
fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX)
fun autoFollows(p: ComponentsManager.Proton, comp: String): Boolean =
follows(p) || (comp == "fex" && !p.valve && ComponentsManager.bionicTool(p.dir.name))
fun fexLine(p: ComponentsManager.Proton): Line =
if (ComponentsManager.bionicTool(p.dir.name)) LINES.first { it.release == ComponentsManager.DD_BIONIC } else line("fex", false)
fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
fun strays(
@@ -34,8 +41,8 @@ object ComponentUpdates {
choices: Map<String, Map<String, ComponentsManager.Choice>>,
placed: Set<String>,
): List<Pair<ComponentsManager.Proton, String>> =
protons.filterNot(::follows).flatMap { p ->
choices[p.id].orEmpty().filter { (_, c) -> !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
protons.flatMap { p ->
choices[p.id].orEmpty().filter { (comp, c) -> !autoFollows(p, comp) && !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
}
fun unseen(
@@ -53,13 +60,14 @@ object ComponentUpdates {
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) }
return items.filter { it.release == line.release && it.comp == line.comp && belongs(it.file, line) }
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
}
fun belongs(file: String, line: Line): Boolean =
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true &&
(line.comp != "fex" || ComponentsManager.bionicFex(file) == (line.release == ComponentsManager.DD_BIONIC))
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
@@ -161,7 +169,7 @@ object ComponentUpdates {
fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> {
val ranked = line?.takeIf { belongs(current, it) }
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
return (owned + stored.filter { ranked != null && belongs(it, ranked) })
return (owned + stored.filter { ranked != null && ranked.release == ComponentsManager.DD_NIGHTLY && belongs(it, ranked) })
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
}
}
@@ -29,6 +29,7 @@ object ComponentsManager {
private const val NIGHTLIES = "The412Banner/Nightlies"
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
internal const val DD_NIGHTLY = "linux-nightly"
internal const val DD_BIONIC = "bionic-stable"
private val RELEASES = linkedMapOf(
"FexCore-Linux" to "fex",
"Dxvk-Linux" to "dxvk",
@@ -37,9 +38,9 @@ object ComponentsManager {
"Vkd3d-proton-Linux" to "vkd3d",
)
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
@@ -201,8 +202,34 @@ object ComponentsManager {
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
}
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) {
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
if (comp == "fex" && file != null) fetchFexTwin(context, safeName(file))
}
// Twin downloads in flight: one worker per name, so two profile changes cannot share one partial download.
private val twinDownloads = HashSet<String>()
private fun fetchFexTwin(context: Context, file: String) {
val twin = fexTwin(file) ?: return
if (protons(context).all { fexFits(it.dir.name, file) }) return
synchronized(lock) { if (isStored(context, twin) || !twinDownloads.add(twin)) return }
val app = context.applicationContext
Thread({
try {
runCatching {
val item = catalogItem(app, twin, if (bionicFex(twin)) DD_BIONIC else "FexCore-Linux")
if (item == null) Log.i(TAG, "$twin is not listed")
else {
download(app, item) {}
republish(app)
}
}.onFailure { Log.w(TAG, "download $twin", it) }
} finally {
synchronized(lock) { twinDownloads.remove(twin) }
}
}, "fex-twin").start()
}
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
@@ -413,7 +440,7 @@ object ComponentsManager {
}
}
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
if (comp == "fex") FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
if (comp == "fex" && !bionicTool(dir.name)) FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
COMP_DIR[comp]?.let { compDir ->
for (arch in PE_ARCHES) {
val target = File(dir, "$compDir/$arch")
@@ -603,7 +630,9 @@ object ComponentsManager {
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
.filter { owned(comp, it) }.associateWith { File(base, it) }
}
for (rel in managed(comp) - files.keys) {
// A bionic tool never loses a FEX file: its launch.sh would put the whole bundled FEX back.
val removed = if (comp == "fex" && bionicTool(p.dir.name)) emptySet() else managed(comp) - files.keys
for (rel in removed) {
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
.append('\t').append(rel).append("\t-\t-\n")
}
@@ -620,7 +649,8 @@ object ComponentsManager {
val version = safeName(file.removePrefix("original "))
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
} else {
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
val fit = (if (comp == "fex") launchFex(p.dir.name, file) { File(packagesDir(context), it).isFile } else file) ?: return null
safeName(fit.removeSuffix(".wcp")) to File(packagesDir(context), fit)
}.takeIf { it.second.isFile }
}
@@ -651,12 +681,14 @@ object ComponentsManager {
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS) {
val file = profile.optString(comp)
if (file.isEmpty()) continue
val wcp = File(packagesDir(context), file)
if (!wcp.isFile) continue
val key = safeName(file.removeSuffix(".wcp"))
for (p in all) append(scope, p, comp, key, wcp)
val chosen = profile.optString(comp)
if (chosen.isEmpty()) continue
for (p in all) {
val file = (if (comp == "fex") launchFex(p.dir.name, chosen) { File(packagesDir(context), it).isFile } else chosen) ?: continue
val wcp = File(packagesDir(context), file)
if (!wcp.isFile) continue
append(scope, p, comp, safeName(file.removeSuffix(".wcp")), wcp)
}
}
}
return PreparedLaunchState(lines.toString(), keep)
@@ -677,6 +709,7 @@ object ComponentsManager {
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp)
requireSelectable(context, info.comp)
requireFits(p, info)
val state = loadState(context)
if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
@@ -690,7 +723,11 @@ object ComponentsManager {
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
}
private fun requireFits(p: Proton, info: Package) =
check(info.comp != "fex" || fexFits(p.dir.name, info.file)) { "${info.file} is not a FEX build for ${p.name}" }
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
requireFits(p, info)
ensureOriginal(context, p, info.comp, state)
val hashes = installFiles(context, p.dir, info.comp, wcp)
state.sub("active").sub(p.id).put(info.comp, JSONObject()
@@ -803,6 +840,18 @@ object ComponentsManager {
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
installs?.any { liveSelection(key, entry, it) } == true
// An installed tool that launches with `name` as the stored twin of a game's FEX choice (a Linux choice on
// DroidDeck-Bionic, a -bionic one on another Proton): deleting the twin would drop that choice for that tool.
internal fun twinUser(state: JSONObject, installed: List<Proton>, name: String): Proton? {
val profiles = state.optJSONObject("profiles") ?: return null
for (scope in profiles.keys()) {
val chosen = profiles.optJSONObject(scope)?.optString("fex")?.takeIf { it.isNotEmpty() } ?: continue
if (fexTwin(chosen) != name) continue
installed.firstOrNull { !fexFits(it.dir.name, chosen) }?.let { return it }
}
return null
}
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
val byId = installed.groupBy { it.id }
val names = HashSet<String>()
@@ -819,7 +868,11 @@ object ComponentsManager {
val profiles = state.optJSONObject("profiles")
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
val profile = profiles?.optJSONObject(scope) ?: continue
COMPONENTS.forEach { comp -> profile.optString(comp).takeIf { it.isNotEmpty() }?.let(names::add) }
COMPONENTS.forEach { comp ->
val file = profile.optString(comp).takeIf { it.isNotEmpty() } ?: return@forEach
names.add(file)
if (comp == "fex" && installed.any { !fexFits(it.dir.name, file) }) fexTwin(file)?.let(names::add)
}
}
return names
}
@@ -890,6 +943,7 @@ object ComponentsManager {
val queued = state.sub("queued").sub(target.id)
var changed = false
wanted.forEach { (comp, entry) ->
if (comp == "fex" && !fexFits(target.dir.name, entry.optString("file"))) return@forEach
if (active?.has(comp) != true && !queued.has(comp)) {
queued.put(comp, entry)
changed = true
@@ -970,6 +1024,8 @@ object ComponentsManager {
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val twinTool = twinUser(state, protons(context), name)
check(twinTool == null) { context.getString(R.string.cmgr_package_in_use, name, twinTool?.name ?: "") }
val installed = protons(context).groupBy { it.id }
var changed = false
for (key in listOf("queued", "active")) {
@@ -1066,8 +1122,11 @@ object ComponentsManager {
return Catalog(items, o.optLong("fetchedAt"))
}
internal fun assetComp(release: String, name: String): String? =
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
DD_BIONIC -> "fex"
else -> null
}
internal val CATALOG_ORDER: Comparator<CatalogItem> =
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
@@ -1155,6 +1214,25 @@ object ComponentsManager {
return runCatching { readWcpEntry(original, rel) }.getOrNull()
}
// DroidDeck-Bionic loads only Android builds of FEX's unix libraries; other Protons only glibc builds.
internal fun bionicTool(dirName: String?): Boolean = dirName?.startsWith("DroidDeck-Bionic") == true
internal fun bionicFex(file: String): Boolean = file.endsWith("-bionic.wcp", ignoreCase = true)
internal fun fexFits(toolDir: String?, file: String): Boolean = bionicTool(toolDir) == bionicFex(file)
internal fun fexTwin(file: String): String? = when {
file.endsWith("-linux.wcp", ignoreCase = true) -> file.dropLast("-linux.wcp".length) + "-bionic.wcp"
file.endsWith("-bionic.wcp", ignoreCase = true) -> file.dropLast("-bionic.wcp".length) + "-linux.wcp"
else -> null
}
internal fun launchFex(toolDir: String, file: String, stored: (String) -> Boolean): String? =
if (fexFits(toolDir, file)) file else fexTwin(file)?.takeIf(stored)
internal fun <T> forTool(comp: String, toolDir: String?, items: List<T>, selected: String? = null, file: (T) -> String): List<T> =
if (comp != "fex") items else items.filter { file(it) == selected || fexFits(toolDir, file(it)) }
fun supports(p: Proton, comp: String): Boolean =
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
@@ -0,0 +1,52 @@
package com.droiddeck.launcher.session
import android.util.Log
import com.droiddeck.launcher.stores.StoreInstalls
import java.io.File
object CpuCacheSysfs {
private const val TAG = "SessionService"
private val FEX_CPUID_SIZE_KB = mapOf(1 to 32, 2 to 512, 3 to 8192)
private val PROCESS = java.util.UUID.randomUUID().toString()
private val STARTS = java.util.concurrent.atomic.AtomicInteger()
fun binds(root: File, start: Int = STARTS.incrementAndGet(), host: File = File("/sys/devices/system/cpu"), process: String = PROCESS): List<String> = try {
root.listFiles()?.forEach { old -> if (old.name != process) StoreInstalls.deleteTree(old) }
val dir = File(root, "$process/$start")
StoreInstalls.deleteTree(dir)
val cpus = host.list { _, name -> name.matches(Regex("cpu\\d+")) }?.sorted().orEmpty()
val binds = cpus.mapNotNull { cpu ->
val staged = try {
stage(File(host, "$cpu/cache"), File(dir, cpu))
} catch (e: Exception) {
Log.w(TAG, "cpu cache: could not stage $cpu: $e")
false
}
if (staged) File(dir, cpu).path + ":" + File(host, "$cpu/cache").path else null
}
Log.i(TAG, "cpu cache: ${binds.size} of ${cpus.size} cores report the sizes the x86 CPUID reports")
binds
} catch (e: Exception) {
Log.w(TAG, "cpu cache: could not stage the core caches: $e")
emptyList()
}
private fun stage(cache: File, out: File): Boolean {
val indexes = cache.listFiles { f -> f.isDirectory && f.name.matches(Regex("index\\d+")) } ?: return false
var staged = false
for (index in indexes) {
val target = File(out, index.name).apply { mkdirs() }
val kb = runCatching { File(index, "level").readText().trim().toInt() }.getOrNull()?.let { FEX_CPUID_SIZE_KB[it] }
val files = index.listFiles { f -> f.isFile } ?: throw java.io.IOException("cannot list $index")
for (f in files) {
if (kb != null && f.name == "size") continue
File(target, f.name).writeText(f.readText())
}
if (kb == null) continue
File(target, "size").writeText("${kb}K\n")
staged = true
}
return staged
}
}
@@ -935,9 +935,9 @@ internal object EnhancedSessionLogShare {
private fun category(entry: String): Category {
val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
return Category.SESSION
}
@@ -948,8 +948,9 @@ internal object EnhancedSessionLogShare {
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "droiddeck-bionic.log",
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
"rpcs3", "RPCS3.log",
)
private val KNOWN_COMPONENT_PATTERNS = listOf(
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
@@ -74,10 +74,16 @@ object ExperimentalProtons {
return PREFIX + base + (tag?.let { "-$it" } ?: "")
}
/** DroidDeck-Bionic test builds are prereleases of the same repository and have their own row in the Proton list. */
internal fun listed(assets: List<ProtonExtras.Asset>): List<ProtonExtras.Asset> {
val bionic = ProtonExtras.tools.first { it.id == ProtonExtras.BIONIC }
return assets.filterNot { bionic.assetPattern.containsMatchIn(it.name) }
}
fun refresh(context: Context): List<Release>? {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true)
val assets = listed(ProtonExtras.assets(tool, fetched.releases, prerelease = true))
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
if (!SessionState.running) {
reconcile(context, fetched)
@@ -0,0 +1,82 @@
package com.droiddeck.launcher.session
/**
* Orders launch attempts and at most one pending game link.
*
* This is main-thread state: call it from the UI thread. A ticket is an identity,
* not a counter comparison, so a stale callback can only act on its own request.
*/
internal class LaunchTicket internal constructor(val serial: Long)
internal class LaunchCoordinator<O : Any, R : Any> {
internal class Link<O : Any, R : Any> internal constructor(
val ticket: LaunchTicket,
val owner: O,
val request: R?,
) {
/** Only the activity intent that delivered this link may finish it by a refresh. */
fun ownedBy(owner: O?): Boolean = this.owner === owner
}
private var next = 0L
private var current: LaunchTicket? = null
private var pending: Link<O, R>? = null
private var handling: LaunchTicket? = null
/** A launch that is allowed to proceed; it supersedes any pending link. */
fun beginLaunch(): LaunchTicket {
val ticket = LaunchTicket(++next)
current = ticket
pending = null
handling = null
return ticket
}
/** A game-link intent; it supersedes any earlier launch or link. */
fun beginLink(owner: O): LaunchTicket {
val ticket = LaunchTicket(++next)
current = ticket
pending = Link(ticket, owner, null)
handling = null
return ticket
}
/** The asynchronous link read returned; false means a newer request won. */
fun resolve(ticket: LaunchTicket, request: R?): Boolean {
val link = pending ?: return false
if (link.ticket !== ticket) return false
pending = Link(ticket, link.owner, request)
return true
}
fun beginHandling(ticket: LaunchTicket): Boolean {
val link = pending ?: return false
if (link.ticket !== ticket || link.request == null) return false
handling = ticket
return true
}
fun releaseHandling(ticket: LaunchTicket) {
if (handling === ticket) handling = null
}
fun isHandling(ticket: LaunchTicket): Boolean = handling === ticket
fun isCurrent(ticket: LaunchTicket): Boolean = current === ticket
fun hasPending(): Boolean = pending != null
fun pendingLink(): Link<O, R>? = pending
fun consume(ticket: LaunchTicket): Boolean {
val link = pending ?: return false
if (link.ticket !== ticket) return false
pending = null
handling = null
return true
}
fun cancelAll() {
next++
current = null
pending = null
handling = null
}
}
@@ -14,7 +14,8 @@ object ProtonDefault {
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
data class Request(val seq: Long, val valve: Boolean, val dir: String)
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>,
val source: String? = null)
data class GameChoice(val valve: Boolean, val dir: String)
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
@@ -34,6 +35,7 @@ object ProtonDefault {
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
}?.takeIf { it.name.isNotEmpty() }
},
source = o.optString("source").ifEmpty { null },
)
}
@@ -99,7 +101,13 @@ object ProtonDefault {
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
val d = dir(context)
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
val body = JSONObject().put("seq", seq).put("valve", proton.valve).put("dir", proton.dir.name).toString(1) + "\n"
writeRequest(d, Request(seq, proton.valve, proton.dir.name))
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
private fun writeRequest(d: File, request: Request) {
val body = JSONObject().put("seq", request.seq).put("valve", request.valve).put("dir", request.dir).toString(1) + "\n"
val staged = File(d, "request.json.staged")
try {
d.mkdirs()
@@ -110,8 +118,45 @@ object ProtonDefault {
Log.w(TAG, "could not write the Proton request", e)
throw e
}
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
// The default that names a tool an update replaces moves to the new one, as the per-game picks do: otherwise the guest
// no longer finds it and falls back to DroidDeck-Proton.
internal fun movedDefault(state: State, request: Request?, from: Set<String>, to: String, now: Long): Request? {
val (valve, dir) = chosen(state, request) ?: return null
if (valve || dir !in from) return null
return Request(nextSeq(now, state, request), false, to)
}
@Synchronized
fun moveDefault(context: Context, from: Set<String>, to: String) {
val d = dir(context)
val moved = movedDefault(state(context), parseRequest(read(File(d, "request.json"))), from, to, System.currentTimeMillis()) ?: return
writeRequest(d, moved)
}
// DroidDeck-Bionic keeps one build. A default naming another one moves to the installed build: an app from before
// updates carried the default over left it, or the guest fell back to its own tool when that build was gone (the
// request the app last wrote still names it).
internal fun bionicDefault(state: State, request: Request?, prefix: String, newest: String, now: Long): Request? {
val current = chosen(state, request)
val stale = when {
current != null && !current.first && current.second.startsWith(prefix) -> current.second
state.source == "fallback" && request != null && !request.valve && request.dir.startsWith(prefix) -> request.dir
else -> return null
}
return if (stale == newest) null else Request(nextSeq(now, state, request), false, newest)
}
/** The default and the per-game picks that name a DroidDeck-Bionic build other than [newest] move to it. */
@Synchronized
fun keepBionicCurrent(context: Context, prefix: String, newest: String) {
val d = dir(context)
bionicDefault(state(context), parseRequest(read(File(d, "request.json"))), prefix, newest, System.currentTimeMillis())
?.let { writeRequest(d, it) }
val games = parseGames(read(File(d, GAMES)))
val stale = games.values.filterNotNull().filter { !it.valve && it.dir.startsWith(prefix) && it.dir != newest }.map { it.dir }.toSet()
if (stale.isNotEmpty()) movedGames(games, stale, newest)?.let { writeGames(d, it) }
}
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
@@ -8,6 +8,7 @@ import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.NativeGuest
import java.io.File
import java.util.Locale
import org.json.JSONArray
@@ -32,20 +33,27 @@ object ProtonExtras {
@Volatile
private var replacing = false
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex,
val prereleases: Boolean = false)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null, val releaseName: String = tag)
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
const val OWN = "droiddeck"
const val BIONIC = "bionic"
val tools = listOf(
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*aarch64\\.tar\\.(gz|xz)$")),
// Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases. No-proot only.
Tool(BIONIC, "DroidDeck-Bionic", "DroidDeck-Bionic", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Bionic-.*aarch64\\.tar\\.(gz|xz)$"), prereleases = true),
)
/** The sources offered on this device: DroidDeck-Bionic only with Run without proot on. */
fun offered(context: Context): List<Tool> = tools.filter { it.id != BIONIC || NativeGuest.enabled(context) }
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
@@ -120,10 +128,11 @@ object ProtonExtras {
private var lastAttempt = 0L
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
keepBionicCurrent(context)
synchronized(checkLock) {
val file = latestFile(context)
val cache = readJson(file)
val due = tools.filter { tool ->
val due = offered(context).filter { tool ->
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
force || (now - at) !in 0 until CHECK_EVERY_MS
}
@@ -173,15 +182,32 @@ object ProtonExtras {
fun remove(context: Context, tool: Tool, dir: String? = null) {
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name)
if (deleteTool(context, name)) ComponentsManager.forgetProton(context, name)
}
// A tool folder can hold links that point out of it (a prefix template's dosdevices/z: -> /), and
// File.deleteRecursively() follows links into directories: remove each link itself, never what it points to.
private fun deleteTool(context: Context, name: String): Boolean {
val dir = File(toolsDir(context), name)
FileUtils.delete(dir)
return !dir.exists() && !java.nio.file.Files.isSymbolicLink(dir.toPath())
}
fun removeOlder(context: Context, tool: Tool) {
installedAll(context, tool).dropLast(1).forEach {
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it)
if (deleteTool(context, it)) ComponentsManager.forgetProton(context, it)
}
}
// DroidDeck-Bionic: the default and the game picks name the installed build, also when they were left on one an
// older app deleted without moving them.
private fun keepBionicCurrent(context: Context) {
if (SessionState.running) return
val tool = tools.firstOrNull { it.id == BIONIC } ?: return
val newest = installedAll(context, tool).lastOrNull() ?: return
runCatching { ProtonDefault.keepBionicCurrent(context, tool.prefix, newest) }.onFailure { Log.w(TAG, "bionic default and picks", it) }
}
private fun replaceOlder(context: Context, tool: Tool) {
val all = installedAll(context, tool)
val newest = all.lastOrNull() ?: return
@@ -194,7 +220,9 @@ object ProtonExtras {
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
// DroidDeck-Bionic only: the guest finds no default for a deleted Bionic build and falls back to DroidDeck-Proton
if (tool.id == BIONIC && runCatching { ProtonDefault.moveDefault(context, setOf(old), newest) }.onFailure { Log.w(TAG, "default pick of $old", it) }.isFailure) continue
if (deleteTool(context, old)) ComponentsManager.forgetProton(context, old)
else Log.w(TAG, "could not remove $old")
}
} finally {
@@ -342,7 +370,7 @@ object ProtonExtras {
archive.delete()
unqueue(context, tool)
record(context, tool, placed, asset.tag)
if (tool.id == OWN) replaceOlder(context, tool)
if (tool.id == OWN || tool.id == BIONIC) replaceOlder(context, tool)
if (EsyncPacks.enabled(context)) {
onProgress(context.getString(R.string.esync_fetching), -1)
try {
@@ -427,7 +455,7 @@ object ProtonExtras {
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
val candidates = (0 until array.length()).asSequence()
.mapNotNull { array.optJSONObject(it) }
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
.filter { !it.optBoolean("draft", false) && (tool.prereleases || !it.optBoolean("prerelease", false)) }
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
}
@@ -75,6 +75,7 @@ object SessionArtifacts {
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
val record = Record(dir)
copySteamLogs(context, dir, record, steamArch)
copyRpcs3Log(context, dir, record)
VacDiagnostics.collect(context, dir)
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
SessionLogCapture.dumpMemoryPressure(File(dir, "memory-pressure.log"))
@@ -321,6 +322,9 @@ object SessionArtifacts {
runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" }
private const val LOG_MARKS = "steam-log-marks.txt"
private const val RPCS3_LOG_MARKS = "rpcs3-log-marks.txt"
private const val RPCS3_LOGS = "root/.cache/rpcs3"
private const val RPCS3_LOG = "RPCS3.log"
private const val MAX_STEAM_LOG = 8L * 1024 * 1024
private const val HEAD = 4096L
@@ -328,11 +332,19 @@ object SessionArtifacts {
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
fun markSteamLogs(dir: File, logs: File) {
val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
logs.listFiles { f -> f.isFile }?.let { markLogs(dir, LOG_MARKS, it.toList()) }
}
fun markRpcs3Log(dir: File, root: File) {
markLogs(dir, RPCS3_LOG_MARKS, listOf(File(root, "$RPCS3_LOGS/$RPCS3_LOG")).filter { it.isFile })
}
private fun markLogs(dir: File, marks: String, files: List<File>) {
val lines = files.mapNotNull { f ->
val size = f.length()
head(f, size)?.let { "$size\t$it\t${f.name}" }
} ?: return
runCatching { File(dir, LOG_MARKS).writeText(lines.joinToString("") { "$it\n" }) }
}
runCatching { File(dir, marks).writeText(lines.joinToString("") { "$it\n" }) }
}
private fun head(f: File, length: Long): String? = runCatching {
@@ -348,8 +360,8 @@ object SessionArtifacts {
java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) }
}.getOrNull()
private fun steamLogMarks(dir: File): List<Mark>? = runCatching {
File(dir, LOG_MARKS).readLines().mapNotNull { line ->
private fun logMarks(dir: File, marks: String): List<Mark>? = runCatching {
File(dir, marks).readLines().mapNotNull { line ->
val parts = line.split('\t', limit = 3)
parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } }
}
@@ -371,11 +383,32 @@ object SessionArtifacts {
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
if (!logs.isDirectory) return
val out = File(dir, "steam").apply { mkdirs() }
val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }
addCopied(record, copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running })
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
}
private fun copyRpcs3Log(context: Context, dir: File, record: Record, stopWhenSessionStarts: Boolean = false) {
val out = File(dir, "rpcs3")
val logs = File(LinuxRuntime.rootDir(context), RPCS3_LOGS)
val copied = copyRpcs3LogResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running } ?: return
addCopied(record, copied)
if (copied.files.isNotEmpty()) Log.i(TAG, "collected RPCS3's log, scrubbed, into $out")
}
internal fun copyRpcs3Log(logs: File, dir: File, out: File): List<File> = copyRpcs3LogResult(logs, dir, out) { false }?.files.orEmpty()
private fun copyRpcs3LogResult(logs: File, dir: File, out: File, shouldStop: () -> Boolean): CopyResult? {
if (!File(dir, RPCS3_LOG_MARKS).isFile || !File(logs, RPCS3_LOG).isFile) return null
out.mkdirs()
val result = copySessionLogsResult(logs, dir, out, marksName = RPCS3_LOG_MARKS, accept = { it.name == RPCS3_LOG }, shouldStop = shouldStop)
if (result.files.isEmpty()) out.delete()
return result
}
private fun addCopied(record: Record, result: CopyResult) {
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
record.failed = record.failed || result.failed
record.deferred = record.deferred || result.deferred
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
}
internal fun copySessionLogs(
@@ -383,20 +416,22 @@ object SessionArtifacts {
dir: File,
out: File,
openWriter: (File) -> Writer = { it.bufferedWriter() },
): List<File> = copySessionLogsResult(logs, dir, out, openWriter) { false }.files
): List<File> = copySessionLogsResult(logs, dir, out, openWriter = openWriter) { false }.files
private fun copySessionLogsResult(
logs: File,
dir: File,
out: File,
marksName: String = LOG_MARKS,
accept: (File) -> Boolean = { true },
openWriter: (File) -> Writer = { it.bufferedWriter() },
shouldStop: () -> Boolean,
): CopyResult {
val marks = steamLogMarks(dir)
val marks = logMarks(dir, marksName)
val copied = ArrayList<File>()
var failed = false
var deferred = false
val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false)
val sources = logs.listFiles { f -> f.isFile && accept(f) } ?: return CopyResult(copied, true, false)
for (src in sources) {
if (shouldStop()) {
failed = true
@@ -567,6 +602,7 @@ object SessionArtifacts {
steamArch = recordedClient(dir),
stopWhenSessionStarts = stopWhenSessionStarts,
)
copyRpcs3Log(context, dir, record, stopWhenSessionStarts)
if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) {
if (!record.failed && VacDiagnostics.collect(context, dir)) {
try {
@@ -154,6 +154,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
"usr/local/bin/droiddeck-snap-run" to "usr/local/bin/droiddeck-snap-run",
"usr/local/bin/droiddeck-snap-confine" to "usr/local/bin/droiddeck-snap-confine",
"usr/local/bin/droiddeck-diversion-stub" to "usr/local/bin/droiddeck-diversion-stub",
"usr/local/bin/droiddeck-snapctl" to "usr/local/bin/droiddeck-snapctl",
"usr/local/bin/droiddeck-systemd-run" to "usr/local/bin/systemd-run",
"usr/local/bin/droiddeck-snap-cli" to "usr/local/bin/snap",
@@ -263,7 +264,9 @@ object SessionFiles {
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
"usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke",
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck/dwarfsextract" to "usr/local/lib/droiddeck/dwarfsextract",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/LICENSE",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
@@ -814,6 +814,11 @@ object SessionPrefs {
prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply()
}
fun displayDriverFromAuto(context: Context): Boolean {
val id = androidDriver(context)
return id.isEmpty() || (gpuDriverMode(context) == GPU_DRIVERS_AUTO && id in gpuAutoInstalled(context))
}
fun picturePosition(context: Context): String =
prefs(context).getString("picturePosition", "center")
@@ -1343,6 +1348,10 @@ object SessionPrefs {
SessionDisplay.effectiveChoice(
resolutionStored(context, mode, panel, false), resolutionStored(context, mode, panel, true), portrait)
fun followScales(context: Context, mode: String, panel: Pair<Int, Int>): Pair<Float?, Float?> =
SessionDisplay.followScale(resolutionChoice(context, mode, panel, false)) to
SessionDisplay.followScale(resolutionChoice(context, mode, panel, true))
fun resolutionStored(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean): String {
if (!portrait) return landscapeResolutionStored(context, mode, panel)
val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE
@@ -1553,7 +1562,7 @@ object SessionPrefs {
fun adoptAddedGameExe(context: Context, folderPath: String, expected: String, path: String, seen: Int): Boolean =
synchronized(addedGameLock) {
val unchanged = addedGameExe(context, folderPath) == expected
if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply()
if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putString("addedAdopted:Exe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply()
unchanged
}
@@ -784,7 +784,7 @@ class SessionService : Service() {
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, SessionPrefs.guestHostname(this))
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this))
.forEach { (k, v) -> env[k] = v }
} else prootEnv
@@ -1033,6 +1033,9 @@ class SessionService : Service() {
)
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
// DroidDeck-Bionic games load an Android driver build; this is the one the display uses, for a runtime driver
// that has none.
guest.add("DROIDDECK_DISPLAY_DRIVER=" + com.droiddeck.launcher.gpu.TurnipDriver(this).effectiveId())
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
guest.add("XWAYLAND_NO_GLAMOR=1")
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
@@ -1070,6 +1073,7 @@ class SessionService : Service() {
guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this)))
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
if (SessionState.mode == MODE_STEAM) guest.add("DD_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
SessionPaths.current()?.let { SessionArtifacts.markRpcs3Log(it, LinuxRuntime.rootDir(this)) }
SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null
SessionState.steamClientArch?.let { arch ->
guest.add("DD_STEAM_CLIENT_ARCH=$arch")
@@ -1263,6 +1267,7 @@ class SessionService : Service() {
components.add(hwmon)
binds.add(hwmon.dir.path + ":/sys/class/hwmon")
}
binds.addAll(CpuCacheSysfs.binds(File(filesDir, "session/sys/cpu-cache")))
val cpuStat = CpuStatComponent(File(filesDir, "session/proc-stat"))
if (cpuStat.prepare()) {
cpuStat.attach(this)
@@ -148,6 +148,9 @@ object SessionState {
@Volatile
var outputSize: Pair<Int, Int> = Pair(1920, 1080)
@Volatile
var followScales: Pair<Float?, Float?> = null to null
@Volatile
var followScreen = false
var followScale = 1f
@@ -3,8 +3,10 @@ package com.droiddeck.launcher.stores
import android.content.Context
import android.os.StatFs
import android.os.storage.StorageManager
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SecondaryLibrary
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.util.zip.CRC32
@@ -12,6 +14,7 @@ import java.util.zip.CRC32
object StoreInstallRoot {
const val SPACE_UNKNOWN = -1L
private const val INTERNAL = "root/Games/Stores"
const val INTERNAL_GUEST = "/$INTERNAL"
private const val ON_VOLUME = "Games"
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
@@ -179,6 +182,24 @@ object StoreInstallRoot {
fun externalBindSpecsForXodus(context: Context): List<String> =
externalBindSpecs(externalRootsForXodus(context), LinuxRuntime.rootDir(context))
fun guestBinds(context: Context): List<String> {
val out = ArrayList<String>(externalBindSpecs(context))
val root = LinuxRuntime.rootDir(context)
GameStorage.effective(context)?.takeIf { File(it.path).isDirectory }?.let { library ->
val content = SecondaryLibrary.contentPath(File(library.path)).path
for (guest in SecondaryLibrary.CARD_GUESTS) {
File(root, guest.removePrefix("/")).mkdirs()
out += "$content:$guest"
}
}
for (folder in AddedGames.roots(context)) {
if (!folder.host.isDirectory || !folder.host.canRead()) continue
File(root, folder.guest.removePrefix("/")).mkdirs()
out += folder.host.path + ":" + folder.guest
}
return out
}
internal fun externalBindSpecs(roots: List<Pair<File, String>>, guestRoot: File): List<String> =
roots.mapNotNull { (host, guest) ->
if (!host.isDirectory || !host.canRead()) return@mapNotNull null
@@ -12,8 +12,11 @@ object StoreLaunch {
const val EPIC_CODE = ".droiddeck-epic-code"
const val EPIC_ARGS = ".droiddeck-epic-args"
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EPIC_PARENT = "Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
/** DroidDeck-Bionic's Wine has Android's root on Z:; that tool sets this to the guest's root as its Wine names it. */
const val GUEST_ROOT = "DROIDDECK_GUEST_ROOT"
private const val ROOT_VAR = "DD_R"
private const val UBISOFT_SERVICE = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EPIC_PARENT = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
/** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */
const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
/** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */
@@ -47,6 +50,10 @@ object StoreLaunch {
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
if (sidecar.store == Store.EPIC || sidecar.store == Store.UBISOFT) {
lines += "set \"$ROOT_VAR=Z:\""
lines += "if defined $GUEST_ROOT set \"$ROOT_VAR=%$GUEST_ROOT%\""
}
if (sidecar.store == Store.EPIC) {
lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\""
lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\""
@@ -137,7 +144,6 @@ object StoreLaunch {
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
@@ -65,6 +65,7 @@ class StoreLoginActivity : ComponentActivity() {
val readsPage: Boolean get() = false
val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()"
fun pageReady(result: String): Boolean = true
fun browserStep(page: String): String? = null
fun forgetSignIn(done: () -> Unit) = done()
fun pageFinished(view: WebView, url: String) {}
}
@@ -72,6 +73,7 @@ class StoreLoginActivity : ComponentActivity() {
private var store: Store? = null
private var clientUrl: String? = null
private var flow: Flow? = null
private var pendingBrowserStep: String? = null
private var webViewRef: WebView? = null
private var popupWebView: WebView? = null
private lateinit var contentHost: FrameLayout
@@ -211,6 +213,7 @@ class StoreLoginActivity : ComponentActivity() {
private fun reloadLogin() {
dismissPopup(); clearError()
pendingBrowserStep = null
captured.set(false)
val fresh = generateState()
oauthState = fresh
@@ -332,9 +335,13 @@ class StoreLoginActivity : ComponentActivity() {
private fun readPage(view: WebView, f: Flow, left: Int) {
view.evaluateJavascript(f.pageScript) { json ->
if (flow !== f) return@evaluateJavascript
val result = json ?: ""
if (!f.pageReady(result) && left > 0) view.postDelayed({ readPage(view, f, left - 1) }, PAGE_RETRY_MS)
else Thread({ settle(f.finish(this, view, result)) }, "store-login").start()
else {
val step = f.browserStep(result)
if (step == null || !continueInBrowser(step)) Thread({ settle(f.finish(this, view, result)) }, "store-login").start()
}
}
}
@@ -350,6 +357,21 @@ class StoreLoginActivity : ComponentActivity() {
if (f.readsPage) readPage(view, f, PAGE_TRIES) else Thread({ settle(f.finish(this, view, url)) }, "store-login").start()
}
private fun continueInBrowser(url: String): Boolean {
if (isFinishing || isDestroyed) return false
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) {
pendingBrowserStep = url
return true
}
val opened = runCatching { startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url))) }
.onFailure { Log.w(TAG, "no browser took the sign-in step: ${it.javaClass.simpleName}") }
.isSuccess
if (!opened) return false
titleText.text = getString(R.string.stores_login_title, store?.label ?: "")
showError(getString(R.string.stores_login_continue_in_browser, store?.label ?: ""))
return true
}
private fun settle(problem: String?) {
runOnUiThread {
if (problem == null) { StoresState.refresh(this); finish(); return@runOnUiThread }
@@ -367,6 +389,10 @@ class StoreLoginActivity : ComponentActivity() {
override fun onStart() {
super.onStart()
pendingBrowserStep?.let { step ->
pendingBrowserStep = null
if (!continueInBrowser(step)) reloadLogin()
}
if (clientUrl != null && !isFinishing) com.droiddeck.launcher.session.SessionService.holdForSignIn(this, true)
}
@@ -7,9 +7,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SecondaryLibrary
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
@@ -75,22 +73,10 @@ object BattleNetInstall {
}
internal fun binds(context: Context): List<String> {
val out = ArrayList<String>(StoreInstallRoot.externalBindSpecs(context))
val root = LinuxRuntime.rootDir(context)
GameStorage.effective(context)?.let { library ->
if (!File(library.path).isDirectory) throw IllegalStateException(context.getString(R.string.game_sync_err_game_storage))
val content = SecondaryLibrary.contentPath(File(library.path)).path
for (guest in SecondaryLibrary.CARD_GUESTS) {
File(root, guest.removePrefix("/")).mkdirs()
out += "$content:$guest"
}
}
for (folder in AddedGames.roots(context)) {
if (!folder.host.isDirectory || !folder.host.canRead()) continue
File(root, folder.guest.removePrefix("/")).mkdirs()
out += folder.host.path + ":" + folder.guest
}
return out
return StoreInstallRoot.guestBinds(context)
}
internal fun run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int =
@@ -5,8 +5,9 @@ import android.webkit.WebView
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.StoreLoginActivity
import org.json.JSONObject
import org.json.JSONTokener
internal class EpicLogin private constructor(
internal class EpicLogin internal constructor(
override val startUrl: String,
override val userAgent: String,
private val redirectPrefix: String,
@@ -15,6 +16,12 @@ internal class EpicLogin private constructor(
override fun isRedirect(url: String): Boolean = url.startsWith(redirectPrefix)
override fun browserStep(page: String): String? {
val action = correctiveAction(page) ?: return null
Log.i(TAG, "the redirect page asks for a corrective action: $action")
return ACCOUNT_SIGN_IN_URL
}
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
val code = EpicNative.call("auth.codeFromPage", JSONObject().put("text", url))?.optString("code", "").orEmpty()
if (code.isEmpty()) {
@@ -38,6 +45,15 @@ internal class EpicLogin private constructor(
companion object {
private const val TAG = "EpicLogin"
private const val CORRECTIVE_ACTION_REQUIRED = "errors.com.epicgames.oauth.corrective_action_required"
internal const val ACCOUNT_SIGN_IN_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal"
internal fun correctiveAction(page: String): String? {
val text = runCatching { JSONTokener(page).nextValue() }.getOrNull() as? String ?: page
val body = runCatching { JSONObject(text.trim()) }.getOrNull() ?: return null
if (body.optString("errorCode") != CORRECTIVE_ACTION_REQUIRED) return null
return body.optJSONObject("metadata")?.optString("correctiveAction").orEmpty().ifEmpty { "unknown" }
}
fun create(): StoreLoginActivity.Flow? {
val config = EpicNative.call("auth.config") ?: return null
@@ -4,7 +4,6 @@ import android.content.Context;
import android.util.Log;
import com.droiddeck.launcher.frontend.AddedGames;
import com.droiddeck.launcher.runtime.GuestCommand;
import com.droiddeck.launcher.stores.StoreLanguage;
import com.droiddeck.launcher.stores.StoreLog;
import com.droiddeck.launcher.stores.download.StoreDownloadTier;
@@ -271,11 +270,10 @@ public final class GogDownloadManager {
long planned = 0;
boolean sized = true;
for (InstallerPart part : parts) { planned += part.size; if (part.size <= 0) sized = false; }
if (sized) {
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(planned, usable)) {
throw new InstallException("Not enough free space: need " + formatBytes(planned) + ", only " + formatBytes(usable) + " free");
}
long needed = installerBytesNeeded(knownPartBytes(parts), GogLibrary.INSTANCE.sizeOf(ctx, game.gameId));
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, usable)) {
throw new InstallException("Not enough free space: need " + formatBytes(needed) + ", only " + formatBytes(usable) + " free");
}
long total = 0;
for (InstallerPart part : parts) {
@@ -327,10 +325,7 @@ public final class GogDownloadManager {
cb.onProgress("Extracting installer…", 95);
int rc;
try {
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
"/usr/local/bin/droiddeck-innoextract", "--gog", "--silent",
"-d", guestDir, guestSetup),
false, "gog-innoextract", null, null, false, cancelled, null,
rc = GogInnoextract.extract(ctx, guestSetup, guestDir, "gog-innoextract", cancelled,
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
} catch (Exception e) {
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
@@ -339,6 +334,16 @@ public final class GogDownloadManager {
if (rc != 0) throw new InstallException("The installer could not be extracted (innoextract exit " + rc + ")");
}
static long knownPartBytes(List<InstallerPart> parts) {
long known = 0;
for (InstallerPart part : parts) if (part.size > 0) known += part.size;
return known;
}
static long installerBytesNeeded(long downloadBytes, long installedBytes) {
return Math.max(0, downloadBytes) + Math.max(0, installedBytes);
}
static final class InstallerPart {
final String url;
final String filename;
@@ -0,0 +1,17 @@
package com.droiddeck.launcher.stores.gog
import android.content.Context
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.stores.StoreInstallRoot
import java.util.concurrent.atomic.AtomicBoolean
internal object GogInnoextract {
private const val PROGRAM = "/usr/local/bin/droiddeck-innoextract"
@JvmStatic
fun extract(context: Context, setup: String, target: String, logName: String, cancelled: AtomicBoolean, onLine: (String) -> Unit): Int =
GuestCommand.run(context, argv(setup, target), logName = logName,
extraBinds = StoreInstallRoot.guestBinds(context), cancelled = cancelled, onLine = onLine)
internal fun argv(setup: String, target: String): List<String> = listOf(PROGRAM, "--gog", "--silent", "-d", target, setup)
}
@@ -3,11 +3,9 @@ package com.droiddeck.launcher.stores.gog
import android.content.Context
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONArray
@@ -71,8 +69,7 @@ internal object GogOffline {
val source = AddedGames.guestPath(context, installer) ?: error("The GOG installer is not visible to Linux")
val target = AddedGames.guestPath(context, extracted) ?: error("The GOG staging folder is not visible to Linux")
handle.stage(DownloadStage.INSTALL, "Extracting the full offline installer")
val rc = GuestCommand.run(context, listOf("/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", target, source),
extraBinds = StoreInstallRoot.externalBindSpecs(context), cancelled = stop, logName = "gog-refresh", onLine = handle::log)
val rc = GogInnoextract.extract(context, source, target, "gog-refresh", stop, handle::log)
if (stop.get()) return
check(rc == 0) { "GOG installer extraction failed (exit $rc)" }
applyRefresh(proposal, extracted, handle, stop)
@@ -117,6 +117,7 @@ import com.droiddeck.launcher.IconPack
import android.content.pm.ShortcutInfo
import android.graphics.Bitmap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.withContext
import com.droiddeck.launcher.HomeWidgets
@@ -388,21 +389,49 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
}
val front = LocalFrontFocus.current
val steer = rememberCoroutineScope()
// Down goes to the tile straight below. The grid's own search only sees the tiles laid out so far, so above a short or
// The tile a move is heading to, by its id so that a list update cannot shift it, and the number of the latest move.
val aim = remember { arrayOfNulls<String>(1) }
val moves = remember { intArrayOf(0) }
val move = remember { arrayOfNulls<Job>(1) }
// Up and Down go to the tile straight above or below. The grid's own search works from where the tiles are drawn at that
// moment, so while a scroll is still catching up with fast presses it skips a row or drifts a column, and above a short or
// unseen last row it lands on a tile further left; above a gap in a short last row the row's last tile takes it.
// Presses aim from the tile a move is already heading to, so none is lost before the focus lands.
Box(Modifier.weight(1f).fillMaxWidth().onPreviewKeyEvent { event ->
val k = event.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_DPAD_DOWN || front == null) return@onPreviewKeyEvent false
val from = entries.indexOfFirst { tileId(it) == front.last }
val down = k.keyCode == KeyEvent.KEYCODE_DPAD_DOWN
if ((!down && k.keyCode != KeyEvent.KEYCODE_DPAD_UP) || front == null) return@onPreviewKeyEvent false
val aimed = aim[0]?.let { id -> entries.indexOfFirst { tileId(it) == id } } ?: -1
if (aim[0] != null && aimed < 0) {
// The tile a move was heading to has left the list: that move is dropped and the press aims from the focus.
move[0]?.cancel()
aim[0] = null
}
val from = aimed.takeIf { it >= 0 } ?: entries.indexOfFirst { tileId(it) == front.last }
val columns = (grid.layoutInfo.visibleItemsInfo.maxOfOrNull { it.column } ?: 0) + 1
if (from < 0 || from / columns == entries.lastIndex / columns) return@onPreviewKeyEvent false
if (from < 0) return@onPreviewKeyEvent false
// At the first or last row the press leaves the grid, unless a move has not landed yet: then it waits for it.
val edge = if (down) from / columns == entries.lastIndex / columns else from < columns
if (edge) return@onPreviewKeyEvent aim[0] != null
if (k.action == KeyEvent.ACTION_DOWN) {
val id = tileId(entries[minOf(from + columns, entries.lastIndex)])
val shown = (front.attached[id] ?: 0) > 0
if (!shown || runCatching { front.items.getValue(id).requestFocus() }.isFailure) steer.launch {
// The row below is not laid out yet: bring it in, then take it.
if (!shown) grid.scrollBy((grid.layoutInfo.visibleItemsInfo.firstOrNull { it.index == from + leadItems }?.size?.height ?: 0).toFloat())
focusSoon { front.items.getValue(id) }
val to = if (down) minOf(from + columns, entries.lastIndex) else from - columns
val id = tileId(entries[to])
aim[0] = id
val mine = ++moves[0]
// A newer move replaces the one still on its way, so an older target cannot take focus after it lands.
move[0]?.cancel()
move[0] = steer.launch {
try {
// Show the row before it takes focus. The grid composes rows ahead of the view without placing them, and a
// tile focused there neither scrolls in nor has a place for the next search to start from.
grid.reveal(to + leadItems)
if (moves[0] != mine) return@launch
focusSoon { front.items.getValue(id) }
} finally {
// Also when a touch scroll cancels the reveal, so the edge rows do not keep waiting for a move that ended.
// Only the latest move clears it: a cancelled one finishing late must not clear a newer move's target.
if (moves[0] == mine) aim[0] = null
}
}
}
true
@@ -558,6 +587,26 @@ private fun HeaderChoiceButton(
}
}
/** Scrolls the least that shows item [index] whole inside the padding, a row at a time while it is still outside the laid out items. */
private suspend fun LazyGridState.reveal(index: Int) {
repeat(4) {
val info = layoutInfo
val shown = info.visibleItemsInfo
val item = shown.firstOrNull { it.index == index }
val by = when {
item != null -> {
val bottom = item.offset.y + item.size.height - (info.viewportEndOffset - info.afterContentPadding)
if (item.offset.y < 0) item.offset.y else maxOf(bottom, 0)
}
index > (shown.lastOrNull() ?: return).index -> shown.last().size.height
index < shown.first().index -> -shown.first().size.height
else -> return
}
if (by == 0) return
scrollBy(by.toFloat())
}
}
@Composable
private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
@@ -526,11 +526,11 @@ fun ComponentsPage(
val availableTitle: @Composable (String) -> String = { l ->
when (l) {
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot, view?.proton?.dir?.name).size)
}
}
val followed = view?.proton?.let(ComponentUpdates::follows) == true
val moded: (String) -> Boolean = { followed && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
val followed: (String) -> Boolean = { l -> view?.proton?.let { ComponentUpdates.autoFollows(it, l) } == true }
val moded: (String) -> Boolean = { followed(it) && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
when (l) {
@@ -614,7 +614,7 @@ fun ComponentsPage(
}
}
else -> {
val available = availableRows(l, catalog, snapshot)
val available = availableRows(l, catalog, snapshot, view?.proton?.dir?.name)
if (available.isEmpty()) EmptyLine(if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new))
for ((stable, nightly) in available) {
val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable
@@ -974,18 +974,18 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
o.label.substringAfterLast(" · ", "").ifEmpty { o.label }.let { if (isCurrent) stringResource(R.string.comp_this_build, it) else stringResource(R.string.comp_earlier_build, it) },
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
} + ComponentsManager.forTool(l, view.proton.dir.name, (snapshot?.packages ?: emptyList()).filter { it.comp == l }, st.activeFile) { it.file }.map { s ->
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
}
}
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<CatalogItem> {
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<CatalogItem> {
val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet()
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }
return ComponentsManager.forTool(l, toolDir, catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }) { it.file }
}
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<Pair<CatalogItem, CatalogItem?>> {
val available = availableFor(l, catalog, snapshot)
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<Pair<CatalogItem, CatalogItem?>> {
val available = availableFor(l, catalog, snapshot, toolDir)
val pairs = ComponentsManager.nightlyPairs(available)
val paired = pairs.values.toSet()
return available.filter { it !in paired }.map { it to pairs[it] }
@@ -1201,7 +1201,7 @@ private fun GameComponentOverrides(
}
GamePackageRow(
comp = "fex",
packages = packages,
packages = ComponentsManager.forTool("fex", protonChoice?.dir ?: generalProton?.dir?.name, packages, componentChoices["fex"]) { it.file },
selectedFile = componentChoices["fex"],
open = componentMenu == "fex",
busy = busy,
@@ -60,7 +60,8 @@ import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.files.StorageRoot
import com.droiddeck.launcher.files.StorageRoots
import com.droiddeck.launcher.stores.formatBytes
import java.io.File
@@ -74,10 +75,16 @@ internal class PickVolume(val root: File, val label: String, val removable: Bool
}
internal fun pickVolumes(context: Context): List<PickVolume> =
listOf(PickVolume(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), removable = false)) +
GameStorage.options(context).mapNotNull { o ->
File(o.path.substringBefore("/Android/")).takeIf { it.isDirectory }?.let { PickVolume(it, o.name, removable = true) }
}.distinctBy { it.root.absolutePath }
pickVolumes(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), StorageRoots.list(context))
internal fun pickVolumes(internal: File, internalLabel: String, roots: List<StorageRoot>): List<PickVolume> {
val internalPath = internal.absolutePath.trimEnd('/')
fun overlapsInternal(path: String) = path == internalPath || path.startsWith("$internalPath/") || internalPath.startsWith("$path/")
return listOf(PickVolume(internal, internalLabel, removable = false)) +
roots.filter { it.readable && !overlapsInternal(it.dir.absolutePath.trimEnd('/')) }
.map { PickVolume(it.dir, it.label, removable = true) }
.distinctBy { it.root.absolutePath }
}
internal class PickFolder(val dir: File, val readable: Boolean)
@@ -58,6 +58,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.withFrameNanos
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.first
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
@@ -764,12 +765,31 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
focusManager.clearFocus(force = true)
onRailSelect(key)
}, a)
val stepScope = androidx.compose.runtime.rememberCoroutineScope()
val pageKeyNow = androidx.compose.runtime.rememberUpdatedState(s.pageKey)
var railHold by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
if (!processSettingsPageVisible) {
val keys = navigationKeys(s)
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
PageSwipe.direction = step
onRailSelect(key)
if (s.dualScreen) { onRailSelect(key); return@let }
showRailPage(key, false)
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
val since = MainTabSteps.otherKeys
val owner = selected
val ownPage = if (key == "components") "components" else null
railHold?.cancel()
// Pages focus their own first control as they appear; the ring stays on the rail until another key moves it.
railHold = stepScope.launch {
var pageShown = false
repeat(RAIL_HOLD_FRAMES) {
withFrameNanos { }
if (MainTabSteps.otherKeys != since || selected != owner) return@launch
if (pageKeyNow.value == ownPage) pageShown = true else if (pageShown) return@launch
if (frontFocus.focusedRail != key) runCatching { frontFocus.railFor(key).requestFocus() }
}
}
}
}
}
@@ -900,4 +920,7 @@ internal object ChildProcessSetup {
internal object MainTabSteps {
@Volatile var handler: ((Int) -> Unit)? = null
@Volatile var otherKeys = 0
}
private const val RAIL_HOLD_FRAMES = 60
@@ -1098,8 +1098,6 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
internal const val GAME_SETTINGS_MENU = "game-settings"
private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal"
@Composable
private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) {
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
@@ -1149,7 +1147,7 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro
MenuItem(stringResource(R.string.epic_resolve), checked = false) {
host.open = null
runCatching {
appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(EPIC_RESOLVE_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(com.droiddeck.launcher.stores.epic.EpicLogin.ACCOUNT_SIGN_IN_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
}
@@ -38,8 +38,10 @@ import com.droiddeck.launcher.input.InputButtonShape
import com.droiddeck.launcher.input.InputButtonImages
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.ThrottledRedraw
import com.droiddeck.launcher.input.pcKeyLabel
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.min
@@ -581,6 +583,10 @@ class InputSurfaceView(
private var originY = 0f
private var knobX = 0f
private var knobY = 0f
private var drawnX = 0f
private var drawnY = 0f
private var atRim = false
private val redraw = ThrottledRedraw(this, STICK_REDRAW_MS)
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
@@ -663,6 +669,7 @@ class InputSurfaceView(
MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
touching = false
atRim = false
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL || event.flags and MotionEvent.FLAG_CANCELED != 0
travel = maxOf(travel, hypot(event.x - downX, event.y - downY))
lastUp = if (!clicking && !cancelled && event.eventTime - downAt <= STICK_TAP_MS && travel <= tapSlop) event.eventTime else 0L
@@ -678,15 +685,27 @@ class InputSurfaceView(
var dx = x - originX
var dy = y - originY
val length = hypot(dx, dy)
if (length > r) { dx *= r / length; dy *= r / length }
if (force || dx != knobX || dy != knobY) move(dx, dy, r)
val rim = length > r
if (rim) { dx *= r / length; dy *= r / length }
val reachedRim = rim && !atRim
atRim = rim
if (force || dx != knobX || dy != knobY) move(dx, dy, r, throttled = !force && !reachedRim, rim = rim)
}
private fun move(dx: Float, dy: Float, r: Float) {
private fun move(dx: Float, dy: Float, r: Float, throttled: Boolean = false, rim: Boolean = false) {
knobX = dx
knobY = dy
source?.update(dx / r, dy / r)
invalidate()
if (!throttled) {
redraw.cancel()
drawnX = dx
drawnY = dy
invalidate()
} else if (rim || abs(dx - drawnX) >= MIN_STICK_MOVE_PX || abs(dy - drawnY) >= MIN_STICK_MOVE_PX) {
drawnX = dx
drawnY = dy
redraw.request()
}
}
private fun setClick(down: Boolean) {
@@ -699,6 +718,7 @@ class InputSurfaceView(
override fun onDetachedFromWindow() {
setClick(false)
if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f)
redraw.cancel()
super.onDetachedFromWindow()
}
}
@@ -766,6 +786,8 @@ class InputSurfaceView(
companion object {
private const val CLICK_MS = 300L
private const val STICK_TAP_MS = 200L
private const val STICK_REDRAW_MS = 33L
private const val MIN_STICK_MOVE_PX = 1f
private const val CLASSIC_REACH = 0.5f
private const val PANEL_REACH = 0.30f
private const val HIT_SLACK = 0.25f
@@ -1787,12 +1787,15 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
chipModifier = track("cmp-proton"),
onPick = { id -> a.onGameProton(gameProfile.appId, id) },
)
val gameTool = snap.protons.firstOrNull { it.proton.id == gameProfile.protonId }?.proton?.dir?.name
for (comp in ComponentsManager.COMPONENTS) {
val value = gameProfile.components.getValue(comp)
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val options: List<Pair<String?, String>> =
listOf(null to stringResource(R.string.comp_game_use_general)) +
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (managedDxvk) emptyList() else ComponentsManager.forTool(
comp, gameTool, snap.packages.filter { it.comp == comp }, gameProfile.componentFiles[comp],
) { it.file }.map { it.file to it.version }
DrawerStackedChoice(
host = host,
key = "game-cmp-$comp",
@@ -1875,7 +1878,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val originals = view.originals.filter { it.comp == comp }
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
ComponentsManager.forTool(comp, p.dir.name, snap.packages.filter { it.comp == comp }, st.activeFile) { it.file }.map { it.file to it.version }
if (options.isEmpty() && !managedDxvk) continue
val current = st.activeFile ?: "orig:$build"
val shown = options.firstOrNull { it.first == current }?.second
@@ -84,7 +84,7 @@ object CompositorHost {
com.droiddeck.launcher.gpu.TpUbwcHint.applyToProcess(context)
WaylandCompositor.nativeStartWithSurface(
surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir,
SessionPrefs.androidDriver(context).isEmpty(),
SessionPrefs.displayDriverFromAuto(context),
)
attached = surface
started = true
+1
View File
@@ -2818,6 +2818,7 @@
<string name="stores_login_error_ssl">الاتصال بصفحة تسجيل الدخول غير آمن.</string>
<string name="stores_login_error_verification">تعذّر التحقّق من تسجيل الدخول. حاوِل مرة أخرى.</string>
<string name="stores_login_error_generic">فشل تسجيل الدخول. حاوِل مرة أخرى.</string>
<string name="stores_login_continue_in_browser">يحتاج %1$s إلى خطوة أخرى. أكملها في المتصفح الذي فُتح، ثم حاول مرة أخرى.</string>
<string name="common_close">إغلاق</string>
<string name="common_back">رجوع</string>
<string name="common_edit">تعديل</string>
@@ -2784,6 +2784,7 @@
<string name="stores_login_error_ssl">La conexión con la página de inicio de sesión no es segura.</string>
<string name="stores_login_error_verification">No se pudo verificar el inicio de sesión. Inténtalo de nuevo.</string>
<string name="stores_login_error_generic">No se pudo iniciar sesión. Inténtalo de nuevo.</string>
<string name="stores_login_continue_in_browser">%1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo.</string>
<string name="common_close">Cerrar</string>
<string name="common_back">Atrás</string>
<string name="common_edit">Editar</string>
+1
View File
@@ -2714,6 +2714,7 @@
<string name="stores_login_error_ssl">Връзката със страницата за вход не е защитена.</string>
<string name="stores_login_error_verification">Входът не можа да бъде потвърден. Опитай отново.</string>
<string name="stores_login_error_generic">Входът се провали. Опитай отново.</string>
<string name="stores_login_continue_in_browser">%1$s изисква още една стъпка. Завърши я в браузъра, който се отвори, и опитай отново.</string>
<string name="common_close">Затвори</string>
<string name="common_back">Назад</string>
<string name="common_edit">Редактирай</string>
+1
View File
@@ -2766,6 +2766,7 @@
<string name="stores_login_error_ssl">Spojení s přihlašovací stránkou není zabezpečené.</string>
<string name="stores_login_error_verification">Přihlášení se nepodařilo ověřit. Zkuste to znovu.</string>
<string name="stores_login_error_generic">Přihlášení se nezdařilo. Zkuste to znovu.</string>
<string name="stores_login_continue_in_browser">%1$s vyžaduje ještě jeden krok. Dokončete ho v prohlížeči, který se otevřel, a zkuste to znovu.</string>
<string name="common_close">Zavřít</string>
<string name="common_back">Zpět</string>
<string name="common_edit">Upravit</string>
+1
View File
@@ -2714,6 +2714,7 @@
<string name="stores_login_error_ssl">Forbindelsen til loginsiden er ikke sikker.</string>
<string name="stores_login_error_verification">Login kunne ikke bekræftes. Forsøg igen.</string>
<string name="stores_login_error_generic">Login mislykkedes. Forsøg igen.</string>
<string name="stores_login_continue_in_browser">%1$s kræver et trin mere. Fuldfør det i browseren, der blev åbnet, og prøv igen.</string>
<string name="common_close">Luk</string>
<string name="common_back">Tilbage</string>
<string name="common_edit">Rediger</string>
+1
View File
@@ -2703,6 +2703,7 @@
<string name="stores_login_error_ssl">Die Verbindung zur Anmeldeseite ist nicht sicher.</string>
<string name="stores_login_error_verification">Die Anmeldung konnte nicht bestätigt werden. Versuche es erneut.</string>
<string name="stores_login_error_generic">Anmeldung fehlgeschlagen. Versuche es erneut.</string>
<string name="stores_login_continue_in_browser">%1$s braucht noch einen Schritt. Schließe ihn im geöffneten Browser ab und versuche es dann erneut.</string>
<string name="common_close">Schließen</string>
<string name="common_back">Zurück</string>
<string name="common_edit">Bearbeiten</string>
+1
View File
@@ -2714,6 +2714,7 @@
<string name="stores_login_error_ssl">Η σύνδεση με τη σελίδα σύνδεσης δεν είναι ασφαλής.</string>
<string name="stores_login_error_verification">Δεν ήταν δυνατή η επαλήθευση της σύνδεσης. Δοκιμάστε ξανά.</string>
<string name="stores_login_error_generic">Η σύνδεση απέτυχε. Δοκιμάστε ξανά.</string>
<string name="stores_login_continue_in_browser">Το %1$s χρειάζεται ένα ακόμη βήμα. Ολοκληρώστε το στο πρόγραμμα περιήγησης που άνοιξε και δοκιμάστε ξανά.</string>
<string name="common_close">Κλείσιμο</string>
<string name="common_back">Πίσω</string>
<string name="common_edit">Επεξεργασία</string>
+1
View File
@@ -2737,6 +2737,7 @@
<string name="stores_login_error_ssl">La conexión con la página de inicio de sesión no es segura.</string>
<string name="stores_login_error_verification">No se pudo verificar el inicio de sesión. Inténtalo de nuevo.</string>
<string name="stores_login_error_generic">No se pudo iniciar sesión. Inténtalo de nuevo.</string>
<string name="stores_login_continue_in_browser">%1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo.</string>
<string name="common_close">Cerrar</string>
<string name="common_back">Atrás</string>
<string name="common_edit">Editar</string>
+1
View File
@@ -2714,6 +2714,7 @@
<string name="stores_login_error_ssl">Yhteys kirjautumissivulle ei ole suojattu.</string>
<string name="stores_login_error_verification">Kirjautumista ei voitu vahvistaa. Yritä uudelleen.</string>
<string name="stores_login_error_generic">Kirjautuminen epäonnistui. Yritä uudelleen.</string>
<string name="stores_login_continue_in_browser">%1$s vaatii vielä yhden vaiheen. Viimeistele se avautuneessa selaimessa ja yritä sitten uudelleen.</string>
<string name="common_close">Sulje</string>
<string name="common_back">Takaisin</string>
<string name="common_edit">Muokkaa</string>
+1
View File
@@ -2736,6 +2736,7 @@
<string name="stores_login_error_ssl">La liaison avec la page de connexion n\'est pas sécurisée.</string>
<string name="stores_login_error_verification">Impossible de vérifier la connexion. Réessayez.</string>
<string name="stores_login_error_generic">Échec de la connexion. Réessayez.</string>
<string name="stores_login_continue_in_browser">%1$s demande une étape de plus. Terminez-la dans le navigateur qui s\'est ouvert, puis réessayez.</string>
<string name="common_close">Fermer</string>
<string name="common_back">Retour</string>
<string name="common_edit">Modifier</string>
+1
View File
@@ -2714,6 +2714,7 @@
<string name="stores_login_error_ssl">साइन-इन पेज से कनेक्शन सुरक्षित नहीं है।</string>
<string name="stores_login_error_verification">साइन-इन सत्यापित नहीं हो सका। फिर कोशिश करें।</string>
<string name="stores_login_error_generic">साइन-इन विफल रहा। फिर कोशिश करें।</string>
<string name="stores_login_continue_in_browser">%1$s को एक और चरण चाहिए। खुले हुए ब्राउज़र में इसे पूरा करें, फिर दोबारा कोशिश करें।</string>
<string name="common_close">बंद करें</string>
<string name="common_back">बैक</string>
<string name="common_edit">संपादित करें</string>
+1
View File
@@ -2714,6 +2714,7 @@
<string name="stores_login_error_ssl">A kapcsolat a bejelentkezési oldalhoz nem biztonságos.</string>
<string name="stores_login_error_verification">A bejelentkezést nem sikerült ellenőrizni. Próbálja újra.</string>
<string name="stores_login_error_generic">A bejelentkezés sikertelen. Próbálja újra.</string>
<string name="stores_login_continue_in_browser">A(z) %1$s még egy lépést kér. Fejezze be a megnyílt böngészőben, majd próbálja újra.</string>
<string name="common_close">Bezárás</string>
<string name="common_back">Vissza</string>
<string name="common_edit">Szerkesztés</string>
+1
View File
@@ -2689,6 +2689,7 @@
<string name="stores_login_error_ssl">Koneksi ke halaman masuk tidak aman.</string>
<string name="stores_login_error_verification">Proses masuk tidak dapat diverifikasi. Coba lagi.</string>
<string name="stores_login_error_generic">Proses masuk gagal. Coba lagi.</string>
<string name="stores_login_continue_in_browser">%1$s memerlukan satu langkah lagi. Selesaikan di browser yang terbuka, lalu coba lagi.</string>
<string name="common_close">Tutup</string>
<string name="common_back">Kembali</string>
<string name="common_edit">Edit</string>
+1
View File
@@ -2728,6 +2728,7 @@
<string name="stores_login_error_ssl">La connessione alla pagina di accesso non è sicura.</string>
<string name="stores_login_error_verification">Impossibile verificare l\'accesso. Riprova.</string>
<string name="stores_login_error_generic">Accesso non riuscito. Riprova.</string>
<string name="stores_login_continue_in_browser">%1$s richiede un altro passaggio. Completalo nel browser che si è aperto, poi riprova.</string>
<string name="common_close">Chiudi</string>
<string name="common_back">Indietro</string>
<string name="common_edit">Modifica</string>
+1
View File
@@ -2689,6 +2689,7 @@
<string name="stores_login_error_ssl">ログインページへの接続は安全ではありません。</string>
<string name="stores_login_error_verification">ログインを確認できませんでした。もう一度お試しください。</string>
<string name="stores_login_error_generic">ログインに失敗しました。もう一度お試しください。</string>
<string name="stores_login_continue_in_browser">%1$s で追加の手順が必要です。開いたブラウザーで完了してから、もう一度お試しください。</string>
<string name="common_close">閉じる</string>
<string name="common_back">戻る</string>
<string name="common_edit">編集</string>
+1
View File
@@ -2689,6 +2689,7 @@
<string name="stores_login_error_ssl">로그인 페이지 연결이 안전하지 않습니다.</string>
<string name="stores_login_error_verification">로그인을 확인할 수 없습니다. 다시 시도하세요.</string>
<string name="stores_login_error_generic">로그인에 실패했습니다. 다시 시도하세요.</string>
<string name="stores_login_continue_in_browser">%1$s에서 한 단계가 더 필요합니다. 열린 브라우저에서 완료한 다음 다시 시도하세요.</string>
<string name="common_close">닫기</string>
<string name="common_back">뒤로</string>
<string name="common_edit">편집</string>
+1
View File
@@ -2689,6 +2689,7 @@
<string name="stores_login_error_ssl">Sambungan ke halaman log masuk tidak selamat.</string>
<string name="stores_login_error_verification">Log masuk tidak dapat disahkan. Cuba lagi.</string>
<string name="stores_login_error_generic">Log masuk gagal. Cuba lagi.</string>
<string name="stores_login_continue_in_browser">%1$s memerlukan satu langkah lagi. Selesaikannya dalam pelayar yang dibuka, kemudian cuba lagi.</string>
<string name="common_close">Tutup</string>
<string name="common_back">Kembali</string>
<string name="common_edit">Sunting</string>
+1
View File
@@ -2714,6 +2714,7 @@
<string name="stores_login_error_ssl">Tilkoblingen til innloggingssiden er ikke sikker.</string>
<string name="stores_login_error_verification">Innloggingen kunne ikke verifiseres. Prøv igjen.</string>
<string name="stores_login_error_generic">Innlogging mislyktes. Prøv igjen.</string>
<string name="stores_login_continue_in_browser">%1$s trenger ett trinn til. Fullfør det i nettleseren som ble åpnet, og prøv igjen.</string>
<string name="common_close">Lukk</string>
<string name="common_back">Tilbake</string>
<string name="common_edit">Rediger</string>
+1
View File
@@ -2714,6 +2714,7 @@
<string name="stores_login_error_ssl">De verbinding met de aanmeldpagina is niet beveiligd.</string>
<string name="stores_login_error_verification">De aanmelding kon niet worden geverifieerd. Probeer het opnieuw.</string>
<string name="stores_login_error_generic">Aanmelden mislukt. Probeer het opnieuw.</string>
<string name="stores_login_continue_in_browser">%1$s vraagt nog één stap. Rond die af in de browser die is geopend en probeer het opnieuw.</string>
<string name="common_close">Sluiten</string>
<string name="common_back">Terug</string>
<string name="common_edit">Bewerken</string>
+1
View File
@@ -2766,6 +2766,7 @@
<string name="stores_login_error_ssl">Połączenie ze stroną logowania nie jest bezpieczne.</string>
<string name="stores_login_error_verification">Nie udało się zweryfikować logowania. Spróbuj ponownie.</string>
<string name="stores_login_error_generic">Logowanie nie powiodło się. Spróbuj ponownie.</string>
<string name="stores_login_continue_in_browser">%1$s wymaga jeszcze jednego kroku. Dokończ go w otwartej przeglądarce, a potem spróbuj ponownie.</string>
<string name="common_close">Zamknij</string>
<string name="common_back">Wstecz</string>
<string name="common_edit">Edytuj</string>
@@ -2742,6 +2742,7 @@
<string name="stores_login_error_ssl">A ligação à página de início de sessão não é segura.</string>
<string name="stores_login_error_verification">Não foi possível verificar o início de sessão. Tente novamente.</string>
<string name="stores_login_error_generic">Falha no início de sessão. Tente novamente.</string>
<string name="stores_login_continue_in_browser">%1$s precisa de mais um passo. Conclua-o no navegador que foi aberto e tente novamente.</string>
<string name="common_close">Fechar</string>
<string name="common_back">Voltar</string>
<string name="common_edit">Editar</string>
+1
View File
@@ -2750,6 +2750,7 @@
<string name="stores_login_error_ssl">A conexão com a página de login não é segura.</string>
<string name="stores_login_error_verification">Não foi possível verificar o login. Tente de novo.</string>
<string name="stores_login_error_generic">Falha no login. Tente de novo.</string>
<string name="stores_login_continue_in_browser">%1$s precisa de mais uma etapa. Conclua no navegador que foi aberto e tente novamente.</string>
<string name="common_close">Fechar</string>
<string name="common_back">Voltar</string>
<string name="common_edit">Editar</string>
+1
View File
@@ -2740,6 +2740,7 @@
<string name="stores_login_error_ssl">Conexiunea la pagina de autentificare nu este sigură.</string>
<string name="stores_login_error_verification">Autentificarea nu a putut fi verificată. Încearcă din nou.</string>
<string name="stores_login_error_generic">Autentificarea a eșuat. Încearcă din nou.</string>
<string name="stores_login_continue_in_browser">%1$s mai cere un pas. Finalizează-l în browserul care s-a deschis, apoi încearcă din nou.</string>
<string name="common_close">Închide</string>
<string name="common_back">Înapoi</string>
<string name="common_edit">Editează</string>
+1
View File
@@ -2764,6 +2764,7 @@
<string name="stores_login_error_ssl">Подключение к странице входа не защищено.</string>
<string name="stores_login_error_verification">Не удалось подтвердить вход. Повторите попытку.</string>
<string name="stores_login_error_generic">Ошибка входа. Повторите попытку.</string>
<string name="stores_login_continue_in_browser">%1$s требует ещё один шаг. Завершите его в открывшемся браузере и попробуйте снова.</string>
<string name="common_close">Закрыть</string>
<string name="common_back">Назад</string>
<string name="common_edit">Изменить</string>
+1
View File
@@ -2714,6 +2714,7 @@
<string name="stores_login_error_ssl">Anslutningen till inloggningssidan är inte säker.</string>
<string name="stores_login_error_verification">Inloggningen kunde inte verifieras. Försök igen.</string>
<string name="stores_login_error_generic">Inloggningen misslyckades. Försök igen.</string>
<string name="stores_login_continue_in_browser">%1$s behöver ett steg till. Slutför det i webbläsaren som öppnades och försök sedan igen.</string>
<string name="common_close">Stäng</string>
<string name="common_back">Tillbaka</string>
<string name="common_edit">Redigera</string>
+1
View File
@@ -2689,6 +2689,7 @@
<string name="stores_login_error_ssl">การเชื่อมต่อไปยังหน้าลงชื่อเข้าใช้ไม่ปลอดภัย</string>
<string name="stores_login_error_verification">ไม่สามารถยืนยันการลงชื่อเข้าใช้ได้ ลองใหม่</string>
<string name="stores_login_error_generic">ลงชื่อเข้าใช้ล้มเหลว ลองใหม่</string>
<string name="stores_login_continue_in_browser">%1$s ต้องการอีกหนึ่งขั้นตอน ทำให้เสร็จในเบราว์เซอร์ที่เปิดขึ้น แล้วลองอีกครั้ง</string>
<string name="common_close">ปิด</string>
<string name="common_back">กลับ</string>
<string name="common_edit">แก้ไข</string>
+1
View File
@@ -2703,6 +2703,7 @@
<string name="stores_login_error_ssl">Oturum açma sayfasına bağlantı güvenli değil.</string>
<string name="stores_login_error_verification">Oturum açma doğrulanamadı. Yeniden deneyin.</string>
<string name="stores_login_error_generic">Oturum açma başarısız oldu. Yeniden deneyin.</string>
<string name="stores_login_continue_in_browser">%1$s bir adım daha istiyor. Açılan tarayıcıda tamamlayın, ardından yeniden deneyin.</string>
<string name="common_close">Kapat</string>
<string name="common_back">Geri</string>
<string name="common_edit">Düzenle</string>
+1
View File
@@ -2766,6 +2766,7 @@
<string name="stores_login_error_ssl">З’єднання зі сторінкою входу не захищене.</string>
<string name="stores_login_error_verification">Не вдалося підтвердити вхід. Спробуйте ще раз.</string>
<string name="stores_login_error_generic">Вхід не вдався. Спробуйте ще раз.</string>
<string name="stores_login_continue_in_browser">%1$s потребує ще одного кроку. Завершіть його у відкритому браузері та спробуйте ще раз.</string>
<string name="common_close">Закрити</string>
<string name="common_back">Назад</string>
<string name="common_edit">Редагувати</string>
+1
View File
@@ -2689,6 +2689,7 @@
<string name="stores_login_error_ssl">Kết nối đến trang đăng nhập không an toàn.</string>
<string name="stores_login_error_verification">Không thể xác minh đăng nhập. Hãy thử lại.</string>
<string name="stores_login_error_generic">Đăng nhập thất bại. Hãy thử lại.</string>
<string name="stores_login_continue_in_browser">%1$s cần thêm một bước. Hãy hoàn tất trong trình duyệt vừa mở, rồi thử lại.</string>
<string name="common_close">Đóng</string>
<string name="common_back">Quay lại</string>
<string name="common_edit">Sửa</string>
@@ -2763,6 +2763,7 @@
<string name="stores_login_error_ssl">与登录页面的连接不安全。</string>
<string name="stores_login_error_verification">无法验证登录。请重试。</string>
<string name="stores_login_error_generic">登录失败。请重试。</string>
<string name="stores_login_continue_in_browser">%1$s 还需要一个步骤。请在已打开的浏览器中完成,然后重试。</string>
<string name="common_close">关闭</string>
<string name="common_back">返回</string>
<string name="common_edit">编辑</string>
@@ -2686,6 +2686,7 @@
<string name="stores_login_error_ssl">與登入頁面的連線不安全。</string>
<string name="stores_login_error_verification">無法驗證登入,請再試一次。</string>
<string name="stores_login_error_generic">登入失敗,請再試一次。</string>
<string name="stores_login_continue_in_browser">%1$s 還需要一個步驟。請在已開啟的瀏覽器中完成,然後再試一次。</string>
<string name="common_close">關閉</string>
<string name="common_back">返回</string>
<string name="common_edit">編輯</string>
@@ -2686,6 +2686,7 @@
<string name="stores_login_error_ssl">與登入頁面的連線不安全。</string>
<string name="stores_login_error_verification">無法驗證登入。請再試一次。</string>
<string name="stores_login_error_generic">登入失敗。請再試一次。</string>
<string name="stores_login_continue_in_browser">%1$s 還需要一個步驟。請在已開啟的瀏覽器中完成,然後再試一次。</string>
<string name="common_close">關閉</string>
<string name="common_back">返回</string>
<string name="common_edit">編輯</string>
+1
View File
@@ -3034,6 +3034,7 @@
<string name="stores_login_error_ssl">The connection to the sign-in page is not secure.</string>
<string name="stores_login_error_verification">The sign-in could not be verified. Try again.</string>
<string name="stores_login_error_generic">Sign-in failed. Try again.</string>
<string name="stores_login_continue_in_browser">%1$s needs one more step. Finish it in the browser that opened, then try again.</string>
<string name="common_close">Close</string>
<string name="common_back">Back</string>
<string name="common_edit">Edit</string>
@@ -0,0 +1,85 @@
package com.droiddeck.launcher
import android.content.Intent
import com.droiddeck.launcher.core.SteamIntegration
import com.droiddeck.launcher.frontend.GameRequest
import com.droiddeck.launcher.session.LaunchCoordinator
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.util.ReflectionHelpers
/**
* A replacement activity intent invalidates everything this activity has not dispatched yet: a
* resolved but unhandled game link, and an accepted launch that is still waiting for its session.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class FrontEndIntentSupersedeTest {
private lateinit var activity: FrontEndActivity
private lateinit var coordinator: LaunchCoordinator<Intent, GameRequest>
@Before
fun setUp() {
activity = Robolectric.buildActivity(FrontEndActivity::class.java).get()
coordinator = ReflectionHelpers.getField(activity, "launchCoordinator")
}
@Test
fun aReplacementIntentDropsAResolvedPendingLink() {
val owner = Intent(activity, FrontEndActivity::class.java)
val ticket = coordinator.beginLink(owner)
assertTrue(coordinator.resolve(ticket, GameRequest(id = "app")))
supersede()
assertFalse(coordinator.hasPending())
assertNull(coordinator.pendingLink())
}
@Test
fun aReplacementIntentInvalidatesAnAcceptedLaunch() {
val ticket = coordinator.beginLaunch()
assertTrue(coordinator.isCurrent(ticket))
supersede()
assertFalse(coordinator.isCurrent(ticket))
assertNull(shadowOf(activity).nextStartedActivity)
}
@Test
fun anActionSetupIntentSupersedesTheGameLinkItReplaced() {
val owner = Intent(activity, FrontEndActivity::class.java)
val ticket = coordinator.beginLink(owner)
assertTrue(coordinator.resolve(ticket, GameRequest(id = "app")))
deliver(Intent(activity, FrontEndActivity::class.java).setAction(SteamIntegration.ACTION_SETUP))
assertFalse(coordinator.hasPending())
assertFalse(coordinator.isCurrent(ticket))
assertNull(shadowOf(activity).nextStartedActivity)
}
private fun supersede() {
ReflectionHelpers.callInstanceMethod<Void>(activity, "supersedeUncommittedLaunch")
}
/** onNewIntent() is protected, which is exactly how the platform delivers a replacement intent. */
private fun deliver(intent: Intent) {
val method = FrontEndActivity::class.java.getDeclaredMethod("onNewIntent", Intent::class.java)
method.isAccessible = true
try {
method.invoke(activity, intent)
} finally {
method.isAccessible = false
}
}
}
@@ -11,4 +11,10 @@ class DeviceSupportTest {
// A PowerVR HAL without usable DRM access also reaches this unavailable case.
assertFalse(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = false))
}
@Test fun bridgeServesEveryNonAdrenoWithoutASystemDriverRoute() {
assertTrue(DeviceSupport.bridgeUsable(adreno = false, systemDriverReady = false))
assertFalse(DeviceSupport.bridgeUsable(adreno = true, systemDriverReady = false))
assertFalse(DeviceSupport.bridgeUsable(adreno = false, systemDriverReady = true))
}
}
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.assumeFilePermissionsEnforced
import android.os.Environment
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreInstallRoot
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
@@ -92,6 +93,38 @@ class AddedExesTest {
}
}
@Test fun reselectingTheCurrentExeKeepsItWhenTheRankingChanges() {
val storage = tmp.newFolder("Ranked")
exe(File(storage, "Example/Example.exe"))
exe(File(storage, "Example/Other.exe"))
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setGameStorage(app, storage.path, "Card")
val folder = File(storage, "Example")
val current = AddedGames.scan(app).single { it.folder == folder }.exe
val other = listOf("Example.exe", "Other.exe").map { File(folder, it) }.single { it.path != current.path }
val existing = AddedGames.addExe(app, current)
assertTrue(existing is AddedGames.AddResult.Existing)
assertEquals(current.path, SessionPrefs.addedGameExe(app, folder.path))
File(folder, "MicrosoftGame.config").writeText("<Executable Name=\"${other.name}\" />")
assertEquals(other.path, AddedGames.rank(folder).exes.first().path)
assertEquals(current.path, AddedGames.scan(app).single { it.folder == folder }.exe.path)
}
@Test fun reselectingASteamInstallsExeThroughAnAliasStoresTheReachablePath() {
val storage = tmp.newFolder("Aliased")
val pick = exe(File(storage, "steamapps/common/Example/Example.exe"))
File(storage, "steamapps/appmanifest_123.acf").writeText("\"installdir\" \"Example\"")
SessionPrefs.setAddedGamesDirs(app, emptyList())
SessionPrefs.setGameStorage(app, storage.path, "Card")
val alias = File(tmp.newFolder("Links"), "Example.exe")
java.nio.file.Files.createSymbolicLink(alias.toPath(), pick.toPath())
assertTrue(AddedGames.addExe(app, alias) is AddedGames.AddResult.Existing)
assertEquals(pick.path, AddedExes.list(app).single { it.folder == pick.parentFile!!.path }.exe)
assertEquals(pick.path, SessionPrefs.addedGameExe(app, pick.parentFile!!.path))
assertEquals(pick.path, AddedGames.scan(app).single { it.folder == pick.parentFile }.exe.path)
AddedExes.drop(app, pick.parentFile!!.path)
}
@Test fun anotherExeInTheSameGameSwitchesItsExe() {
noGamesFolders()
val first = onStorage("Games2/Hades/Hades.exe")
@@ -297,6 +330,39 @@ class AddedExesTest {
assertEquals(listOf(other.path), AddedGames.scan(app).map { it.exe.path })
}
private fun routeEveryGameTo(steamApp: Int) {
val config = File(SessionPrefs.activeSteamRoot(app), "userdata/123/config").apply { mkdirs() }
val routes = org.json.JSONObject()
AddedGames.scan(app).forEach { routes.put(it.appId.toString(), steamApp) }
File(config, ".droiddeck-routes.json").writeText(routes.toString())
}
@Test fun anotherProgramOfASteamInstallIsNotRoutedToTheSteamApp() {
noGamesFolders()
val main = onStorage("Games2/The Binding of Isaac Rebirth/isaac-ng.exe")
val launcher = onStorage("Games2/The Binding of Isaac Rebirth/REPENTOGONLauncher.exe")
AddedExes.put(app, AddedExes.Entry(main.parent!!, launcher.path))
routeEveryGameTo(250900)
val game = AddedGames.scan(app).single()
assertEquals(launcher.path, game.exe.path)
assertEquals(main.path, game.candidates.first().path)
assertNull(game.steamAppId)
assertTrue(!game.steamProgram)
assertTrue(File(AddedGames.writeListing(app, listOf(game), emptyList()).path).readText().contains("\"route\":false"))
}
@Test fun theSteamAppsOwnProgramStillRoutesToTheSteamApp() {
noGamesFolders()
val main = onStorage("Games2/The Binding of Isaac Rebirth/isaac-ng.exe")
onStorage("Games2/The Binding of Isaac Rebirth/REPENTOGONLauncher.exe")
AddedExes.put(app, AddedExes.Entry(main.parent!!, main.path))
routeEveryGameTo(250900)
val game = AddedGames.scan(app).single()
assertEquals(250900, game.steamAppId)
assertTrue(game.steamProgram)
assertTrue(!File(AddedGames.writeListing(app, listOf(game), emptyList()).path).readText().contains("route"))
}
@Test fun aDifferentGameWithANumberedNameIsNotTakenAsAnotherBuild() {
noGamesFolders()
val held = onStorage("Games2/id/Doom/Doom.exe")
@@ -396,6 +462,15 @@ class AddedExesTest {
assertEquals("$clash-2", guests.last())
}
@Test fun aFolderNamedStoresIsNotBoundOverTheInternalStoreRoot() {
noGamesFolders()
val stores = File(tmp.newFolder("card"), "Stores").apply { exe(File(this, "One/One.exe")) }
val result = AddedGames.addFolder(app, stores)
val guest = SessionPrefs.gameFolderBinds(app).single().second
assertTrue(guest != StoreInstallRoot.INTERNAL_GUEST && guest.startsWith("${AddedGames.GUEST_DIR}/Stores-"))
assertEquals("$guest/One/One.exe", result.added.single().guestExe)
}
@Test fun aRemovedSingleExeGameStaysOffUntilPickedAgain() {
noGamesFolders()
val pick = onStorage("Download/Celeste/Celeste.exe")
@@ -47,6 +47,11 @@ class AddedGamesSteamEditsTest {
.writeText(JSONObject().put("games", JSONObject().put(appId.toString(), game)).toString())
}
private fun legacyAdoption(exe: File, seen: Int) {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putString("addedExe:${folder.path}", exe.path).putInt("addedExeSeen:${folder.path}", seen).commit()
}
private fun scanned() = AddedGames.scan(context).single { it.folder == folder }
@Test fun aTargetChangedInSteamBecomesTheAppsChoiceOnce() {
@@ -68,6 +73,65 @@ class AddedGamesSteamEditsTest {
assertEquals(main.path, SessionPrefs.addedGameExe(context, folder.path))
}
@Test fun aTargetChosenInSteamKeepsTheSteamAppsRouteBeforeAndAfterItIsAdopted() {
val first = scanned()
val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json")
routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString())
assertEquals(250900, scanned().steamAppId)
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1)
val adopted = scanned()
assertEquals(other, adopted.exe)
assertEquals(250900, adopted.steamAppId)
assertTrue(adopted.steamProgram)
val later = scanned()
assertEquals(other, later.exe)
assertEquals(250900, later.steamAppId)
assertTrue(later.steamProgram)
}
@Test fun aTargetAdoptedBeforeTheMarkerExistedKeepsTheSteamAppsRoute() {
val first = scanned()
val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json")
routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString())
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1)
legacyAdoption(other, 1)
assertNull(SessionPrefs.addedGameAdopted(context, folder.path, "Exe"))
val legacy = scanned()
assertEquals(other, legacy.exe)
assertEquals(250900, legacy.steamAppId)
assertTrue(legacy.steamProgram)
assertEquals(other.path, SessionPrefs.addedGameAdopted(context, folder.path, "Exe"))
}
@Test fun aProgramPickedInDroidDeckThatSteamNeverEditedStaysOutOfTheRoute() {
val first = scanned()
val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json")
routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString())
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/Example.exe", 1)
legacyAdoption(other, 1)
val picked = scanned()
assertEquals(other, picked.exe)
assertNull(picked.steamAppId)
assertTrue(!picked.steamProgram)
}
@Test fun aProgramChosenInDroidDeckAfterASteamEditLeavesTheSteamAppsRoute() {
val first = scanned()
val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json")
routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString())
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1)
assertEquals(other, scanned().exe)
val third = File(folder, "Third.exe").apply { writeBytes(ByteArray(4)) }
SessionPrefs.setAddedGameExe(context, folder.path, third.path)
val chosen = scanned()
assertEquals(third, chosen.exe)
assertNull(chosen.steamAppId)
assertTrue(!chosen.steamProgram)
}
@Test fun theListingTellsTheSessionWhichSteamEditTheAppHasTaken() {
val first = scanned()
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 3)
@@ -66,6 +66,27 @@ class AddedGamesStoreScanTest {
assertTrue(game.guestExe.endsWith("/Tools/Editor.exe"))
}
@Test fun everyStoreKeepsItsLauncherWhenItsOwnExeIsReselected() {
for (store in listOf(Store.GOG, Store.AMAZON, Store.EPIC)) {
val folder = install(store, "own-${store.id}", "Own ${store.label}", "Binaries/Game.exe", launcher = true)
val own = File(folder, "Binaries/Game.exe")
val before = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
assertTrue(AddedGames.addExe(app, own) is AddedGames.AddResult.Existing)
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
assertEquals(own.path, game.exe.path)
assertTrue(game.guestExe.endsWith("/" + StoreLaunch.LAUNCHER))
assertEquals(before.appId, game.appId)
}
}
@Test fun aDifferentPickedExeOnAnyStoreGameIsRunDirectly() {
val folder = install(Store.GOG, "tool", "Tool GOG", "Binaries/Game.exe", launcher = true)
val tool = File(folder, "Tools/Editor.exe").apply { parentFile!!.mkdirs(); writeText("tool") }
AddedExes.put(app, AddedExes.Entry(folder.path, tool.path, picked = true))
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
assertTrue(game.guestExe.endsWith("/Tools/Editor.exe"))
}
@Test fun anOlderSidecarsSteamSwitchIsIgnoredEveryInstallIsListed() {
val folder = install(Store.AMAZON, "amzn1.adg.product.x", "Yakuza 0", "Yakuza0.exe")
val file = StoreGameSidecar.file(folder)
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -182,6 +183,41 @@ class GamesFolderMigrationTest {
assertEquals(listOf(pc.path to AddedGames.GUEST_DIR + "/PC"), binds)
}
@Test fun aMigratedFolderNamedStoresDoesNotTakeTheInternalStoreGuest() {
val stores = File(tmp.newFolder("card"), "Stores").apply { exe(this, "One/One.exe") }
val pc = tmp.newFolder("PC").apply { exe(this, "Two/Two.exe") }
SessionPrefs.setAddedGamesDirs(app, listOf(stores.path, pc.path))
GamesFolderMigration.run(app)
val binds = SessionPrefs.gameFolderBinds(app).toMap()
assertTrue(binds.getValue(stores.path) != StoreInstallRoot.INTERNAL_GUEST)
assertEquals(AddedGames.GUEST_DIR + "/PC", binds.getValue(pc.path))
val games = AddedGames.scan(app).associateBy { it.name }
assertEquals(binds.getValue(stores.path) + "/One/One.exe", games.getValue("One").guestExe)
}
@Test fun aSavedBindAtTheInternalStoreGuestIsRepathed() {
val stores = File(tmp.newFolder("card"), "Stores").apply { exe(this, "One/One.exe") }
val pc = tmp.newFolder("PC").apply { exe(this, "Two/Two.exe") }
SessionPrefs.setGameFolderBinds(
app,
listOf(stores.path to StoreInstallRoot.INTERNAL_GUEST, pc.path to AddedGames.GUEST_DIR + "/PC"),
)
GamesFolderMigration.run(app)
val binds = SessionPrefs.gameFolderBinds(app).toMap()
assertTrue(binds.getValue(stores.path) != StoreInstallRoot.INTERNAL_GUEST)
assertTrue(binds.getValue(stores.path).startsWith("${AddedGames.GUEST_DIR}/Stores-"))
assertEquals(AddedGames.GUEST_DIR + "/PC", binds.getValue(pc.path))
assertTrue(binds.values.none { it == StoreInstallRoot.INTERNAL_GUEST })
assertEquals(binds.getValue(stores.path) + "/One/One.exe", AddedGames.guestPath(app, File(stores, "One/One.exe")))
val installer = File(stores, "GOG/Game/setup_1.exe").apply { parentFile?.mkdirs(); writeText("MZ") }
val guestInstaller = AddedGames.guestPath(app, installer)!!
val extractorBinds = StoreInstallRoot.guestBinds(app).map { it.substringBeforeLast(':') to it.substringAfterLast(':') }
val covering = extractorBinds.filter { (_, mount) -> guestInstaller.startsWith("$mount/") }.maxByOrNull { it.second.length }!!
assertEquals(installer.canonicalFile, File(covering.first + guestInstaller.removePrefix(covering.second)).canonicalFile)
val internalInstaller = "${StoreInstallRoot.INTERNAL_GUEST}/GOG/Game/setup_1.exe"
assertTrue(extractorBinds.none { (_, mount) -> internalInstaller == mount || internalInstaller.startsWith("$mount/") })
}
@Test fun twoFoldersOfOneNameKeepTheirOwnGuestPaths() {
val a = File(tmp.newFolder("a"), "Games").apply { mkdirs() }
val b = File(tmp.newFolder("b"), "Games").apply { mkdirs() }
@@ -0,0 +1,102 @@
package com.droiddeck.launcher.input
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class AxisPacingTest {
@Test fun theFirstReportIsWrittenAtOnce() {
assertEquals(100L, AxisPacing(4).dueAt(100, true))
}
@Test fun stickMotionInsideTheIntervalWaitsForItsEnd() {
val pacing = AxisPacing(4)
pacing.wrote(100)
assertEquals(104L, pacing.dueAt(101, true))
assertEquals(104L, pacing.dueAt(103, true))
assertEquals(104L, pacing.dueAt(104, true))
assertEquals(110L, pacing.dueAt(110, true))
}
@Test fun buttonsAndRestTransitionsAreNeverHeldBack() {
val pacing = AxisPacing(4)
pacing.wrote(100)
assertEquals(101L, pacing.dueAt(101, false))
}
@Test fun onlyMotionThatStaysOffRestIsPaced() {
assertTrue(AxisPacing.keepsMoving(0, 0))
assertTrue(AxisPacing.keepsMoving(1200, 1300))
assertTrue(AxisPacing.keepsMoving(-40, 25))
assertFalse(AxisPacing.keepsMoving(0, 900))
assertFalse(AxisPacing.keepsMoving(900, 0))
}
@Test fun theIntervalRunsFromTheFlushNotFromTheRequest() {
val pacing = AxisPacing(4)
assertEquals(100L, pacing.dueAt(100, true))
pacing.wrote(110)
assertEquals(114L, pacing.dueAt(111, true))
}
@Test fun aHeldReportIsReleasedOnlyAtItsDeadline() {
val pacing = AxisPacing(4)
assertTrue(pacing.hold(104))
assertFalse(pacing.hold(104))
assertFalse(pacing.release(103))
assertTrue(pacing.release(104))
assertFalse(pacing.release(105))
}
@Test fun aCallbackFromACancelledHoldCannotPublishTheNextHoldEarly() {
val pacing = AxisPacing(4)
assertTrue(pacing.hold(104))
assertTrue(pacing.cancel())
pacing.wrote(104)
assertTrue(pacing.hold(pacing.dueAt(105, true)))
assertFalse(pacing.release(105))
assertTrue(pacing.release(108))
}
@Test fun cancellingWithNothingHeldRemovesNoCallback() {
val pacing = AxisPacing(4)
assertFalse(pacing.cancel())
assertTrue(pacing.hold(104))
assertTrue(pacing.release(104))
assertFalse(pacing.cancel())
}
@Test fun aThousandHertzPadReachesTheGuestAtTheIntervalRate() {
val writes = feed(AxisPacing(4), sampleMs = 1, durationMs = 1000)
assertTrue("$writes writes", writes in 249..251)
}
@Test fun aPadSlowerThanTheIntervalIsNeverDelayed() {
val pacing = AxisPacing(4)
for (now in 0L until 1000L step 5) {
assertEquals(now, pacing.dueAt(now, true))
pacing.wrote(now)
}
}
private fun feed(pacing: AxisPacing, sampleMs: Long, durationMs: Long): Int {
var writes = 0
var pendingAt = -1L
for (now in 0L until durationMs step sampleMs) {
if (pendingAt in 0..now) {
pacing.wrote(pendingAt)
writes++
pendingAt = -1
}
val due = pacing.dueAt(now, true)
if (due <= now) {
pacing.wrote(now)
writes++
} else if (pendingAt < 0) {
pendingAt = due
}
}
return writes
}
}
@@ -694,22 +694,22 @@ class InputLibraryTest {
for (desktop in listOf(false, true)) for (panel in listOf(null, InputStockLayouts.TRACKPAD) + DeckPanel.entries.map { it.bindings }) {
val shown = library.panelLayout(desktop, panel)!!.elements
assertTrue(shown.isNotEmpty())
assertFalse(library.compileActive(desktop, panel).showsMouseButton(InputRole.SECONDARY, shown, library.compileStock(desktop, panel)))
assertFalse(library.compileActive(desktop, panel).showsLeftMouseButton(InputRole.SECONDARY, shown, library.compileStock(desktop, panel)))
}
}
@Test fun userBoundSecondScreenMouseButtonIsDetected() {
@Test fun userBoundSecondScreenLeftMouseButtonIsDetected() {
val stock = InputLibraries.read(context)
val grips = DeckPanel.GRIPS.bindings
val button = stock.panelLayout(false, grips)!!.elements.first { it.control.dimensions == 1 }
val bound = stock.withPreset(stock.preset(grips).copy(elements = mapOf(button.id to InputAction.MouseButton(272))))
for (desktop in listOf(false, true)) {
assertTrue(bound.compileActive(desktop, grips).showsMouseButton(InputRole.SECONDARY, listOf(button), bound.compileStock(desktop, grips)))
assertFalse(bound.compileActive(desktop, grips).showsMouseButton(InputRole.PRIMARY, listOf(button), bound.compileStock(desktop, grips)))
assertTrue(bound.compileActive(desktop, grips).showsLeftMouseButton(InputRole.SECONDARY, listOf(button), bound.compileStock(desktop, grips)))
assertFalse(bound.compileActive(desktop, grips).showsLeftMouseButton(InputRole.PRIMARY, listOf(button), bound.compileStock(desktop, grips)))
}
val pad = stock.panelLayout(true, InputStockLayouts.TRACKPAD)!!.elements.single()
val rebound = stock.withPreset(stock.preset(InputStockLayouts.TRACKPAD).let { it.copy(clicks = it.clicks + (pad.id to InputAction.MouseButton(273))) })
assertTrue(rebound.compileActive(true).showsMouseButton(InputRole.SECONDARY, listOf(pad), rebound.compileStock(true)))
assertFalse(rebound.compileActive(true).showsLeftMouseButton(InputRole.SECONDARY, listOf(pad), rebound.compileStock(true)))
}
@Test fun copiedStockPanelsKeepTapsClickingUntilAMouseButtonIsAdded() {
@@ -720,13 +720,13 @@ class InputLibraryTest {
val layout = copied.activeLayout(desktop, InputRole.SECONDARY)!!
assertNotEquals(source.id, layout.id)
assertEquals(source.id, layout.origin)
assertFalse(copied.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements, copied.compileStock(desktop)))
assertFalse(copied.compileActive(desktop).showsLeftMouseButton(InputRole.SECONDARY, layout.elements, copied.compileStock(desktop)))
val added = InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f, id = "custom:added")
val grown = copied.withLayout(layout.copy(elements = layout.elements + added))
val bindings = grown.activePart(desktop, InputRole.SECONDARY).bindings
val bound = grown.withPreset(grown.preset(bindings).let { it.copy(elements = it.elements + (added.id to InputAction.MouseButton(272))) })
assertTrue(bound.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements + added, bound.compileStock(desktop)))
assertFalse(bound.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements, bound.compileStock(desktop)))
assertTrue(bound.compileActive(desktop).showsLeftMouseButton(InputRole.SECONDARY, layout.elements + added, bound.compileStock(desktop)))
assertFalse(bound.compileActive(desktop).showsLeftMouseButton(InputRole.SECONDARY, layout.elements, bound.compileStock(desktop)))
}
}
}
@@ -15,57 +15,73 @@ class OnScreenMouseButtonTest {
private fun profile(vararg elements: Pair<String, InputAction>, clicks: Map<String, InputAction> = emptyMap(), base: InputProfile = game) =
base.copy(elements = mapOf(InputRole.PRIMARY to elements.toMap()), clicks = mapOf(InputRole.PRIMARY to clicks))
@Test fun shownButtonBoundToAMouseButtonIsDetected() {
listOf(272, 273, 274).forEach { code ->
assertTrue(profile(button.id to InputAction.MouseButton(code)).showsMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
@Test fun shownButtonBoundToTheLeftMouseButtonIsDetected() {
assertTrue(profile(button.id to InputAction.MouseButton(272)).showsLeftMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
}
@Test fun rightOrMiddleMouseButtonAloneKeepsTapsClicking() {
listOf(273, 274, 275, 276).forEach { code ->
assertFalse(profile(button.id to InputAction.MouseButton(code)).showsLeftMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
val stickClick = profile(stick.id to InputAction.Native(), clicks = mapOf(stick.id to InputAction.MouseButton(code)))
assertFalse(stickClick.showsLeftMouseButton(InputRole.PRIMARY, listOf(stick), game))
assertFalse(game.withBinding(InputRole.PRIMARY, InputControl.A, InputAction.MouseButton(code)).showsLeftMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
}
}
@Test fun rightButtonNextToALeftButtonStillStopsTapClicks() {
val right = InputSurfaceElement(InputControl.B, .7f, .6f, .1f, .1f, id = "custom:right")
val both = profile(button.id to InputAction.MouseButton(272), right.id to InputAction.MouseButton(273))
assertTrue(both.showsLeftMouseButton(InputRole.PRIMARY, listOf(button, right), game))
assertFalse(both.showsLeftMouseButton(InputRole.PRIMARY, listOf(right), game))
}
@Test fun stickClickBoundToAMouseButtonIsDetected() {
val profile = profile(stick.id to InputAction.Native(), clicks = mapOf(stick.id to InputAction.MouseButton(272)))
assertTrue(profile.showsMouseButton(InputRole.PRIMARY, listOf(stick), game))
assertTrue(profile.showsLeftMouseButton(InputRole.PRIMARY, listOf(stick), game))
}
@Test fun legacyButtonUsesItsRoleBinding() {
val profile = game.withBinding(InputRole.PRIMARY, InputControl.A, InputAction.MouseButton(272))
assertTrue(profile.showsMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
assertFalse(profile.showsMouseButton(InputRole.SECONDARY, listOf(legacyA), game))
assertTrue(profile.showsLeftMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
assertFalse(profile.showsLeftMouseButton(InputRole.SECONDARY, listOf(legacyA), game))
}
@Test fun stockDesktopOverlayKeepsTapsClicking() {
assertFalse(desktop.showsMouseButton(InputRole.PRIMARY, overlay, desktop))
assertFalse(desktop.showsLeftMouseButton(InputRole.PRIMARY, overlay, desktop))
}
@Test fun userBoundMouseButtonInDesktopIsDetected() {
val rebound = desktop.withBinding(InputRole.PRIMARY, InputControl.X, InputAction.MouseButton(272))
assertTrue(rebound.showsMouseButton(InputRole.PRIMARY, overlay, desktop))
val stickClick = desktop.withBinding(InputRole.PRIMARY, InputControl.L3, InputAction.MouseButton(274))
assertTrue(stickClick.showsMouseButton(InputRole.PRIMARY, overlay, desktop))
assertTrue(profile(button.id to InputAction.MouseButton(272), base = desktop).showsMouseButton(InputRole.PRIMARY, overlay + button, desktop))
assertTrue(rebound.showsLeftMouseButton(InputRole.PRIMARY, overlay, desktop))
val stickClick = desktop.withBinding(InputRole.PRIMARY, InputControl.L3, InputAction.MouseButton(272))
assertTrue(stickClick.showsLeftMouseButton(InputRole.PRIMARY, overlay, desktop))
val middleStickClick = desktop.withBinding(InputRole.PRIMARY, InputControl.L3, InputAction.MouseButton(274))
assertFalse(middleStickClick.showsLeftMouseButton(InputRole.PRIMARY, overlay, desktop))
assertTrue(profile(button.id to InputAction.MouseButton(272), base = desktop).showsLeftMouseButton(InputRole.PRIMARY, overlay + button, desktop))
}
@Test fun desktopBindingsOnAGameBaseProfileAreUserPicked() {
val copied = desktop.copy(id = "custom")
assertTrue(copied.showsMouseButton(InputRole.PRIMARY, overlay, game))
assertTrue(copied.showsLeftMouseButton(InputRole.PRIMARY, overlay, game))
}
@Test fun layoutWithoutAMouseButtonKeepsTapsClicking() {
val profile = profile(button.id to InputAction.Keys(listOf(57)), stick.id to InputAction.Pointer())
assertFalse(profile.showsMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
assertFalse(game.showsMouseButton(InputRole.PRIMARY, listOf(legacyA, stick) + overlay, game))
assertFalse(profile.showsLeftMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
assertFalse(game.showsLeftMouseButton(InputRole.PRIMARY, listOf(legacyA, stick) + overlay, game))
}
@Test fun hiddenMouseButtonDoesNotCount() {
assertFalse(profile(button.id to InputAction.MouseButton(272)).showsMouseButton(InputRole.PRIMARY, listOf(stick), game))
assertFalse(profile(button.id to InputAction.MouseButton(272)).showsMouseButton(InputRole.PRIMARY, emptyList(), game))
assertFalse(profile(button.id to InputAction.MouseButton(272)).showsLeftMouseButton(InputRole.PRIMARY, listOf(stick), game))
assertFalse(profile(button.id to InputAction.MouseButton(272)).showsLeftMouseButton(InputRole.PRIMARY, emptyList(), game))
}
@Test fun physicalMouseBindingsDoNotCount() {
val profile = game.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.MouseButton(272))
assertFalse(profile.showsMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
assertFalse(profile.showsLeftMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
}
@Test fun invalidMouseCodeDoesNotCount() {
assertFalse(profile(button.id to InputAction.MouseButton(1)).showsMouseButton(InputRole.PRIMARY, listOf(button), game))
assertFalse(profile(button.id to InputAction.MouseButton(1)).showsLeftMouseButton(InputRole.PRIMARY, listOf(button), game))
}
}
@@ -45,7 +45,7 @@ class NativeGuestTest {
val command = NativeGuest.command(root, "/usr/bin/env", listOf("-i", "A=1"))
assertEquals(File(root, "usr/lib/ld-linux-aarch64.so.1").path, command[0])
assertEquals(listOf("--library-path", NativeGuest.libraryPath(root), "--argv0", "env", File(root, "usr/bin/env").path, "-i", "A=1"), command.drop(1))
assertTrue("LD_LIBRARY_PATH" !in NativeGuest.environment(root))
assertTrue("LD_LIBRARY_PATH" !in NativeGuest.environment(root, "/usr/bin/env"))
}
@Test
@@ -79,13 +79,22 @@ class NativeGuestTest {
@Test
fun mountsWithoutADestinationMapToThemselves() {
val root = rootWithLoader()
val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b"))
val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b"), "/usr/bin/env")
assertEquals("/dev:/dev|/a:/b", env["DDNATV_BINDS"])
assertEquals(root.path, env["DDNATV_ROOT"])
assertTrue("LD_LIBRARY_PATH" !in env)
assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so"))
}
@Test
fun theProgramTheLoaderRunsIsNamedInItsEnvironment() {
val root = rootWithLoader()
val program = NativeGuest.command(root, "/usr/bin/env", listOf("-i"))[5]
assertEquals(program, NativeGuest.sessionEnvironment(root, listOf("/dev"), "/usr/bin/env")["DDNATV_REAL_EXE"])
assertEquals(program, NativeGuest.environment(root, "/usr/bin/env")["DDNATV_REAL_EXE"])
assertEquals(program, NativeGuest.builder(root, "/", listOf("/usr/bin/env", "-i"), emptyMap()).environment()["DDNATV_REAL_EXE"])
}
private val linkRoot = "/data/user/0/app/files/linuxfs"
private val sdBinds = listOf(
"/mnt/media_rw/CARD/files/steam:/mnt/droiddeck-sd",
@@ -0,0 +1,139 @@
package com.droiddeck.launcher.session
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
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 java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class ComponentsBionicFexTest {
private val bionicTool = "DroidDeck-Bionic-12.8-r24"
private val ownTool = "DroidDeck-Proton-11-12.8"
private fun proton(dir: String, valve: Boolean = false) =
ComponentsManager.Proton(dir, dir, File("/steam/compatibilitytools.d/$dir"), "/p/$dir", "$dir-1", valve)
private fun item(file: String, release: String) = ComponentsManager.CatalogItem(file, "fex", release, "", 1, "")
@Test fun onlyBionicNamedPackagesFitDroidDeckBionic() {
assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-bionic.wcp"))
assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-PPA-BIONIC.WCP"))
assertFalse(ComponentsManager.bionicFex("FEXCore-2611.1-linux.wcp"))
assertFalse(ComponentsManager.bionicFex("DD-FEXCore-2611+51-nightly.wcp"))
assertFalse(ComponentsManager.bionicFex("bionic-FEXCore-2611.wcp"))
assertTrue(ComponentsManager.bionicTool(bionicTool))
assertFalse(ComponentsManager.bionicTool(ownTool))
assertFalse(ComponentsManager.bionicTool("GE-Proton10-25"))
assertFalse(ComponentsManager.bionicTool(null))
assertTrue(ComponentsManager.fexFits(bionicTool, "FEXCore-2611-bionic.wcp"))
assertFalse(ComponentsManager.fexFits(bionicTool, "FEXCore-2611-linux.wcp"))
assertFalse(ComponentsManager.fexFits(bionicTool, "DD-FEXCore-2611+51-nightly.wcp"))
assertTrue(ComponentsManager.fexFits(ownTool, "DD-FEXCore-2611+51-nightly.wcp"))
assertTrue(ComponentsManager.fexFits(ownTool, "FEXCore-2611-linux.wcp"))
assertFalse(ComponentsManager.fexFits(ownTool, "FEXCore-2611-bionic.wcp"))
assertFalse(ComponentsManager.fexFits(null, "FEXCore-2611-bionic.wcp"))
}
@Test fun aTwinSwapsTheLinuxAndBionicEnding() {
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.fexTwin("FEXCore-2611.1-linux.wcp"))
assertEquals("FEXCore-2611.1-linux.wcp", ComponentsManager.fexTwin("FEXCore-2611.1-bionic.wcp"))
assertEquals("FEXCore-2611-PPA-bionic.wcp", ComponentsManager.fexTwin("FEXCore-2611-PPA-linux.wcp"))
assertNull(ComponentsManager.fexTwin("DD-FEXCore-2611+51-nightly.wcp"))
assertNull(ComponentsManager.fexTwin("my-fex.wcp"))
}
@Test fun aLaunchTakesTheChoiceOrItsStoredTwinForEachFlavor() {
val stored = setOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "FEXCore-2610-linux.wcp")
val has: (String) -> Boolean = { it in stored }
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.launchFex(bionicTool, "FEXCore-2611.1-linux.wcp", has))
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.launchFex(bionicTool, "FEXCore-2611.1-bionic.wcp", has))
assertEquals("FEXCore-2611.1-linux.wcp", ComponentsManager.launchFex(ownTool, "FEXCore-2611.1-bionic.wcp", has))
assertEquals("FEXCore-2610-linux.wcp", ComponentsManager.launchFex(ownTool, "FEXCore-2610-linux.wcp", has))
assertEquals("DD-FEXCore-2611+51-nightly.wcp", ComponentsManager.launchFex(ownTool, "DD-FEXCore-2611+51-nightly.wcp", has))
assertNull(ComponentsManager.launchFex(bionicTool, "FEXCore-2610-linux.wcp", has))
assertNull(ComponentsManager.launchFex(bionicTool, "DD-FEXCore-2611+51-nightly.wcp", has))
}
@Test fun fexListsShowTheProtonsFlavorAndTheCurrentChoice() {
val files = listOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "DD-FEXCore-2611+51-nightly.wcp", "FEXCore-2610-bionic.wcp")
assertEquals(listOf("FEXCore-2611.1-bionic.wcp", "FEXCore-2610-bionic.wcp"), ComponentsManager.forTool("fex", bionicTool, files) { it })
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "DD-FEXCore-2611+51-nightly.wcp"), ComponentsManager.forTool("fex", ownTool, files) { it })
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "DD-FEXCore-2611+51-nightly.wcp"), ComponentsManager.forTool("fex", null, files) { it })
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "FEXCore-2610-bionic.wcp"),
ComponentsManager.forTool("fex", bionicTool, files, selected = "FEXCore-2611.1-linux.wcp") { it })
assertEquals(files, ComponentsManager.forTool("dxvk", bionicTool, files) { it })
}
@Test fun bionicStableAssetsAreFex() {
assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_BIONIC, "FEXCore-2611.1-bionic.wcp"))
assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_BIONIC, "FEXCore-2610-PPA-bionic.wcp"))
assertEquals("fex", ComponentsManager.assetComp("FexCore-Linux", "FEXCore-2611.1-linux.wcp"))
}
@Test fun aGameFexChoiceKeepsItsTwinInUseWhileTheOtherFlavorIsInstalled() {
val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp")))
assertEquals(setOf("FEXCore-2611.1-linux.wcp"), ComponentsManager.packagesInUse(state, listOf(proton(ownTool))))
assertEquals(setOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp"),
ComponentsManager.packagesInUse(state, listOf(proton(ownTool), proton(bionicTool))))
}
@Test fun aTwinAGameChoiceStillNeedsCannotBeDeletedAsUnused() {
val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp")))
assertEquals(bionicTool, ComponentsManager.twinUser(state, listOf(proton(ownTool), proton(bionicTool)), "FEXCore-2611.1-bionic.wcp")?.dir?.name)
assertEquals(null, ComponentsManager.twinUser(state, listOf(proton(ownTool)), "FEXCore-2611.1-bionic.wcp"))
assertEquals(null, ComponentsManager.twinUser(state, listOf(proton(ownTool), proton(bionicTool)), "FEXCore-2610-bionic.wcp"))
assertEquals(null, ComponentsManager.twinUser(JSONObject(), listOf(proton(bionicTool)), "FEXCore-2611.1-bionic.wcp"))
}
@Test fun droidDeckBionicFollowsTheNewestBionicFexAndNothingElse() {
val bionic = proton(bionicTool)
val own = proton(ownTool)
assertTrue(ComponentUpdates.autoFollows(bionic, "fex"))
assertFalse(ComponentUpdates.autoFollows(bionic, "dxvk"))
assertFalse(ComponentUpdates.autoFollows(bionic, "vkd3d"))
assertFalse(ComponentUpdates.autoFollows(proton(bionicTool, valve = true), "fex"))
assertFalse(ComponentUpdates.follows(bionic))
assertTrue(ComponentUpdates.autoFollows(own, "dxvk"))
assertFalse(ComponentUpdates.autoFollows(proton("GE-Proton10-25"), "fex"))
assertEquals("fex-bionic", ComponentUpdates.fexLine(bionic).key)
assertEquals("fex", ComponentUpdates.fexLine(own).key)
assertEquals("fex", ComponentUpdates.line("fex", false).key)
val catalog = listOf(
item("DD-FEXCore-2611+51-nightly.wcp", ComponentsManager.DD_NIGHTLY),
item("DD-FEXCore-2611+52-bionic.wcp", ComponentsManager.DD_NIGHTLY),
item("FEXCore-2611.1-linux.wcp", "FexCore-Linux"),
item("FEXCore-2610-bionic.wcp", ComponentsManager.DD_BIONIC),
item("FEXCore-2611-PPA-bionic.wcp", ComponentsManager.DD_BIONIC),
item("FEXCore-2611.1-bionic.wcp", ComponentsManager.DD_BIONIC),
)
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(bionic), emptySet())?.file)
assertNull(ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(bionic), setOf("FEXCore-2611.1-bionic.wcp")))
assertEquals("DD-FEXCore-2611+51-nightly.wcp", ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(own), emptySet())?.file)
}
@Test fun pruningTheBionicLineKeepsBionicPackagesTheUserDownloaded() {
val line = ComponentUpdates.fexLine(proton(bionicTool))
val current = "FEXCore-2611.1-bionic.wcp"
val stored = listOf("FEXCore-2610-bionic.wcp", "FEXCore-2611-PPA-bionic.wcp", current, "FEXCore-2610-linux.wcp")
assertEquals(listOf("FEXCore-2610-bionic.wcp"),
ComponentUpdates.stale(line, setOf("FEXCore-2610-bionic.wcp", current), stored, setOf(current), current))
}
@Test fun aBionicProtonsOwnFexChoiceIsNotHandedBack() {
val bionic = proton(bionicTool)
val choices = mapOf(bionic.id to mapOf(
"fex" to ComponentsManager.Choice("FEXCore-2611.1-bionic.wcp", false, bionic.version),
"dxvk" to ComponentsManager.Choice("DD-dxvk-3.1.1+190-nightly.wcp", false, bionic.version),
))
assertEquals(listOf(bionic to "dxvk"),
ComponentUpdates.strays(listOf(bionic), choices, setOf("FEXCore-2611.1-bionic.wcp", "DD-dxvk-3.1.1+190-nightly.wcp")))
}
}
@@ -8,6 +8,7 @@ import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
@@ -23,6 +24,7 @@ class ComponentsRepublishTest {
private val fex = "FEXCore-2610-d2rfix28-linux.wcp"
private val scope = "2596113170"
private val dll = "files/lib/wine/aarch64-windows/libwow64fex.dll"
private val so = "files/lib/wine/aarch64-unix/libwow64fex.so"
private lateinit var context: Context
@Before fun setUp() {
@@ -48,6 +50,61 @@ class ComponentsRepublishTest {
assertEquals(fex, ComponentsManager.gameComponents(context, scope)["fex"])
}
@Test fun aGlibcGameFexChoiceWithoutItsTwinLeavesDroidDeckBionicOnItsOwnFex() {
proton("DroidDeck-Proton 11-12.8", "DroidDeck-Proton-11-12.8")
proton("DroidDeck-Bionic-12.8-r6", "DroidDeck-Bionic-12.8-r6")
packageFile()
ComponentsManager.setGameComponent(context, scope, "fex", fex) { false }
assertEquals(setOf("DroidDeck-Proton 11-12.8"), scopedTools())
val bionic = rows().filter { it[1] == "DroidDeck-Bionic-12.8-r6" && it[3] == "fex" }
assertTrue(bionic.isNotEmpty())
assertTrue(bionic.all { it[0] == "*" && "/store/original-DroidDeck-Bionic-12.8-r6-" in it[6] })
}
@Test fun aGameFexChoiceReachesEachProtonAsTheBuildOfItsFlavor() {
proton("DroidDeck-Proton-11-12.8", "DroidDeck-Proton-11-12.8")
proton("DroidDeck-Bionic-12.8-r24", "DroidDeck-Bionic-12.8-r24")
val linux = "FEXCore-2611.1-linux.wcp"
val bionic = "FEXCore-2611.1-bionic.wcp"
packageFile(linux, "FEXCore-Linux", "glibc wow64")
packageFile(bionic, "FEXCore-Bionic", "android wow64")
for (choice in listOf(linux, bionic)) {
ComponentsManager.setGameComponent(context, scope, "fex", choice) { false }
val scoped = rows().filter { it[0] == scope && it[3] == "fex" }
val own = scoped.single { it[1] == "DroidDeck-Proton-11-12.8" && it[4] == dll }
val android = scoped.single { it[1] == "DroidDeck-Bionic-12.8-r24" && it[4] == dll }
assertEquals("glibc wow64", File(LinuxRuntime.rootDir(context), own[6].removePrefix("/")).readText())
assertEquals("android wow64", File(LinuxRuntime.rootDir(context), android[6].removePrefix("/")).readText())
assertTrue(scoped.any { it[1] == "DroidDeck-Proton-11-12.8" && it[6] == "-" })
assertTrue(scoped.none { it[1] == "DroidDeck-Bionic-12.8-r24" && it[6] == "-" })
assertEquals(choice, ComponentsManager.gameComponents(context, scope)["fex"])
}
}
@Test fun aProtonsFexIsOnlyEverSwappedToABuildOfItsFlavor() {
proton("DroidDeck-Proton-11-12.8", "DroidDeck-Proton-11-12.8")
proton("DroidDeck-Bionic-12.8-r24", "DroidDeck-Bionic-12.8-r24")
val linux = "FEXCore-2611.1-linux.wcp"
val bionic = "FEXCore-2611.1-bionic.wcp"
packageFile(linux, "FEXCore-Linux", "glibc wow64")
packageFile(bionic, "FEXCore-Bionic", "android wow64")
val bionicDll = File(protonDir("DroidDeck-Bionic-12.8-r24"), dll)
val ownDll = File(protonDir("DroidDeck-Proton-11-12.8"), dll)
assertThrows(IllegalStateException::class.java) { ComponentsManager.swap(context, "DroidDeck-Bionic-12.8-r24", linux) }
assertThrows(IllegalStateException::class.java) { ComponentsManager.swap(context, "DroidDeck-Proton-11-12.8", bionic) }
assertEquals("bundled FEX DroidDeck-Bionic-12.8-r24", bionicDll.readText())
assertEquals("bundled FEX DroidDeck-Proton-11-12.8", ownDll.readText())
ComponentsManager.swap(context, "DroidDeck-Bionic-12.8-r24", bionic)
ComponentsManager.swap(context, "DroidDeck-Proton-11-12.8", linux)
assertEquals("android wow64", bionicDll.readText())
assertEquals("glibc wow64", ownDll.readText())
assertTrue(File(protonDir("DroidDeck-Bionic-12.8-r24"), so).isFile)
assertTrue(rows().none { it[1] == "DroidDeck-Bionic-12.8-r24" && it[3] == "fex" && it[6] == "-" })
}
@Test fun nothingIsRewrittenWhileTheToolsAreUnchanged() {
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
packageFile()
@@ -117,18 +174,21 @@ class ComponentsRepublishTest {
private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv")
private fun protonDir(name: String) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
private fun proton(name: String, version: String) {
val dir = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
val dir = protonDir(name)
File(dir, "files/lib/wine").mkdirs()
File(dir, "proton").writeText("#!/bin/sh\n")
File(dir, "version").writeText("1 $version\n")
File(dir, dll).apply { parentFile!!.mkdirs(); writeText("bundled FEX $version") }
File(dir, so).apply { parentFile!!.mkdirs(); writeText("bundled unix FEX $version") }
}
private fun packageFile() {
val out = File(context.filesDir, "components/packages/$fex").apply { parentFile!!.mkdirs() }
val profile = JSONObject().put("type", "FEXCore-Linux").put("versionName", "2610-d2rfix28").toString().toByteArray()
val body = "d2rfix28 wow64".toByteArray()
private fun packageFile(name: String = fex, type: String = "FEXCore-Linux", text: String = "d2rfix28 wow64") {
val out = File(context.filesDir, "components/packages/$name").apply { parentFile!!.mkdirs() }
val profile = JSONObject().put("type", type).put("versionName", name.removeSuffix(".wcp")).toString().toByteArray()
val body = text.toByteArray()
TarArchiveOutputStream(ZstdOutputStream(out.outputStream())).use { tar ->
tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() })
tar.write(profile)
@@ -0,0 +1,191 @@
package com.droiddeck.launcher.session
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeFalse
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class CpuCacheSysfsTest {
@get:Rule val tmp = TemporaryFolder()
private fun cache(host: File, cpu: Int, vararg levels: Pair<Int, String?>) {
levels.forEachIndexed { i, (level, size) ->
val index = File(host, "cpu$cpu/cache/index$i").apply { mkdirs() }
File(index, "level").writeText("$level\n")
File(index, "type").writeText(if (level == 1) "Data\n" else "Unified\n")
File(index, "shared_cpu_list").writeText("$cpu\n")
if (size != null) File(index, "size").writeText(size)
}
}
@Test fun everyLevelReportsTheSizeTheEmulatedCpuidReports() {
val host = tmp.newFolder("host")
cache(host, 0, 1 to null, 2 to null, 3 to null)
val root = tmp.newFolder("out")
val out = File(root, "p/1")
val binds = CpuCacheSysfs.binds(root, 1, host, "p")
assertEquals(listOf(File(out, "cpu0").path + ":" + File(host, "cpu0/cache").path), binds)
assertEquals("32K\n", File(out, "cpu0/index0/size").readText())
assertEquals("512K\n", File(out, "cpu0/index1/size").readText())
assertEquals("8192K\n", File(out, "cpu0/index2/size").readText())
assertEquals("2\n", File(out, "cpu0/index1/level").readText())
assertEquals("Unified\n", File(out, "cpu0/index1/type").readText())
}
@Test fun aKernelSizeThatDisagreesWithTheEmulatedCpuidIsReplaced() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to "12288K\n")
val root = tmp.newFolder("out")
val out = File(root, "p/1")
CpuCacheSysfs.binds(root, 1, host, "p")
assertEquals("512K\n", File(out, "cpu0/index0/size").readText())
assertEquals("12288K\n", File(host, "cpu0/cache/index0/size").readText())
}
@Test fun everyCoreIsBoundAndACoreWithoutCacheInfoIsLeftAlone() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
cache(host, 1, 2 to null)
File(host, "cpu2").mkdirs()
File(host, "cpufreq").mkdirs()
val root = tmp.newFolder("out")
val out = File(root, "p/1")
val binds = CpuCacheSysfs.binds(root, 1, host, "p")
assertEquals(2, binds.size)
assertFalse(File(out, "cpu2").exists())
assertTrue(binds.none { it.contains("cpufreq") })
}
@Test fun aLevelOutsideTheEmulatedCpuidIsNotGivenASize() {
val host = tmp.newFolder("host")
cache(host, 0, 4 to null)
val root = tmp.newFolder("out")
val out = File(root, "p/1")
assertEquals(emptyList<String>(), CpuCacheSysfs.binds(root, 1, host, "p"))
assertFalse(File(out, "cpu0/index0/size").exists())
}
@Test fun stalePreviousSessionFilesAreRemoved() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
val out = File(root, "p/1")
File(out, "cpu7/index0").mkdirs()
CpuCacheSysfs.binds(root, 1, host, "p")
assertFalse(File(out, "cpu7").exists())
}
@Test fun aLinkLeftInTheStagedFolderIsRemovedWithoutTouchingItsTarget() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val kept = tmp.newFolder("kept")
File(kept, "file").writeText("x")
val root = tmp.newFolder("out")
val out = File(root, "p/1")
File(out, "cpu0").mkdirs()
Files.createSymbolicLink(File(out, "cpu0/link").toPath(), kept.toPath())
CpuCacheSysfs.binds(root, 1, host, "p")
assertFalse(Files.exists(File(out, "cpu0/link").toPath(), LinkOption.NOFOLLOW_LINKS))
assertEquals("x", File(kept, "file").readText())
}
@Test fun anUnreadableHostLeavesNoBinds() {
assertEquals(emptyList<String>(), CpuCacheSysfs.binds(tmp.newFolder("out"), 1, File(tmp.root, "missing"), "p"))
}
@Test fun earlierProcessesAndTheFlatLayoutAreRemoved() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
listOf("cpu0", "7", "old/1").forEach { File(root, "$it/cpu0/index0").mkdirs() }
val binds = CpuCacheSysfs.binds(root, 3, host, "p")
assertEquals(listOf(File(root, "p/3/cpu0").path + ":" + File(host, "cpu0/cache").path), binds)
assertEquals(listOf("p"), root.list()!!.toList())
}
@Test fun aDelayedEarlierStartKeepsTheNewerStartsSources() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
CpuCacheSysfs.binds(root, 2, host, "p")
CpuCacheSysfs.binds(root, 1, host, "p")
assertEquals("512K\n", File(root, "p/2/cpu0/index0/size").readText())
assertEquals("512K\n", File(root, "p/1/cpu0/index0/size").readText())
}
@Test fun aNewerStartKeepsTheEarlierStartsSources() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
CpuCacheSysfs.binds(root, 1, host, "p")
CpuCacheSysfs.binds(root, 2, host, "p")
assertEquals("512K\n", File(root, "p/1/cpu0/index0/size").readText())
assertEquals("512K\n", File(root, "p/2/cpu0/index0/size").readText())
}
@Test fun startsInOneProcessNeverShareAStagingFolder() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
val first = CpuCacheSysfs.binds(root, host = host, process = "p").single().substringBefore(':')
val second = CpuCacheSysfs.binds(root, host = host, process = "p").single().substringBefore(':')
assertTrue(first != second)
assertEquals("512K\n", File(first, "index0/size").readText())
assertEquals("512K\n", File(second, "index0/size").readText())
}
@Test fun aDelayedWorkerFromARecreatedServiceKeepsItsOwnFolder() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
val ready = java.util.concurrent.CountDownLatch(2)
val pool = java.util.concurrent.Executors.newFixedThreadPool(2)
try {
val starts = List(2) {
pool.submit<String> {
ready.countDown()
ready.await()
CpuCacheSysfs.binds(root, host = host, process = "p").single().substringBefore(':')
}
}.map { it.get(10, java.util.concurrent.TimeUnit.SECONDS) }
assertEquals(2, starts.toSet().size)
starts.forEach { assertEquals("512K\n", File(it, "index0/size").readText()) }
} finally {
pool.shutdownNow()
}
}
@Test fun aCoreWhoseMetadataCannotBeCopiedIsSkippedAndTheOthersStayBound() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
cache(host, 1, 2 to null, 4 to "1024K\n")
val locked = File(host, "cpu1/cache/index1/size")
locked.setReadable(false)
assumeFalse(locked.canRead())
val root = tmp.newFolder("out")
val binds = CpuCacheSysfs.binds(root, 1, host, "p")
assertEquals(listOf(File(root, "p/1/cpu0").path + ":" + File(host, "cpu0/cache").path), binds)
}
@Test fun anUnreadableKernelSizeForAnEmulatedLevelIsStillReplaced() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to "12288K\n")
val locked = File(host, "cpu0/cache/index0/size")
locked.setReadable(false)
assumeFalse(locked.canRead())
val root = tmp.newFolder("out")
assertEquals(1, CpuCacheSysfs.binds(root, 1, host, "p").size)
assertEquals("512K\n", File(root, "p/1/cpu0/index0/size").readText())
}
}
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.gpu.TurnipDriver
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class DisplayDriverFromAutoTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun noDisplayDriverChoiceIsAuto() {
SessionPrefs.setAndroidDriver(context, TurnipDriver.AUTO)
for (mode in listOf(SessionPrefs.GPU_DRIVERS_AUTO, SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.GPU_DRIVERS_MIX)) {
SessionPrefs.setGpuDriverMode(context, mode)
assertTrue(mode, SessionPrefs.displayDriverFromAuto(context))
}
}
@Test fun aPairDisplayHalfInstalledByAutoIsAuto() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0", "DD-Turnip_v0.8.0-linux"))
SessionPrefs.setAndroidDriver(context, "DD-Turnip_v0.8.0")
assertTrue(SessionPrefs.displayDriverFromAuto(context))
}
@Test fun aDriverTheUserImportedStaysTheirChoiceUnderAuto() {
SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO)
SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0"))
SessionPrefs.setAndroidDriver(context, "user-import")
assertFalse(SessionPrefs.displayDriverFromAuto(context))
}
@Test fun anAutoInstalledDriverPickedByHandStaysTheUsersChoice() {
SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0"))
SessionPrefs.setAndroidDriver(context, "DD-Turnip_v0.8.0")
for (mode in listOf(SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.GPU_DRIVERS_MIX)) {
SessionPrefs.setGpuDriverMode(context, mode)
assertFalse(mode, SessionPrefs.displayDriverFromAuto(context))
}
}
}
@@ -98,6 +98,22 @@ class EnhancedSessionLogShareTest {
SessionLogShare.clear(app)
}
@Test fun aBionicGameLogIsSharedWithTheGamesUnderItsName() {
val session = tmp.newFolder("2026-11-22-09-steam")
session.resolve("session.log").writeText("startup ok\n")
val launch = session.resolve("games/2026-11-22-201105-bionic-341940").apply { mkdirs() }
launch.resolve("droiddeck-bionic.log").writeText("20:11:05 waitforexitandrun Hatred.exe\n")
val games = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-games.zip") }
ZipFile(games).use { archive ->
val entry = archive.getEntry("${session.name}/games/2026-11-22-201105-bionic-341940/droiddeck-bionic.log")
assertTrue(entry != null)
assertEquals("20:11:05 waitforexitandrun Hatred.exe\n", archive.getInputStream(entry).bufferedReader().readText())
}
SessionLogShare.clear(app)
}
@Test fun oversizedFilesKeepBoundedBeginningAndTailAndDeclareTruncation() {
val session = tmp.newFolder("2026-11-04-02-game")
session.resolve("steam-7.log").writeText("begin\n" + "middle\n".repeat(100) + "tail\n")
@@ -403,6 +419,23 @@ class EnhancedSessionLogShareTest {
SessionLogShare.clear(app)
}
@Test fun rpcs3LogIsSharedByNameWithTheGameLogs() {
val session = tmp.newFolder("2026-11-24-05-rpcs3")
session.resolve("session.log").writeText("session\n")
session.resolve("rpcs3").mkdirs()
session.resolve("rpcs3/RPCS3.log").writeText("PPU: compiling\n")
val zips = EnhancedSessionLogShare.create(app, session)
fun entries(suffix: String) = ZipFile(zips.single { it.name.endsWith("-$suffix.zip") }).use { archive ->
archive.entries().toList().map { it.name }
}
assertTrue(entries("games").contains("${session.name}/rpcs3/RPCS3.log"))
assertTrue(entries("session").contains("${session.name}/session.log"))
assertFalse(entries("games").contains("${session.name}/session.log"))
SessionLogShare.clear(app)
}
@Test fun unreadableDiscoverySubtreeKeepsOtherLogsAndMarksTheManifestPartial() {
assumeFilePermissionsEnforced()
assumeFalse(System.getProperty("os.name").startsWith("Windows"))
@@ -68,6 +68,19 @@ class ExperimentalProtonsTest {
assertEquals(listOf("pre"), ProtonExtras.assets(tool, releases, true).map { it.tag })
}
@Test
fun bionicBuildsKeepTheirOwnRow() {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val releases = JSONArray("""
[{"tag_name":"DroidDeck-Proton-11-12.8","prerelease":false,"published_at":"2026-11-14T00:00:00Z","assets":[{"name":"DroidDeck-Proton-11-12.8-aarch64.tar.gz","browser_download_url":"https://example/stable"}]},
{"tag_name":"DroidDeck-Bionic-12.8-r37","prerelease":true,"published_at":"2026-11-19T00:00:00Z","assets":[{"name":"DroidDeck-Bionic-12.8-r37-aarch64.tar.xz","browser_download_url":"https://example/bionic"}]},
{"tag_name":"DroidDeck-Proton-11-12.9-test1","prerelease":true,"published_at":"2026-11-19T01:00:00Z","assets":[{"name":"DroidDeck-Proton-11-12.9-test1-aarch64.tar.xz","browser_download_url":"https://example/test"}]}]
""".trimIndent())
val assets = ProtonExtras.assets(tool, releases, true)
assertEquals(listOf("DroidDeck-Bionic-12.8-r37", "DroidDeck-Proton-11-12.9-test1"), assets.map { it.tag })
assertEquals(listOf("DroidDeck-Proton-11-12.9-test1"), ExperimentalProtons.listed(assets).map { it.tag })
}
@Test
fun markerRoundTripKeepsReleaseTag() {
val dir = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d/Experimental-pre").apply { mkdirs() }
@@ -0,0 +1,121 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
class LaunchCoordinatorTest {
@Test
fun aNewLaunchSupersedesAnOlderLaunch() {
val coordinator = LaunchCoordinator<String, String>()
val first = coordinator.beginLaunch()
val second = coordinator.beginLaunch()
assertFalse(coordinator.isCurrent(first))
assertTrue(coordinator.isCurrent(second))
}
@Test
fun anAllowedLaunchDropsThePendingLink() {
val coordinator = LaunchCoordinator<String, String>()
coordinator.beginLink("link")
coordinator.beginLaunch()
assertFalse(coordinator.hasPending())
}
@Test
fun aLinkReadResolvesAndIsConsumed() {
val coordinator = LaunchCoordinator<String, String>()
val ticket = coordinator.beginLink("link")
assertTrue(coordinator.resolve(ticket, "game"))
assertEquals("game", coordinator.pendingLink()?.request)
assertTrue(coordinator.consume(ticket))
assertFalse(coordinator.hasPending())
}
@Test
fun aStaleLinkReadCannotReplaceTheNewLink() {
val coordinator = LaunchCoordinator<String, String>()
val first = coordinator.beginLink("first")
val second = coordinator.beginLink("second")
assertFalse(coordinator.resolve(first, "old"))
assertTrue(coordinator.resolve(second, "new"))
assertEquals("new", coordinator.pendingLink()?.request)
}
@Test
fun handlingNeedsAResolvedLink() {
val coordinator = LaunchCoordinator<String, String>()
val ticket = coordinator.beginLink("link")
assertFalse(coordinator.beginHandling(ticket))
coordinator.resolve(ticket, "game")
assertTrue(coordinator.beginHandling(ticket))
assertTrue(coordinator.isHandling(ticket))
}
@Test
fun aStaleCompletionCannotConsumeTheNewLink() {
val coordinator = LaunchCoordinator<String, String>()
val first = coordinator.beginLink("first")
val second = coordinator.beginLink("second")
coordinator.resolve(second, "new")
assertFalse(coordinator.consume(first))
assertTrue(coordinator.hasPending())
}
@Test
fun aUiLaunchDropsThePendingLinkBeforeItLaunches() {
val coordinator = LaunchCoordinator<String, String>()
coordinator.beginLink("link")
val launch = coordinator.beginLaunch()
assertNull(coordinator.pendingLink())
assertTrue(coordinator.isCurrent(launch))
}
@Test
fun aSecondLinkReplacesTheFirst() {
val coordinator = LaunchCoordinator<String, String>()
val first = coordinator.beginLink("first")
val second = coordinator.beginLink("second")
assertFalse(coordinator.isCurrent(first))
assertTrue(coordinator.isCurrent(second))
assertEquals("second", coordinator.pendingLink()?.owner)
}
@Test
fun aLinkKeepsItsOwnerForIntentCleanup() {
val coordinator = LaunchCoordinator<String, String>()
val ticket = coordinator.beginLink("intent-a")
coordinator.resolve(ticket, "game")
assertSame("intent-a", coordinator.pendingLink()?.owner)
}
@Test
fun aLinkIsOwnedOnlyByItsIntent() {
val coordinator = LaunchCoordinator<String, String>()
val ticket = coordinator.beginLink("intent-a")
coordinator.resolve(ticket, "game")
val link = requireNotNull(coordinator.pendingLink())
assertTrue(link.ownedBy("intent-a"))
assertFalse(link.ownedBy("intent-b"))
assertFalse(link.ownedBy(null))
assertTrue(coordinator.consume(ticket))
assertNull(coordinator.pendingLink())
}
@Test
fun cancelAllInvalidatesEveryOutstandingTicket() {
val coordinator = LaunchCoordinator<String, String>()
coordinator.beginLaunch()
val link = coordinator.beginLink("link")
assertTrue(coordinator.isCurrent(link))
coordinator.cancelAll()
assertFalse(coordinator.isCurrent(link))
assertFalse(coordinator.hasPending())
assertNull(coordinator.pendingLink())
assertFalse(coordinator.resolve(link, "late"))
assertFalse(coordinator.consume(link))
}
}
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.content.pm.ActivityInfo
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
@@ -74,6 +75,35 @@ class PortraitResolutionTest {
assertEquals("1440x2560", SessionPrefs.resolutionStored(app, "steam", panel, true))
}
@Test fun followScreenInLandscapeLeavesAFixedPortraitSizeFixed() {
SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.FOLLOW_SCREEN)
SessionPrefs.setResolutionChoice(app, "steam", "1024x768", portrait = true)
assertEquals(1f to null, SessionPrefs.followScales(app, "steam", panel))
}
@Test fun followScreenInPortraitLeavesAFixedLandscapeSizeFixed() {
SessionPrefs.setResolutionChoice(app, "steam", "1080p")
SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.followScaled(2f), portrait = true)
assertEquals(null to 2f, SessionPrefs.followScales(app, "steam", panel))
}
@Test fun followScalesKeepLinkedAndFixedChoices() {
SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.followScaled(1.5f))
assertEquals(1.5f to 1.5f, SessionPrefs.followScales(app, "steam", panel))
SessionPrefs.setResolutionChoice(app, "steam", "1024x768", portrait = true)
SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT)
assertEquals(null to null, SessionPrefs.followScales(app, "steam", panel))
app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
assertEquals(null to null, SessionPrefs.followScales(app, "steam", panel))
}
@Test fun anAutoOrientationIsNotChangedByFollowScreen() {
assertFalse(SessionPrefs.portrait(app))
SessionPrefs.setOrientation(app, ActivityInfo.SCREEN_ORIENTATION_USER)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(app, true, 700))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(app, false, 700))
}
@Test fun modesKeepSeparateChoices() {
SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true)
assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "lxqt", panel, true))
@@ -127,4 +127,90 @@ class ProtonDefaultTest {
assertTrue(games.containsKey("43"))
assertNull(games["43"])
}
@Test
fun anUpdateMovesTheDefaultThatNamesTheReplacedTool() {
val bionic = """
{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7, "live": false,
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false},
{"name": "DroidDeck-Proton-11-12.8", "display": "DD", "dir": "DroidDeck-Proton 11-12.8", "valve": false}]}
""".trimIndent()
val parsed = ProtonDefault.parseState(bionic)
val from = setOf("DroidDeck-Bionic-12.8-r30")
// applied default, no request yet
assertEquals(ProtonDefault.Request(100, false, "DroidDeck-Bionic-12.8-r31"),
ProtonDefault.movedDefault(parsed, null, from, "DroidDeck-Bionic-12.8-r31", 100))
// a pending request for the replaced tool wins over the applied default and the new seq is above both
assertEquals(ProtonDefault.Request(51, false, "DroidDeck-Bionic-12.8-r31"),
ProtonDefault.movedDefault(parsed, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r30"), from, "DroidDeck-Bionic-12.8-r31", 3))
// a default on another tool stays as it is
assertNull(ProtonDefault.movedDefault(parsed, ProtonDefault.Request(50, false, "DroidDeck-Proton 11-12.8"), from, "DroidDeck-Bionic-12.8-r31", 100))
assertNull(ProtonDefault.movedDefault(ProtonDefault.parseState(state), null, from, "DroidDeck-Bionic-12.8-r31", 100))
// an applied request (seq not above "applied") no longer decides: the applied default does
assertEquals("DroidDeck-Bionic-12.8-r31",
ProtonDefault.movedDefault(parsed, ProtonDefault.Request(7, false, "DroidDeck-Proton 11-12.8"), from, "DroidDeck-Bionic-12.8-r31", 1)?.dir)
}
@Test
fun aBionicDefaultOnAnotherBuildMovesToTheInstalledOne() {
val r37 = "DroidDeck-Bionic-12.8-r37"
val applied = ProtonDefault.parseState("""{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7,
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false},
{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
// the applied default is an older build
assertEquals(ProtonDefault.Request(100, false, r37), ProtonDefault.bionicDefault(applied, null, "DroidDeck-Bionic", r37, 100))
// the guest fell back to its own tool because the requested build was gone: the request still names it
val fallback = ProtonDefault.parseState("""{"default": "droiddeck-proton-arm64", "applied": 50, "source": "fallback",
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
assertEquals(ProtonDefault.Request(51, false, r37),
ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r24"), "DroidDeck-Bionic", r37, 3))
// already the installed build, another tool, or a fallback the request did not cause: left as it is
assertNull(ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, r37), "DroidDeck-Bionic", r37, 3))
assertNull(ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, "DroidDeck-Proton 11-12.8"), "DroidDeck-Bionic", r37, 3))
assertNull(ProtonDefault.bionicDefault(ProtonDefault.parseState(state), null, "DroidDeck-Bionic", r37, 100))
val steam = ProtonDefault.parseState("""{"default": "droiddeck-proton-arm64", "applied": 50, "source": "steam",
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
assertNull(ProtonDefault.bionicDefault(steam, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r24"), "DroidDeck-Bionic", r37, 3))
}
@Test
fun keepingBionicCurrentRewritesTheDefaultAndThePicks() {
val context = RuntimeEnvironment.getApplication()
val d = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat").apply { deleteRecursively(); mkdirs() }
File(d, "state.json").writeText("""{"default": "droiddeck-proton-arm64", "applied": 9, "source": "fallback",
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
File(d, "request.json").writeText("""{"seq": 9, "valve": false, "dir": "DroidDeck-Bionic-12.8-r24"}""")
ProtonDefault.requestGame(context, "42", proton("DroidDeck-Bionic-12.8-r29", false))
ProtonDefault.requestGame(context, "43", proton("DroidDeck-Proton 11-12.8", false))
ProtonDefault.requestGame(context, "44", null)
ProtonDefault.keepBionicCurrent(context, "DroidDeck-Bionic", "DroidDeck-Bionic-12.8-r37")
val request = ProtonDefault.parseRequest(File(d, "request.json").readText())
assertEquals("DroidDeck-Bionic-12.8-r37", request?.dir)
assertTrue(request!!.seq > 9)
val games = ProtonDefault.parseGames(File(d, "games.json").readText())
assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Bionic-12.8-r37"), games["42"])
assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-12.8"), games["43"])
assertTrue(games.containsKey("44"))
assertNull(games["44"])
val before = File(d, "request.json").readText() + File(d, "games.json").readText()
ProtonDefault.keepBionicCurrent(context, "DroidDeck-Bionic", "DroidDeck-Bionic-12.8-r37")
assertEquals(before, File(d, "request.json").readText() + File(d, "games.json").readText())
}
@Test
fun moveDefaultRewritesTheRequestFile() {
val context = RuntimeEnvironment.getApplication()
val d = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat").apply { mkdirs() }
File(d, "state.json").writeText("""{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7,
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false}]}""")
File(d, "request.json").delete()
ProtonDefault.moveDefault(context, setOf("DroidDeck-Bionic-12.8-r30"), "DroidDeck-Bionic-12.8-r31")
val written = ProtonDefault.parseRequest(File(d, "request.json").readText())
assertEquals("DroidDeck-Bionic-12.8-r31", written?.dir)
assertFalse(written!!.valve)
assertTrue(written.seq > 7)
val before = File(d, "request.json").readText()
ProtonDefault.moveDefault(context, setOf("DroidDeck-Bionic-12.8-r29"), "DroidDeck-Bionic-12.8-r31")
assertEquals(before, File(d, "request.json").readText())
}
}
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more