Compare commits

..
Author SHA1 Message Date
Kurt Himebauch fc9ae46bcd fix(recomps): list the catalog before checking game files, and give installed recomps their art 2026-12-01 17:50:20 -05:00
Kurt Himebauch a56d4e38be feat(recomps): Linux recomps become non-Steam games, and Android installs explain failures
Each Linux recomp gets a play script and becomes a native non-Steam
shortcut: written to the session's shortcut listing next to the Epic
launcher, added to a running Steam client at once, and removed with the
recomp. They also show in a Recomps chip in the Library and always start
as the Linux app. Windows recomps were already added games.

An APK without code for the device's CPUs (a 64-bit-only device and a
32-bit-only port) is stopped before Android's prompt, remembered as not
for this device, and skipped when choosing a build. Install failures say
what went wrong, name the game and stay on its page.

Also finds AppImage recomps again: the scan looked one folder too high.
2026-12-01 14:35:07 -05:00
Kurt Himebauch ed6b123984 feat(recomps): pick which build to install, and filter by the builds a project has
The detail page's builds are now choices: the main button installs the
picked build, or switches to it when another is installed, replacing the
old install (an Android app is left for the player to remove). A picked
build installs as listed, without swapping in an arm64 twin.

The Filter menu gains a 'Has a build for' group (Linux ARM64, Linux
x86-64, Windows, Android); like every filter they combine, so ticking all
three desktop builds leaves projects that publish all three.
2026-12-01 14:02:40 -05:00
Kurt Himebauch 611d2d75d1 feat(recomps): a Library-style grid with real sorting and filtering
The page now matches the Library: a ModeHeader with search and Filter,
Sort and Display buttons, box-art tiles sized like the Library's with
badges for installed, owned and updates, and a detail page per recomp
for what it needs, its builds and its actions. Filters combine and show
as removable chips; sorts are best for you, popularity, recently updated,
newly listed and A-Z. A row of original systems stays under the header.

Decomp Buddy's catalog and plans are read again; its copies of projects
taken down by a legal notice stay unused (DECOMP_BUDDY_MIRROR).
2026-12-01 12:23:55 -05:00
Kurt Himebauch f39267e8b0 feat(recomps): turn Decomp Buddy off until its author agrees
RecompCatalog.DECOMP_BUDDY_ENABLED keeps its catalog, plans and download
copies out of the app: the list is Recomp Launcher's and Recompa's, and
the mirror fallback is never used. The parsing code and its tests stay;
the title rules and arm64 twin lookup that follow its code stay on and
stay credited.
2026-12-01 11:45:13 -05:00
Kurt Himebauch 9fee179a80 feat(recomps): match PC ports to owned games by store ID and check their files
The catalogs name no store release, but Recomp Launcher gives each game's
IGDB slug. Wikidata links IGDB slugs to Steam app IDs, GOG slugs and Epic
store slugs, and GOG's products API gives the slug of each owned GOG
product; both answers are cached. A store with known IDs for the game is
matched by ID only. Other ports of the same PC game share its slug.

A match counts once the file a catalog names is in the install, and is
the right version when Decomp Buddy gives its hash or size. The card says
whether files were checked, whether it matched only by name, or which
file is missing or different.
2026-12-01 11:13:15 -05:00
Kurt Himebauch e72496f34d docs(recomps): record the AYN Thor run 2026-12-01 11:13:15 -05:00
Kurt Himebauch 3f0952fece feat(recomps): add Decomp Buddy's catalog and plans, and install arm64 twins
Decomp Buddy's catalog.json and plans.json become the first source: its
plans name the exact release file, the program in it, a scanned sha256
and the game files needed. The 32 MB plans file is read as a stream.
Store installs are matched with Decomp Buddy's title rules, and a plan's
expected file finds the folder inside the install.

Before installing an x86-64 Linux build, the release is checked for its
arm64 twin with a plain download request. When a project's own download
fails, Decomp Buddy's scanned copy is used. Debian packages unpack to
their data.tar, and installs are also matched by repo.
2026-12-01 11:13:15 -05:00
Kurt Himebauch d55da2f3c7 feat(recomps): filter by native builds and by original system
Nearly every recomp needs the player's own files, so that filter said
nothing. The chips are now All, Installed, You own the game and Runs
natively (arm64 Linux or an Android APK), with a row of the original
systems found in the catalogs.
2026-12-01 11:13:15 -05:00
Kurt Himebauch 22b1c21a02 feat(recomps): read Recomp Launcher's and Recompa's catalogs directly, with no catalog of our own
The tab now downloads both community catalogs, caches them with their
ETags and merges them on the device, so there is nothing for DroidDeck
to maintain. The curated list, the bundled catalog and the build and pin
scripts are gone. Ownership of a PC port's game is matched by title
against the player's installs and store libraries, and the wrapper just
starts the program from its own folder.
2026-12-01 11:13:15 -05:00
Kurt Himebauch a2118089c3 feat(recomps): merge the Recomp Launcher and Recompa catalogs, and install Android ports
tools/recomps/build_catalog.py builds the bundled catalog from DroidDeck's
curated entries, Recomp Launcher's pc-catalog.json (Windows and Linux
recomps) and Recompa's index.json (Android ports), matched by repo. Each
entry records the catalogs it came from; the card and the README credit
them.

Android builds install through PackageInstaller after the APK's package
name and signing certificate match the catalog, and already-installed
ports are recognised. Builds without a named program get one guessed
after unpacking. The page is now a lazy grid with search, for the
2,646 entries.
2026-12-01 11:13:15 -05:00
Kurt Himebauch 40b2db8007 feat(recomps): pin catalog releases so installs avoid the GitHub API limit 2026-12-01 11:13:14 -05:00
Kurt Himebauch 91b2f5483d feat(recomps): a Recomps tab that installs recomps and links store-owned game files
Adds More > Recomps: a curated catalog of recompiled and reimplemented
games. Each card installs the best build for the device (native arm64
Linux, x86-64 Linux through FEX, or Windows through Proton as an added
game), finds the game's data in a Steam, GOG or Epic install the player
already has, and passes that folder to the program at launch. ROM-based
recomps say which dump they need and never download one.

The catalog ships in assets and can be replaced by recomps.json in
DroidDeck-Components. tools/recomps/pin_catalog.py pins each entry to a
release so installs skip the rate-limited GitHub API.
2026-12-01 11:13:14 -05:00
121 changed files with 3890 additions and 2547 deletions

No files matched your search

+12
View File
@@ -107,6 +107,18 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
</details>
<details>
<summary><b>Recomps</b></summary>
- The Recomps tab lists the community catalogs below, read straight from their sites. Each entry shows which catalog it came from.
- [Decomp Buddy](https://decompbuddy.com) ([TanookiStudios/decomp-buddy](https://github.com/TanookiStudios/decomp-buddy), GPL-3.0) by Maddie at [Tanooki Studios](https://tanookistudios.com): its `catalog.json` and `plans.json` supply most entries, their exact release files, programs and scanned checksums, and the game files each needs. Matching a PC port to a Steam, GOG or Epic install follows its `src/stores.js` title rules, and arm64 Linux files are found the way its `armSibling` finds them.
- [Recomp Launcher](https://recomplauncher.com) ([elripalda/RecompLauncher](https://github.com/elripalda/RecompLauncher), GPL-3.0) by [@elripalda](https://github.com/elripalda), [@Xarishark](https://github.com/Xarishark) and contributors: its `pc-catalog.json` supplies the Windows and Linux recomps, their release pins and checksums, start programs, setup notes and the game data each needs.
- A PC game's Steam, GOG and Epic IDs come from [Wikidata](https://www.wikidata.org) (CC0), by the IGDB slug Recomp Launcher gives, and GOG product slugs from GOG's public products API.
- [Recompa](https://recompa.app) ([kalasyan/recompa](https://github.com/kalasyan/recompa), GPL-3.0) by [@kalasyan](https://github.com/kalasyan): its `index.json` supplies the Android ports, their APK checksums, package names and signing certificates, and the ROMs or files each needs.
- Every game's build is downloaded from its own developers' releases and keeps its own licence. DroidDeck ships no ROMs or game files.
</details>
<details>
<summary><b>Audio, video and HUD</b></summary>
@@ -1,5 +1,7 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.runtime.RecompData
import com.droiddeck.launcher.stores.Store
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
@@ -70,6 +72,7 @@ internal val previewCases: List<PreviewCase> = listOf(
PreviewCase("library-empty", storesLoaded) { Launcher("games", games = emptyList()) },
PreviewCase("stores", storesLoaded) { Launcher("stores") },
PreviewCase("downloads") { Launcher("downloads") },
PreviewCase("recomps") { RecompsTab() },
PreviewCase("settings") { Launcher("setup") },
PreviewCase("runtime-missing") { Launcher("setup", ready = false) },
PreviewCase("session-menu-controller") { SessionMenu(SessionDrawerPage.CONTROLLER) },
@@ -81,3 +84,34 @@ internal val previewCases: List<PreviewCase> = listOf(
PreviewCase("session-menu-docked-display") { DockedMenu(SessionDrawerPage.DISPLAY) },
PreviewCase("bottom-panel-bar") { BottomPanelBar() },
)
/** The Recomps tab with one recomp installed, one game installed from Steam, one owned on GOG and an Android port. */
@Composable
private fun RecompsTab(): Unit {
androidx.compose.runtime.remember {
fun entry(id: String, name: String, game: String, origin: String, platform: com.droiddeck.launcher.runtime.RecompCatalog.Platform,
needs: String, sources: List<String>) =
com.droiddeck.launcher.runtime.RecompCatalog.Entry(id, name, game, origin, if (origin == "PC") "port" else "recomp", "o/$id", "", "",
null, listOf(com.droiddeck.launcher.runtime.RecompCatalog.Build(platform, Regex("x"))),
com.droiddeck.launcher.runtime.RecompCatalog.Data(com.droiddeck.launcher.runtime.RecompCatalog.DataKind.ROM, needs), sources)
val list = listOf(
entry("zelda64recomp", "Zelda 64: Recompiled", "The Legend of Zelda: Majora's Mask", "N64", com.droiddeck.launcher.runtime.RecompCatalog.Platform.LINUX_ARM64, "Majora's Mask (USA) N64 ROM", listOf("recomp-launcher")),
entry("ironwail", "Ironwail", "Quake", "PC", com.droiddeck.launcher.runtime.RecompCatalog.Platform.LINUX_X64, "Quake's id1 folder", listOf("recomp-launcher")),
entry("fallout2-ce", "Fallout 2 Community Edition", "Fallout 2", "PC", com.droiddeck.launcher.runtime.RecompCatalog.Platform.WINDOWS_X64, "Fallout 2's master.dat", listOf("recomp-launcher", "recompa")),
entry("shipwright", "Ship of Harkinian", "The Legend of Zelda: Ocarina of Time", "N64", com.droiddeck.launcher.runtime.RecompCatalog.Platform.ANDROID, "Ocarina of Time ROM", listOf("recompa")),
)
val states: Map<String, RecompData.State> = mapOf(
"zelda64recomp" to RecompData.State.BringYourOwn(list[0].data),
"ironwail" to RecompData.State.Found(Store.STEAM, java.io.File("/q"), "/root/.local/share/Steam/steamapps/common/Quake", exact = true, checked = true),
"fallout2-ce" to RecompData.State.Owned(Store.GOG, null, exact = true),
"shipwright" to RecompData.State.BringYourOwn(list[3].data),
)
val installed = mapOf("zelda64recomp" to com.droiddeck.launcher.runtime.RecompInstaller.Installed(
"zelda64recomp", "script:zelda-64-recompiled", "v1.2.1", "", "linux-arm64", java.io.File("/z")))
val newer = mapOf("zelda64recomp" to com.droiddeck.launcher.runtime.RecompInstaller.Release("v1.2.2", "", "", "", null))
com.droiddeck.launcher.store.RecompsState.show(list, installed, states, newer)
}
Launcher("recomps")
}
@DroidDeckPreviews @Composable private fun RecompsTabPreview() = RecompsTab()
@@ -205,19 +205,15 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
acquire = exp.fd;
} else {
} else if (dmabuf_fd >= 0) {
if (!g_export_failed_logged) {
g_export_failed_logged = 1;
droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s",
dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd",
draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU");
droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_EXPORT_SYNC_FILE failed (%s): waiting for each frame on the CPU instead",
strerror(errno));
}
if (dmabuf_fd >= 0) {
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
if (draw) return -1;
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw,
s ? droiddeck_surface_color(s) : NULL, ab->format);
+16 -223
View File
@@ -2272,69 +2272,6 @@ static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t
struct draw_list { struct vkp_draw *d; int n, cap; };
#define ZERO_COPY_FALLBACK_SIGNATURES 32u
enum zero_copy_fallback_reason {
ZERO_COPY_NO_SURFACE_BUFFER = 1,
ZERO_COPY_NO_GRALLOC_AHB = 2,
ZERO_COPY_AHB_PRESENT_FAILED = 3
};
struct zero_copy_fallback_signature {
uint32_t reason, format, stride, offset;
int width, height;
uint64_t modifier;
};
static struct zero_copy_fallback_signature g_zero_copy_fallbacks[ZERO_COPY_FALLBACK_SIGNATURES];
static uint32_t g_zero_copy_fallback_count;
static int g_zero_copy_fallback_limit_logged;
static int zero_copy_fallback_should_log(const struct dmabuf_buffer *b, uint32_t reason) {
const struct zero_copy_fallback_signature key = {
.reason = reason, .format = b ? b->format : 0,
.stride = b && b->n_planes ? b->stride[0] : 0,
.offset = b && b->n_planes ? b->offset[0] : 0,
.width = b ? b->width : 0, .height = b ? b->height : 0,
.modifier = b ? b->modifier : 0};
for (uint32_t i = 0; i < g_zero_copy_fallback_count; i++) {
const struct zero_copy_fallback_signature *seen = &g_zero_copy_fallbacks[i];
if (seen->reason == key.reason && seen->format == key.format && seen->stride == key.stride &&
seen->offset == key.offset && seen->width == key.width && seen->height == key.height &&
seen->modifier == key.modifier)
return 0;
}
if (g_zero_copy_fallback_count >= ZERO_COPY_FALLBACK_SIGNATURES) {
if (!g_zero_copy_fallback_limit_logged) {
g_zero_copy_fallback_limit_logged = 1;
droiddeck_log("layer", "zero-copy: further fallback diagnostics suppressed after %u distinct buffer signatures",
ZERO_COPY_FALLBACK_SIGNATURES);
}
return 0;
}
g_zero_copy_fallbacks[g_zero_copy_fallback_count++] = key;
return 1;
}
static void note_zero_copy_fallback(struct surface *s, const struct dmabuf_buffer *b, uint32_t reason,
int scene_w, int scene_h, int present_result) {
if (!zero_copy_fallback_should_log(b, reason)) return;
char name[160] = "unknown surface";
if (s) describe(s, name, sizeof(name));
if (reason == ZERO_COPY_NO_SURFACE_BUFFER) {
droiddeck_log("layer", "zero-copy: layer candidate %s has no associated Wayland surface buffer; using the layer-copy path",
name);
} else {
droiddeck_log("layer", "zero-copy: %s buffer %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx %s; "
"scene %dx%d will use the layer-copy path (direct-present result %d)",
name, b->format & 0xff, (b->format >> 8) & 0xff, (b->format >> 16) & 0xff,
(b->format >> 24) & 0xff, b->width, b->height,
b->n_planes ? b->stride[0] : 0, b->n_planes ? b->offset[0] : 0,
(unsigned long long)b->modifier,
reason == ZERO_COPY_NO_GRALLOC_AHB
? "has no registered gralloc AHardwareBuffer"
: "has a registered gralloc AHardwareBuffer but direct presentation failed",
scene_w, scene_h, present_result);
}
}
static int add_cursor(struct draw_list *dl, int scene_w);
static struct vkp_image *surface_image(struct surface *s) {
@@ -2454,53 +2391,17 @@ static int black_fill_below(const struct draw_list *dl, int n) {
return 1;
}
#define LAYER_CANDIDATE_DIAGNOSTICS 32u
static unsigned g_layer_candidate_diag_count;
static int g_layer_candidate_diag_limit;
static void note_layer_candidate_skip(const struct vkp_draw *d, int index, int reason,
int scene_w, int scene_h) {
static int seen[LAYER_CANDIDATE_DIAGNOSTICS][8];
const int key[8] = {index, reason, scene_w, scene_h, d->dx, d->dy, d->dw, d->dh};
for (unsigned i = 0; i < g_layer_candidate_diag_count; i++)
if (!memcmp(seen[i], key, sizeof(key))) return;
if (g_layer_candidate_diag_count >= LAYER_CANDIDATE_DIAGNOSTICS) {
if (!g_layer_candidate_diag_limit++) droiddeck_log("layer", "zero-copy: further candidate-rejection details suppressed after %u signatures",
LAYER_CANDIDATE_DIAGNOSTICS);
return;
}
memcpy(seen[g_layer_candidate_diag_count++], key, sizeof(key));
const char *why = reason == 1 ? "translucent draw" :
reason == 2 ? "image is not DMA-BUF" :
reason == 3 ? "source rectangle is outside/invalid" :
reason == 4 ? "draw rectangle is outside scene or invalid" :
"not fullscreen and no black backing below";
droiddeck_log("layer", "zero-copy: candidate draw %d rejected: %s; scene %dx%d, dst %dx%d at %d,%d, src %.2f,%.2f %.2fx%.2f, image %dx%d",
index, why, scene_w, scene_h, d->dw, d->dh, d->dx, d->dy,
d->sx, d->sy, d->sw, d->sh, vkp_image_width(d->img), vkp_image_height(d->img));
}
static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) {
for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) {
const struct vkp_draw *d = &dl->d[i];
if (d->blend) { note_layer_candidate_skip(d, i, 1, scene_w, scene_h); continue; }
if (!vkp_image_is_dmabuf(d->img)) { note_layer_candidate_skip(d, i, 2, scene_w, scene_h); continue; }
if (d->blend) continue;
if (!vkp_image_is_dmabuf(d->img)) continue;
if (d->sx < 0 || d->sy < 0 || d->sw < 1.0f || d->sh < 1.0f ||
d->sx + d->sw >= vkp_image_width(d->img) + 1.0f ||
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) {
note_layer_candidate_skip(d, i, 3, scene_w, scene_h);
continue;
}
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) continue;
if (d->dx == 0 && d->dy == 0 && d->dw == scene_w && d->dh == scene_h) return i;
if (d->dx < 0 || d->dy < 0 || d->dw <= 0 || d->dh <= 0 || d->dx + d->dw > scene_w ||
d->dy + d->dh > scene_h) {
note_layer_candidate_skip(d, i, 4, scene_w, scene_h);
continue;
}
if (!black_fill_below(dl, i)) {
note_layer_candidate_skip(d, i, 5, scene_w, scene_h);
continue;
}
d->dy + d->dh > scene_h || !black_fill_below(dl, i)) continue;
return i;
}
return -1;
@@ -2521,56 +2422,6 @@ static void note_copy_scene(const struct draw_list *dl, int scene_w, int scene_h
vkp_image_is_dmabuf(t->img) ? "GPU" : "memory", t->blend ? ", translucent" : "");
}
static struct surface *surface_for_image(const struct vkp_image *img);
static void note_layer_candidate_rejected(const struct draw_list *dl, int scene_w, int scene_h) {
static int seen[32][14];
static unsigned seen_count;
static int limit_logged;
static time_t window_start;
struct timespec now_ts;
const struct vkp_draw *a = dl->n > 0 ? &dl->d[dl->n - 1] : NULL;
const struct vkp_draw *b = dl->n > 1 ? &dl->d[dl->n - 2] : NULL;
struct surface *sa = a ? surface_for_image(a->img) : NULL;
struct surface *sb = b ? surface_for_image(b->img) : NULL;
const int signature[14] = {
dl->n, scene_w, scene_h,
a ? a->dw : 0, a ? a->dh : 0,
a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0,
a ? vkp_image_is_dmabuf(a->img) : 0, a ? a->blend : 0, sa && sa->dmabuf_buf ? 1 : 0,
b ? b->dw : 0, b ? b->dh : 0, b ? vkp_image_is_dmabuf(b->img) : 0, sb && sb->dmabuf_buf ? 1 : 0
};
clock_gettime(CLOCK_MONOTONIC, &now_ts);
if (!window_start || now_ts.tv_sec - window_start >= 30) {
seen_count = 0;
limit_logged = 0;
window_start = now_ts.tv_sec;
}
for (unsigned i = 0; i < seen_count; i++)
if (!memcmp(signature, seen[i], sizeof(signature))) return;
if (seen_count >= 32) {
if (!limit_logged++) droiddeck_log("layer", "zero-copy: further fullscreen-candidate rejection details suppressed after 32 signatures in 30 seconds");
return;
}
memcpy(seen[seen_count++], signature, sizeof(signature));
char below[48];
if (b)
snprintf(below, sizeof(below), "%s %dx%d",
vkp_image_is_dmabuf(b->img) ? "DMA-BUF" : "non-DMA-BUF", b->dw, b->dh);
else
snprintf(below, sizeof(below), "none");
droiddeck_log("layer", "zero-copy: no eligible fullscreen DMA-BUF layer candidate: scene %dx%d, %d draws; "
"top draw %dx%d at %d,%d image %dx%d %s%s surface=%s dmabuf=%s; "
"draw below %s",
scene_w, scene_h, dl->n, a ? a->dw : 0, a ? a->dh : 0, a ? a->dx : 0, a ? a->dy : 0,
a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0,
a && vkp_image_is_dmabuf(a->img) ? "DMA-BUF" : "non-DMA-BUF",
a && a->blend ? " blended" : "",
sa ? "associated" : "unassociated",
sa && sa->dmabuf_buf ? "yes" : "no",
below);
}
static struct surface *surface_for_image(const struct vkp_image *img) {
struct surface *s;
wl_list_for_each(s, &g_surfaces, link)
@@ -2579,56 +2430,16 @@ static struct surface *surface_for_image(const struct vkp_image *img) {
}
static struct surface *ahb_layer_only_candidate(int scene_w, int scene_h) {
static struct {
const struct surface *surface;
int reason, scene_w, scene_h, w, h, buf_w, buf_h, x, y, src_set, dst_set, children;
} seen[32];
static unsigned seen_count;
static int limit_logged;
struct surface *s;
int w = 0, h = 0, reason = 0;
int w, h;
if (wl_list_empty(&g_toplevels)) return NULL;
s = wl_container_of(g_toplevels.prev, s, toplevel_link);
if (!s->dmabuf_buf) reason = 1;
else if (s->dmabuf_buf->img) reason = 2;
else if (!ahb_swapchain_has_ahb(s->dmabuf_buf)) reason = 3;
else if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) reason = 4;
else if (!wl_list_empty(&s->children)) reason = 5;
else if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) reason = 6;
if (!s->dmabuf_buf || s->dmabuf_buf->img || !ahb_swapchain_has_ahb(s->dmabuf_buf)) return NULL;
if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) return NULL;
if (!wl_list_empty(&s->children)) return NULL;
if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) return NULL;
surface_size(s, &w, &h);
if (!reason && (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h)) reason = 7;
if (reason) {
int found = 0;
for (unsigned i = 0; i < seen_count; i++) {
if (seen[i].surface == s && seen[i].reason == reason && seen[i].scene_w == scene_w &&
seen[i].scene_h == scene_h && seen[i].w == w && seen[i].h == h &&
seen[i].buf_w == s->buf_w && seen[i].buf_h == s->buf_h && seen[i].x == s->x &&
seen[i].y == s->y && seen[i].src_set == s->src_set && seen[i].dst_set == s->dst_set &&
seen[i].children == !wl_list_empty(&s->children)) { found = 1; break; }
}
if (!found && seen_count < 32) {
seen[seen_count].surface = s; seen[seen_count].reason = reason;
seen[seen_count].scene_w = scene_w; seen[seen_count].scene_h = scene_h;
seen[seen_count].w = w; seen[seen_count].h = h; seen[seen_count].buf_w = s->buf_w; seen[seen_count].buf_h = s->buf_h;
seen[seen_count].x = s->x; seen[seen_count].y = s->y; seen[seen_count].src_set = s->src_set;
seen[seen_count].dst_set = s->dst_set; seen[seen_count].children = !wl_list_empty(&s->children);
seen_count++;
const char *why = reason == 1 ? "no DMA-BUF buffer" :
reason == 2 ? "buffer is already importable by Vulkan" :
reason == 3 ? "no registered gralloc AHardwareBuffer" :
reason == 4 ? "surface is positioned/cropped/scaled" :
reason == 5 ? "surface has child surfaces" :
reason == 6 ? "hidden shell surface" : "surface or buffer dimensions differ from scene";
char name[160]; describe(s, name, sizeof(name));
droiddeck_log("layer", "zero-copy: AHardwareBuffer-only candidate rejected: %s; %s, scene %dx%d, surface %dx%d at %d,%d, buffer %dx%d, crop=%d destination=%d children=%d",
why, name, scene_w, scene_h, w, h, s->x, s->y, s->buf_w, s->buf_h,
s->src_set, s->dst_set, !wl_list_empty(&s->children));
} else if (!found && !limit_logged) {
limit_logged = 1;
droiddeck_log("layer", "zero-copy: further AHardwareBuffer-only candidate diagnostics suppressed after 32 signatures");
}
return NULL;
}
if (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h) return NULL;
return s;
}
@@ -3071,10 +2882,7 @@ static void render_scene(void) {
struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL;
const struct vkp_draw *ld = li >= 0 ? &dl.d[li] : NULL;
if (li < 0) ls = layer_only;
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) {
if (!cursor_on && !bfi) note_layer_candidate_rejected(&dl, w, h);
note_copy_scene(&dl, w, h, cursor_on);
}
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) note_copy_scene(&dl, w, h, cursor_on);
if (cardboard) ls = NULL;
if (cursor_on) ls = NULL;
if (bfi) ls = NULL;
@@ -3102,30 +2910,15 @@ static void render_scene(void) {
r = generated >= 0 ? 0 : -1;
else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf))
r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld);
if (!fg_pass && generated >= 0 && !fx_on && !framegen && r != 0) {
if (!ls || !ls->dmabuf_buf)
note_zero_copy_fallback(ls, NULL, ZERO_COPY_NO_SURFACE_BUFFER, w, h, r);
else if (!ahb_swapchain_has_ahb(ls->dmabuf_buf))
note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_NO_GRALLOC_AHB, w, h, r);
else
note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_AHB_PRESENT_FAILED, w, h, r);
}
if (r == 0 && !fg_pass) g_zero_copy_shown = ls;
else settle_unwaited();
int ov = 0, ov_done = 0;
if (!fg_pass && generated >= 0 && r != 0 && li >= 0) {
if (fx_on) {
r = sc_layer_present_pass(&dl.d[li], 1, w, h);
} else {
r = sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL,
over == 1 ? &dl.d[li + 1] : NULL, &ov);
ov_done = 1;
}
}
if (!fg_pass && generated >= 0 && r != 0 && li >= 0)
r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h)
: sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL);
if (r == 0) {
if (ls) ls->drawn = 1;
int go[8];
if (!ov_done && over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
int go[8], ov = 0;
if (over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
ov = sc_layer_present_overlay(dl.d[li + 1].img, go, dl.d[li + 1].blend) == 0 ? 1 : -1;
if (ov <= 0) sc_layer_hide_overlay();
if (ov < 0) {
@@ -62,40 +62,8 @@ struct entry {
static struct wl_list g_entries;
static struct wl_event_loop *g_loop;
static uint64_t g_next_id = 1;
static int g_refused_logged;
static int g_ubwc_promised;
#define DISPLAY_BUFFER_MISMATCH_SIGNATURES 64u
struct display_buffer_mismatch_signature {
uint32_t kind, format, stride, offset;
int width, height;
uint64_t modifier;
};
static struct display_buffer_mismatch_signature g_mismatch_signatures[DISPLAY_BUFFER_MISMATCH_SIGNATURES];
static uint32_t g_mismatch_signature_count;
static int g_mismatch_limit_logged;
static int mismatch_should_log(const struct dmabuf_buffer *b, uint32_t kind) {
const struct display_buffer_mismatch_signature key = {
.kind = kind, .format = b->format, .stride = b->stride[0], .offset = b->offset[0],
.width = b->width, .height = b->height, .modifier = b->modifier};
for (uint32_t i = 0; i < g_mismatch_signature_count; i++) {
const struct display_buffer_mismatch_signature *seen = &g_mismatch_signatures[i];
if (seen->kind == key.kind && seen->format == key.format && seen->stride == key.stride &&
seen->offset == key.offset && seen->width == key.width && seen->height == key.height &&
seen->modifier == key.modifier)
return 0;
}
if (g_mismatch_signature_count >= DISPLAY_BUFFER_MISMATCH_SIGNATURES) {
if (!g_mismatch_limit_logged) {
g_mismatch_limit_logged = 1;
droiddeck_log("layer", "display buffers: further mismatch diagnostics suppressed after %u distinct buffer signatures",
DISPLAY_BUFFER_MISMATCH_SIGNATURES);
}
return 0;
}
g_mismatch_signatures[g_mismatch_signature_count++] = key;
return 1;
}
static int g_ubwc_probed[2];
static uint32_t ahb_format_of(uint32_t drm, uint64_t modifier) {
@@ -270,51 +238,16 @@ static void handle_alloc(struct peer *p, const struct display_buffers_request *q
} else {
if (ahb) AHardwareBuffer_release(ahb);
fd = -1;
static struct {
pid_t pid;
uint32_t width, height, format, stride, offset, reason;
uint64_t size, modifier;
} refused[32];
static unsigned refused_count;
static int refused_limit_logged;
uint32_t reason = !sized ? 1u : !sane ? 2u : !wanted ? 3u :
!ahb_swapchain_advertised() ? 4u :
p->count >= DISPLAY_BUFFERS_MAX_PER_CLIENT ? 5u : 6u;
int seen = 0;
for (unsigned i = 0; i < refused_count; i++) {
if (refused[i].pid == p->pid && refused[i].width == q->width && refused[i].height == q->height &&
refused[i].format == q->format && refused[i].stride == q->stride && refused[i].offset == q->offset &&
refused[i].size == q->size && refused[i].modifier == q->modifier && refused[i].reason == reason) {
seen = 1;
break;
}
}
if (!seen && refused_count < 32) {
refused[refused_count].pid = p->pid;
refused[refused_count].width = q->width;
refused[refused_count].height = q->height;
refused[refused_count].format = q->format;
refused[refused_count].stride = q->stride;
refused[refused_count].offset = q->offset;
refused[refused_count].size = q->size;
refused[refused_count].modifier = q->modifier;
refused[refused_count].reason = reason;
refused_count++;
const char *why = reason == 1 ? "invalid dimensions, format, or stride" :
reason == 2 ? "size/offset/layout sanity check failed" :
reason == 3 ? "zero-copy or UBWC offering is disabled" :
reason == 4 ? "AHardwareBuffer swapchain is not advertised" :
reason == 5 ? "per-client allocation limit reached" :
"gralloc allocation/fd/size validation failed";
droiddeck_log(compressed ? "error" : "layer",
"display buffers: allocation refused for pid %d: %s; request %ux%u %c%c%c%c %s stride=%u offset=%u size=%llu modifier=0x%llx (client has %d allocations)",
(int)p->pid, why, q->width, q->height,
q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff,
compressed ? "UBWC" : "linear", q->stride, q->offset,
(unsigned long long)q->size, (unsigned long long)q->modifier, p->count);
} else if (!seen && !refused_limit_logged) {
refused_limit_logged = 1;
droiddeck_log("layer", "display buffers: further allocation-refusal diagnostics suppressed after 32 signatures");
if (sized && wanted && (compressed || !g_refused_logged)) {
g_refused_logged = 1;
droiddeck_log(compressed ? "error" : "layer", "display buffers: no gralloc buffer matches pid %d's %ux%u "
"%c%c%c%c %s layout (stride %u bytes, pixels at %u, %llu bytes; gralloc's layout has pixels at "
"%llu, %llu bytes): %s", (int)p->pid, q->width, q->height,
q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff,
compressed ? "UBWC" : "linear", q->stride, q->offset, (unsigned long long)q->size,
(unsigned long long)(compressed ? ubwc_meta_size(q->width, q->height) : 0),
(unsigned long long)(compressed ? ubwc_size(q->width, q->height, q->stride) : q->size),
compressed ? "its compressed frames cannot be shown" : "its frames keep the copy path");
}
}
if (reply(p, &r, fd) != 0 && e) entry_free(e);
@@ -366,18 +299,9 @@ static int on_listen(int fd, uint32_t mask, void *data) {
}
void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b) {
static int invalid_logged;
struct stat st;
struct entry *e;
if (!g_loop || wl_list_empty(&g_entries)) return;
if (b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) {
if (!invalid_logged) {
invalid_logged = 1;
droiddeck_log("layer", "display buffers: cannot associate %s's DMA-BUF with gralloc (plane count %u; expected one plane at offset 0, or fstat failed)",
droiddeck_client_name(c), b->n_planes);
}
return;
}
if (!g_loop || wl_list_empty(&g_entries) || b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) return;
wl_list_for_each(e, &g_entries, link) {
if (e->dev != st.st_dev || e->ino != st.st_ino) continue;
AHardwareBuffer_Desc d;
@@ -387,27 +311,11 @@ void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, stru
(uint32_t)b->height == e->height
: (b->modifier == MOD_LINEAR || b->modifier == MOD_INVALID) &&
e->stride == b->stride[0];
const uint32_t expected_format = ahb_format_of(b->format, e->modifier);
const int dimensions = b->width > 0 && b->height > 0 &&
(uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height;
if (laid_out && e->format == expected_format && dimensions) {
if (laid_out && e->format == ahb_format_of(b->format, e->modifier) && b->width > 0 && b->height > 0 &&
(uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height)
ahb_swapchain_adopt(c, buffer, b, e->ahb, e->modifier);
} else if (mismatch_should_log(b, 2)) {
droiddeck_log("layer", "display buffers: gralloc DMA-BUF identity matched but layout was rejected for %s: %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx; gralloc %ux%u stride %u format 0x%x, expected format 0x%x (layout %s, dimensions %s)",
droiddeck_client_name(c), b->format & 0xff, (b->format >> 8) & 0xff,
(b->format >> 16) & 0xff, (b->format >> 24) & 0xff, b->width, b->height,
b->stride[0], b->offset[0], (unsigned long long)b->modifier,
e->width, e->height, e->stride, e->format, expected_format,
laid_out ? "ok" : "mismatch", dimensions ? "ok" : "mismatch");
}
return;
}
if (mismatch_should_log(b, 1)) {
droiddeck_log("layer", "display buffers: no registered gralloc allocation matches %s's DMA-BUF identity: %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx; imported normally, copy path only",
droiddeck_client_name(c), b->format & 0xff, (b->format >> 8) & 0xff,
(b->format >> 16) & 0xff, (b->format >> 24) & 0xff, b->width, b->height,
b->stride[0], b->offset[0], (unsigned long long)b->modifier);
}
}
void display_buffers_init(struct wl_display *display) {
+14 -58
View File
@@ -187,8 +187,6 @@ struct layer {
static struct layer g_layers[SC_LAYER_COUNT];
static void apply_frame_rate(ASurfaceTransaction *tx, struct layer *l);
static void coverage_text(const struct layer *l, char *out, size_t n);
static int overlay_slot(struct layer *l, struct vkp_image *src, int *idx, int *wait_fd);
static int overlay_shown(struct layer *l, int idx, const int geo[8], int translucent);
static int g_layers_ready;
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static int g_pending_cb;
@@ -723,15 +721,9 @@ static int layer_geometry(int w, int h, int scene_w, int scene_h, const struct v
static ARect g_game_src, g_game_dst;
static int g_game_geo_known;
static void note_game_geometry(const int r[8]) {
g_game_src = (ARect){r[0], r[1], r[2], r[3]};
g_game_dst = (ARect){r[4], r[5], r[6], r[7]};
g_game_geo_known = 1;
}
static void apply_geometry(ASurfaceTransaction *tx, struct layer *l, const int r[8]) {
ARect srcR = {r[0], r[1], r[2], r[3]}, dstR = {r[4], r[5], r[6], r[7]};
if (l == &g_layers[SC_LAYER_GAME]) note_game_geometry(r);
if (l == &g_layers[SC_LAYER_GAME]) { g_game_src = srcR; g_game_dst = dstR; g_game_geo_known = 1; }
if (!l->geo_valid || memcmp(&srcR, &l->geo_src, sizeof(srcR)) || memcmp(&dstR, &l->geo_dst, sizeof(dstR))) {
api.setGeometry(tx, l->sc, &srcR, &dstR, 0 );
l->geo_src = srcR; l->geo_dst = dstR; l->geo_valid = 1;
@@ -1006,40 +998,19 @@ unavailable:
}
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw,
const struct droiddeck_color *color, const struct vkp_draw *over, int *over_shown) {
const struct droiddeck_color *color) {
struct layer *l = layer_of(SC_LAYER_GAME);
*over_shown = 0;
if (!src || ensure_sc(l) != 0) return -1;
int sw = vkp_image_width(src), sh = vkp_image_height(src);
int r[8];
int g = layer_geometry(sw, sh, scene_w, scene_h, draw, r);
if (g < 0) return -1;
int og[8];
if (over && !vkp_map_draw(over, og)) over = NULL;
if (g == 0) {
sc_layer_hide();
if (over) *over_shown = sc_layer_present_overlay(over->img, og, over->blend) == 0 ? 1 : -1;
return 0;
}
if (g == 0) { sc_layer_hide(); return 0; }
struct vkp_blit blits[2] = {{.src = src, .wait_fd = -1}, {.src = over ? over->img : NULL, .wait_fd = -1}};
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &blits[0].wait_fd);
if (idx < 0) {
log_drop(l);
if (g_alloc_failed) return -1;
if (over) *over_shown = sc_layer_present_overlay(over->img, og, over->blend) == 0 ? 1 : -1;
return 0;
}
blits[0].dst = l->slots[idx].img;
struct layer *ol = layer_of(SC_LAYER_OVERLAY);
int over_idx = -1;
if (over) {
note_game_geometry(r);
const int taken = overlay_slot(ol, over->img, &over_idx, &blits[1].wait_fd);
*over_shown = taken < 0 ? -1 : 1;
if (taken > 0) blits[1].dst = ol->slots[over_idx].img;
}
if (vkp_blit_images(blits, over_idx >= 0 ? 2 : 1) != 0) return -1;
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
if (present_slot(l, idx, r, color, 0) != 0) return -1;
if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8);
if (!l->first_logged) {
@@ -1049,7 +1020,6 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
pool_kind(l->pool_modifier), l->pool_n);
}
vkp_signal_first_frame();
if (over_idx >= 0 && overlay_shown(ol, over_idx, og, over->blend) != 0) *over_shown = -1;
return 0;
}
@@ -1239,19 +1209,17 @@ int sc_layer_overlay_affordable(void) {
return ok;
}
static int overlay_slot(struct layer *l, struct vkp_image *src, int *idx, int *wait_fd) {
*wait_fd = -1;
if (!src) return -1;
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) {
struct layer *l = layer_of(SC_LAYER_OVERLAY);
if (!src || !geo) return -1;
if (!sc_layer_overlay_affordable()) return -1;
if (ensure_sc(l) != 0) return -1;
int sw = vkp_image_width(src), sh = vkp_image_height(src);
if (sw <= 0 || sh <= 0) return -1;
*idx = take_free_slot(l, sw, sh, AHB_RGBA8, wait_fd);
if (*idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
return 1;
}
static int overlay_shown(struct layer *l, int idx, const int geo[8], int translucent) {
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
if (!l->first_logged) {
l->first_logged = 1;
@@ -1260,18 +1228,6 @@ static int overlay_shown(struct layer *l, int idx, const int geo[8], int translu
return 0;
}
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) {
struct layer *l = layer_of(SC_LAYER_OVERLAY);
if (!geo) return -1;
int idx;
struct vkp_blit blit = {.src = src, .wait_fd = -1};
const int taken = overlay_slot(l, src, &idx, &blit.wait_fd);
if (taken <= 0) return taken;
blit.dst = l->slots[idx].img;
if (vkp_blit_images(&blit, 1) != 0) return -1;
return overlay_shown(l, idx, geo, translucent);
}
static int hide_layer(struct layer *l) {
if (!l->sc || !l->shown || api.state != 1) return 0;
ASurfaceTransaction *tx = api.txCreate();
+1 -1
View File
@@ -22,7 +22,7 @@ void sc_layer_hdr_symbols(char *out, size_t size);
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw,
const struct droiddeck_color *color, const struct vkp_draw *over, int *over_shown);
const struct droiddeck_color *color);
int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int scene_h);
int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf,
+27 -62
View File
@@ -20,8 +20,6 @@
#include <unistd.h>
#include <errno.h>
#include <poll.h>
#include <linux/sync_file.h>
#include <sys/ioctl.h>
#include <time.h>
#include <pthread.h>
#include <stdarg.h>
@@ -3164,38 +3162,8 @@ static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_la
0, 0, NULL, 0, NULL, 1, &release);
}
static int merge_wait_fds(int a, int b) {
if (a < 0) return b;
if (b < 0) return a;
struct sync_merge_data m = {.name = "droiddeck-layer-copy", .fd2 = b};
if (ioctl(a, SYNC_IOC_MERGE, &m) == 0) {
close(a);
close(b);
return m.fence;
}
struct pollfd p = {.fd = b, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
close(b);
if (r != 0) return a;
p.fd = a;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
close(a);
return -2;
}
int vkp_blit_images(const struct vkp_blit *blits, int n) {
int wait_fd = -1;
for (int i = 0; i < n; i++) {
if (wait_fd == -2) { if (blits[i].wait_fd >= 0) close(blits[i].wait_fd); continue; }
wait_fd = merge_wait_fds(wait_fd, blits[i].wait_fd);
}
int valid = n > 0 && wait_fd != -2;
for (int i = 0; valid && i < n; i++) {
const struct vkp_image *src = blits[i].src, *dst = blits[i].dst;
if (!src || src->blit_dst || !dst || !dst->blit_dst) valid = 0;
}
if (!valid || dev_init() != 0) {
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
return -1;
}
@@ -3208,35 +3176,32 @@ int vkp_blit_images(const struct vkp_blit *blits, int n) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(g_cmd, &bi);
for (int i = 0; i < n; i++) {
struct vkp_image *src = blits[i].src, *dst = blits[i].dst;
stage_linear_dmabuf(g_cmd, src);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
src->in_general = 1;
}
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
stage_linear_dmabuf(g_cmd, src);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
src->in_general = 1;
}
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
g_vk.EndCommandBuffer(g_cmd);
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
@@ -105,11 +105,7 @@ int vkp_render_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n
int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *rw, int *rh);
struct vkp_blit {
struct vkp_image *src, *dst;
int wait_fd;
};
int vkp_blit_images(const struct vkp_blit *blits, int n);
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd);
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px);
int vkp_update_map(int scene_w, int scene_h);
int vkp_map_draw(const struct vkp_draw *d, int out[8]);
@@ -192,7 +192,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(true)
private var desktopAsUser by mutableStateOf(false)
private var cursorComposite by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
@@ -1039,6 +1038,28 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onHandled()
return
}
// A Linux recomp starts as the Linux app it is, whether or not Steam would launch it.
if (game.source == com.droiddeck.launcher.runtime.RecompShortcuts.SOURCE) {
launchCoordinator.releaseHandling(request)
onHandled()
val key = game.storeId
Thread({
val app = com.droiddeck.launcher.store.UserAppsState.items.firstOrNull { it.key == key }
?: runCatching { com.droiddeck.launcher.runtime.UserApps.list(this).firstOrNull { it.key == key } }.getOrNull()
ui.post {
if (app == null) android.widget.Toast.makeText(this, R.string.recomps_launch_missing, android.widget.Toast.LENGTH_SHORT).show()
else {
Library.recordPlayed(this, game)
startActivity(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, app.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, app.args.toTypedArray()))
onSettled()
}
}
}, "recomp-launch").start()
return
}
val files = game.gameFiles
if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) {
if (startGame(game, returnHome, onHandled, request)) onSettled()
@@ -3050,7 +3071,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
@@ -3067,7 +3088,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
onClientCore = { core, on ->
@@ -3386,7 +3406,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
nativeUserland = SessionPrefs.nativeUserland(this)
desktopAsUser = SessionPrefs.desktopAsUser(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
refreshPhantomStatus()
@@ -807,7 +807,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private var isHomeApp by mutableStateOf(false)
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
private var padConnected by mutableStateOf(false)
private val deviceListener = object : InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) {
@@ -1265,7 +1264,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
) { headTracker?.recenter() }
if (!phonePanel && glasses.present && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot,
controllerSettings?.tint ?: android.graphics.Color.rgb(90, 160, 255), controllerSettings?.opacity ?: 100) {
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.VR
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.GLASSES
drawerOpen = true
}
if (!drawerOpen && !pcKeyboardOpen && !loading.visible) {
@@ -1452,10 +1451,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
LaunchedEffect(drawerOpen, achievementsOpen, AgentGuest.focusRevision, StoreAchievements.revision) {
if (!drawerOpen && !achievementsOpen) {
achievementsInFront = null
return@LaunchedEffect
}
if (!drawerOpen && !achievementsOpen) return@LaunchedEffect
val found = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { resolveAchievementsInFront() }
.onFailure { Log.w(TAG, "achievements in front: ${it.javaClass.simpleName}") }.getOrNull()
@@ -1791,7 +1787,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onBlackFrameInsertion = { on ->
SessionPrefs.setBlackFrameInsertion(this@SessionActivity, on)
blackFrameInsertion = on
CompositorHost.setBlackFrameInsertion(on, refreshHz(), compositorFpsLimit())
CompositorHost.setBlackFrameInsertion(on, refreshHz(), outputFpsLimit())
},
hdr = hdrWanted,
hdrAvailable = hdrAvailable,
@@ -1828,9 +1824,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onRumble = { on -> updateControllerPrefs { ControllerPrefs.setRumble(this@SessionActivity, on) } },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
controllerConnected = padConnected,
achievementsGame = achievementsInFront?.game,
achievementsTitle = achievementsInFront?.title,
onAchievements = achievementsInFront?.let { { drawerOpen = false; achievementsOpen = true } },
achievementsProgress = achievementsInFront?.progress,
padType = if (SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad) padType else null,
onPadType = { id ->
@@ -1951,13 +1945,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onResume = { SessionService.resume(this@SessionActivity) },
orientation = sessionOrientation,
onOrientation = { value ->
when (SessionState.mode) {
SessionService.MODE_STEAM, SessionService.MODE_RUN ->
SessionPrefs.setOrientation(this@SessionActivity, "steam", value)
SessionService.MODE_DESKTOP ->
SessionPrefs.setOrientation(this@SessionActivity, "desktop", value)
else -> SessionPrefs.setOrientation(this@SessionActivity, value)
}
SessionPrefs.setOrientation(this@SessionActivity, value)
sessionOrientation = value
applyFollowOrientation(resources.configuration)
},
@@ -2736,7 +2724,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
oscTrackpads = SessionPrefs.oscTrackpads(this)
backHold = SessionPrefs.backHold(this)
dockedMenuController = SessionPrefs.dockedMenuController(this)
sessionOrientation = SessionPrefs.orientation(this, SessionState.mode)
sessionOrientation = SessionPrefs.orientation(this)
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
@@ -3002,7 +2990,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
CompositorHost.startOrAttach(
this, holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), compositorFpsLimit(),
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(),
)
onOutputAttached(holder)
if (SessionState.running && size != previous) {
@@ -3068,7 +3056,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
WaylandCompositor.nativeResizeOutput(size.first, size.second)
}
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this, SessionState.mode)
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
private fun applyFollowChoice() {
val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first }
@@ -3077,7 +3065,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun applyFollowOrientation(config: android.content.res.Configuration) {
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp, SessionState.mode)
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp)
if (requestedOrientation != wanted) requestedOrientation = wanted
}
@@ -3140,13 +3128,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun displayMode(): String = SessionPrefs.displayMode(this,
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this, SessionState.mode) && !controlsBelowWanted()
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted()
private fun outputSize(): Pair<Int, Int> =
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
resolutionChoice(), portraitOutput())
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this, SessionState.mode)): String {
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String {
val mode = displayMode()
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
@@ -3193,18 +3181,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun outputFpsLimit(): Int = outputFpsLimit(pipUi)
// Android holds the window to the Game Mode override while the panel runs faster; the guest paces to the panel,
// so without this cap every frame past the override is drawn and dropped.
private fun hostFrameCap(): Int {
if (glassesScreen != null || bottomOutputActive) return 0
val display = (if (Build.VERSION.SDK_INT >= 30) display else @Suppress("DEPRECATION") windowManager.defaultDisplay) ?: return 0
return SessionPrefs.hostFrameCap(display.refreshRate, display.mode.refreshRate)
}
private fun compositorFpsLimit(): Int = SessionPrefs.compositorFpsLimit(
mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pipUi, hostFrameCap(),
)
private fun outputFpsLimit(pip: Boolean): Int =
SessionPrefs.compositorFpsLimit(mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pip)
@@ -3242,7 +3218,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
)
val hz = refreshHz()
val changed = kotlin.math.abs(SessionState.refreshHz - hz) > 0.1f
CompositorHost.updatePacing(hz, compositorFpsLimit())
CompositorHost.updatePacing(hz, outputFpsLimit())
pushCardboard(activeCardboard)
if (changed && ::surfaceView.isInitialized) applyFrameGen()
}
@@ -3813,7 +3789,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab.
val pages = sessionDrawerPages(achievementsInFront != null)
val pages = sessionDrawerPages(glasses.present)
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
releaseDrawerDirection()
}
@@ -4969,7 +4945,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun refreshControls() {
padConnected = controllerConnected()
applyUnfoldedControls()
updateOnScreenControls()
}
@@ -6410,7 +6385,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
(getSystemService(INPUT_SERVICE) as? InputManager)
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
padConnected = controllerConnected()
padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this))
refreshSecondScreenDisplays()
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
@@ -586,7 +586,8 @@ object AddedGames {
}.getOrNull()
fun writeListing(context: Context, games: List<Game>,
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context)) +
com.droiddeck.launcher.runtime.RecompShortcuts.listing(context)): File {
val file = listingFile(context).apply { parentFile?.mkdirs() }
val json = StringBuilder("[")
games.forEachIndexed { i, g ->
@@ -248,11 +248,14 @@ object Library {
AddedGames.guestPath(context, g.folder).let { it == null || it !in claimed })
}
val played = shortcutsLastPlayed(SessionPrefs.steamRoot(context, arch))
return (steam + own.map { g -> addedGame(context, g, roots, played[g.appId] ?: 0L) }).distinctBy { it.gameId }
val recomps = com.droiddeck.launcher.runtime.RecompShortcuts.library(context) { appId, gameId ->
maxOf(played[appId] ?: 0L, recordedPlay(context, gameId))
}
return (steam + own.map { g -> addedGame(context, g, roots, played[g.appId] ?: 0L) } + recomps).distinctBy { it.gameId }
}
fun recordPlayed(context: Context, game: SteamGame) {
if (game.library == ADDED) recordPlayed(context, game.gameIdString)
if (game.library == ADDED || game.library == com.droiddeck.launcher.runtime.RecompShortcuts.SOURCE) recordPlayed(context, game.gameIdString)
}
fun recordPlayed(context: Context, gameId: String) {
@@ -0,0 +1,146 @@
package com.droiddeck.launcher.runtime
import android.util.JsonReader
import android.util.JsonToken
import java.io.File
import java.io.Reader
// Decomp Buddy's plans.json (about 16 MB) holds, per repo and platform, the release file to download, the
// program in it and the game files it needs. It is read as a stream, keeping only those fields.
object DecompBuddyPlans {
class GameFile(
val label: String, val filename: String?, val how: String?, val kind: String?,
val hashes: List<Pair<String, String>> = emptyList(), val size: Long = 0,
)
class Target(
val gameTitle: String?, val method: String?, val asset: String?, val tag: String?, val executable: String?,
val sha256: String?, val pkg: String?, val files: List<GameFile>,
)
class Plan(val tag: String?, val targets: Map<String, Target>)
private val WANTED = setOf("windows", "linux", "linux-arm64", "android")
fun read(file: File): Map<String, Plan> = file.bufferedReader().use { read(it) }
fun read(source: Reader): Map<String, Plan> {
val out = HashMap<String, Plan>()
JsonReader(source).use { r ->
r.beginObject()
while (r.hasNext()) {
if (r.nextName() != "plans" || r.peek() != JsonToken.BEGIN_OBJECT) { r.skipValue(); continue }
r.beginObject()
while (r.hasNext()) {
val key = r.nextName()
plan(r)?.let { out[key.lowercase()] = it }
}
r.endObject()
}
r.endObject()
}
return out
}
private fun JsonReader.str(): String? = if (peek() == JsonToken.STRING) nextString() else { skipValue(); null }
private fun plan(r: JsonReader): Plan? {
if (r.peek() != JsonToken.BEGIN_OBJECT) { r.skipValue(); return null }
var tag: String? = null
val targets = HashMap<String, Target>()
r.beginObject()
while (r.hasNext()) when (r.nextName()) {
"tag" -> tag = r.str()
"targets" -> if (r.peek() != JsonToken.BEGIN_OBJECT) r.skipValue() else {
r.beginObject()
while (r.hasNext()) {
val id = r.nextName()
if (id in WANTED) target(r)?.let { targets[id] = it } else r.skipValue()
}
r.endObject()
}
else -> r.skipValue()
}
r.endObject()
return if (targets.isEmpty()) null else Plan(tag, targets)
}
// A repo with several games under one target (a collection) is set up from its first.
private fun target(r: JsonReader): Target? {
if (r.peek() != JsonToken.BEGIN_OBJECT) { r.skipValue(); return null }
var first: Target? = null
r.beginObject()
while (r.hasNext()) {
if (r.nextName() != "games" || r.peek() != JsonToken.BEGIN_ARRAY) { r.skipValue(); continue }
r.beginArray()
while (r.hasNext()) { val g = game(r); if (first == null) first = g }
r.endArray()
}
r.endObject()
return first
}
private fun game(r: JsonReader): Target? {
if (r.peek() != JsonToken.BEGIN_OBJECT) { r.skipValue(); return null }
var title: String? = null
var method: String? = null; var asset: String? = null; var tag: String? = null
var exe: String? = null; var sha: String? = null; var pkg: String? = null
val files = mutableListOf<GameFile>()
r.beginObject()
while (r.hasNext()) when (r.nextName()) {
"game_title" -> title = r.str()
"build" -> if (r.peek() != JsonToken.BEGIN_OBJECT) r.skipValue() else {
r.beginObject()
while (r.hasNext()) when (r.nextName()) {
"method" -> method = r.str()
"release_asset" -> asset = r.str()
"release_tag" -> tag = r.str()
"executable" -> exe = r.str()
"package_id" -> pkg = r.str()
"scanned" -> if (r.peek() != JsonToken.BEGIN_OBJECT) r.skipValue() else {
r.beginObject()
while (r.hasNext()) if (r.nextName() == "sha256") sha = r.str() else r.skipValue()
r.endObject()
}
else -> r.skipValue()
}
r.endObject()
}
"game_files" -> if (r.peek() != JsonToken.BEGIN_ARRAY) r.skipValue() else {
r.beginArray()
while (r.hasNext()) {
if (r.peek() != JsonToken.BEGIN_OBJECT) { r.skipValue(); continue }
var label = ""; var name: String? = null; var how: String? = null; var kind: String? = null
val hashes = mutableListOf<Pair<String, String>>(); var size = 0L
r.beginObject()
while (r.hasNext()) when (r.nextName()) {
"label" -> label = r.str().orEmpty()
"expected_filename" -> name = r.str()
"how_provided" -> how = r.str()
"kind" -> kind = r.str()
"expected_size" -> size = if (r.peek() == JsonToken.NUMBER) r.nextLong() else { r.skipValue(); 0L }
"expected_hashes" -> if (r.peek() != JsonToken.BEGIN_ARRAY) r.skipValue() else {
r.beginArray()
while (r.hasNext()) {
if (r.peek() != JsonToken.BEGIN_OBJECT) { r.skipValue(); continue }
var algo: String? = null; var value: String? = null
r.beginObject()
while (r.hasNext()) when (r.nextName()) { "algo" -> algo = r.str(); "value" -> value = r.str(); else -> r.skipValue() }
r.endObject()
if (algo != null && value != null) hashes += algo to value
}
r.endArray()
}
else -> r.skipValue()
}
r.endObject()
files += GameFile(label, name, how, kind, hashes, size)
}
r.endArray()
}
else -> r.skipValue()
}
r.endObject()
return Target(title, method, asset, tag, exe, sha, pkg, files)
}
}
@@ -38,11 +38,6 @@ object ElfSeccompPatch {
val end = minOf(data.size, buffer.getLong(at + 8).toInt() + buffer.getLong(at + 32).toInt()) and 3.inv()
var pos = start
while (pos + 4 <= end) {
if (patchTermiosRequest(buffer, pos, end)) {
patched++
pos += 4
continue
}
val replacement = when (buffer.getInt(pos)) {
MOV_X8_SET_ROBUST_LIST -> NOP
MOV_X8_CLONE3, MOV_X8_RSEQ -> MOV_X0_ENOSYS
@@ -70,40 +65,6 @@ object ElfSeccompPatch {
return patched
}
/**
* glibc 2.42 and later read and set a terminal with TCGETS2 and TCSETS2/W2/F2, which Android's
* SELinux policy refuses on an app's pseudo-terminal slaves (EACCES): isatty() was false in every
* Konsole, ssh and tmux session, so bash had no prompt or job control and stdout was not line
* buffered. TCGETS and TCSETS* carry the same struct without its two speed fields, which glibc
* then takes from c_cflag. A site is `movz xN, #lo` then `movk xN, #hi, lsl #16`; the movz gets
* the old request and the movk becomes a no-op.
*/
private fun patchTermiosRequest(buffer: ByteBuffer, pos: Int, end: Int): Boolean {
val movz = buffer.getInt(pos)
if ((movz and 0x7fe00000) != 0x52800000) return false
val low = (movz ushr 5) and 0xffff
if (low !in 0x542a..0x542d) return false
val register = movz and 0x1f
var next = pos + 4
while (next < minOf(end, pos + 4 + 4 * 4)) {
val movk = buffer.getInt(next)
if ((movk and 0x7fe00000) == 0x72a00000 && (movk and 0x1f) == register) {
val request = when ((movk ushr 5) and 0xffff) {
0x802c -> if (low == 0x542a) 0x5401 else return false
0x402c -> if (low != 0x542a) 0x5402 + (low - 0x542b) else return false
else -> return false
}
buffer.putInt(pos, (movz and 0x1f.inv() and (0xffff shl 5).inv()) or (request shl 5) or register)
buffer.putInt(next, NOP)
return true
}
// Anything between that might read or write the register would see the old low half
if (intArrayOf(0, 5, 10, 16).any { (movk ushr it) and 0x1f == register }) return false
next += 4
}
return false
}
/** Patches the file behind [path] (symlinks followed) if it still has unpatched call sites. */
fun patchFile(path: File): Int {
val target = path.canonicalFile
@@ -0,0 +1,145 @@
package com.droiddeck.launcher.runtime
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageInstaller
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.widget.Toast
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.update.SelfInstaller
import java.io.File
object RecompAndroid {
const val ACTION_STATUS = "com.droiddeck.launcher.recomps.INSTALL_STATUS"
private const val RECORDS = "recomps-android"
private const val INCOMPATIBLE = "incompatible"
@Volatile private var registered = false
@Volatile var onChanged: () -> Unit = {}
// Why the last install of each package failed, in words for the player.
@Volatile var onFailed: (pkg: String, message: String) -> Unit = { _, _ -> }
private val sessions = java.util.concurrent.ConcurrentHashMap<Int, Pair<String, String>>()
private fun incompatibleFile(context: Context) = File(File(context.filesDir, RECORDS).apply { mkdirs() }, INCOMPATIBLE)
// Packages whose APK has no code for this device's CPUs, found when one was downloaded or refused.
fun incompatible(context: Context): Set<String> =
FileUtils.readString(incompatibleFile(context))?.lines()?.map { it.trim() }?.filter { it.isNotEmpty() }?.toSet().orEmpty()
private fun markIncompatible(context: Context, pkg: String) {
val now = incompatible(context) + pkg
FileUtils.writeString(incompatibleFile(context), now.joinToString("\n"))
}
// The CPUs an APK has native code for, from its lib/<abi>/ folders; empty when it has none (Java only).
internal fun apkAbis(apk: File): Set<String> = runCatching {
java.util.zip.ZipFile(apk).use { zip ->
zip.entries().asSequence().map { it.name }.filter { it.startsWith("lib/") }.mapNotNull { it.split('/').getOrNull(1)?.takeIf { a -> a.isNotEmpty() } }.toSet()
}
}.getOrDefault(emptySet())
internal fun fits(abis: Set<String>, device: List<String>): Boolean = abis.isEmpty() || abis.any { it in device }
private fun record(context: Context, pkg: String) = File(File(context.filesDir, RECORDS), pkg)
fun installed(context: Context, entries: List<RecompCatalog.Entry>): Map<String, RecompInstaller.Installed> {
val pm = context.packageManager
return entries.mapNotNull { e ->
val pkg = e.android?.pkg ?: return@mapNotNull null
runCatching { pm.getPackageInfo(pkg, 0) }.getOrNull() ?: return@mapNotNull null
val lines = FileUtils.readString(record(context, pkg))?.lines().orEmpty()
e.id to RecompInstaller.Installed(e.id, "android:$pkg", lines.getOrNull(0)?.takeIf { it.isNotEmpty() },
lines.getOrNull(1), RecompCatalog.Platform.ANDROID.key, record(context, pkg))
}.toMap()
}
// Runs on a worker thread. The APK must carry the package name and signing certificate the catalog
// names, so a replaced release asset cannot install as, or over, a different app.
fun install(context: Context, entry: RecompCatalog.Entry, build: RecompCatalog.Build, release: RecompInstaller.Release, apk: File): String? {
val pkg = build.pkg ?: return context.getString(R.string.recomps_apk_mismatch)
val abis = apkAbis(apk)
val device = Build.SUPPORTED_ABIS.toList()
if (!fits(abis, device)) {
markIncompatible(context, pkg)
return context.getString(R.string.recomps_apk_wrong_cpu, abis.sorted().joinToString(", "), device.joinToString(", "))
}
if (!SelfInstaller.canInstall(context)) {
context.startActivity(SelfInstaller.permissionIntent(context).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
return context.getString(R.string.recomps_allow_installs)
}
val flags = if (Build.VERSION.SDK_INT >= 28) PackageManager.GET_SIGNING_CERTIFICATES else @Suppress("DEPRECATION") PackageManager.GET_SIGNATURES
val info = context.packageManager.getPackageArchiveInfo(apk.path, flags) ?: return context.getString(R.string.recomps_apk_mismatch)
if (info.packageName != pkg) return context.getString(R.string.recomps_apk_mismatch)
if (build.signer != null && build.signer !in SelfInstaller.archiveSignerDigests(info)) return context.getString(R.string.recomps_apk_mismatch)
listen(context)
FileUtils.writeString(record(context, pkg).apply { parentFile?.mkdirs() }, "${release.tag}\n${release.published}\n")
SelfInstaller.install(context, apk, pkg, ACTION_STATUS) { id -> sessions[id] = pkg to entry.name }
return null
}
fun launch(context: Context, pkg: String): Boolean {
val intent = context.packageManager.getLaunchIntentForPackage(pkg) ?: return false
return runCatching { context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }.isSuccess
}
fun uninstall(context: Context, pkg: String) {
record(context, pkg).delete()
runCatching {
context.startActivity(Intent(Intent.ACTION_DELETE, Uri.parse("package:$pkg")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
private fun listen(context: Context) {
if (registered) return
registered = true
val app = context.applicationContext
val receiver = object : BroadcastReceiver() {
override fun onReceive(c: Context, intent: Intent) {
val session = intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1)
val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)
val (pkg, name) = (if (status == PackageInstaller.STATUS_PENDING_USER_ACTION) sessions[session] else sessions.remove(session))
?: (intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME).orEmpty() to "")
when (status) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
confirm?.let { SelfInstaller.safeConfirmIntent(app, it) }?.let { runCatching { app.startActivity(it) } }
}
PackageInstaller.STATUS_SUCCESS -> onChanged()
else -> {
val raw = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)
if (raw?.contains("NO_MATCHING_ABIS") == true && pkg.isNotEmpty()) markIncompatible(app, pkg)
val message = failure(app, status, raw)
Toast.makeText(app, if (name.isNotEmpty()) app.getString(R.string.recomps_apk_failed_named, name, message) else message,
Toast.LENGTH_LONG).show()
if (pkg.isNotEmpty()) onFailed(pkg, message)
onChanged()
}
}
}
}
val filter = IntentFilter(ACTION_STATUS)
if (Build.VERSION.SDK_INT >= 33) app.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
else app.registerReceiver(receiver, filter)
}
// What went wrong, in words: Android's own status message names the cause but not what to do about it.
internal fun failure(context: Context, status: Int, message: String?): String = when {
message?.contains("NO_MATCHING_ABIS") == true || status == PackageInstaller.STATUS_FAILURE_INCOMPATIBLE ->
context.getString(R.string.recomps_apk_fail_cpu, Build.SUPPORTED_ABIS.joinToString(", "))
message?.contains("UPDATE_INCOMPATIBLE") == true || status == PackageInstaller.STATUS_FAILURE_CONFLICT ->
context.getString(R.string.recomps_apk_fail_conflict)
message?.contains("VERSION_DOWNGRADE") == true -> context.getString(R.string.recomps_apk_fail_downgrade)
status == PackageInstaller.STATUS_FAILURE_STORAGE -> context.getString(R.string.recomps_apk_fail_storage)
status == PackageInstaller.STATUS_FAILURE_ABORTED -> context.getString(R.string.recomps_apk_fail_cancelled)
status == PackageInstaller.STATUS_FAILURE_BLOCKED -> context.getString(R.string.recomps_apk_fail_blocked)
status == PackageInstaller.STATUS_FAILURE_INVALID -> context.getString(R.string.recomps_apk_fail_invalid)
else -> context.getString(R.string.recomps_apk_fail_other, message ?: status.toString())
}
}
@@ -0,0 +1,369 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.FileUtils
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
// The list is Decomp Buddy's, Recomp Launcher's and Recompa's own catalogs, read as their apps publish them.
// DroidDeck keeps no catalog of its own: it caches each feed, revalidates it with its ETag, and merges them by
// GitHub repo, in that order of precedence.
object RecompCatalog {
private const val TAG = "RecompCatalog"
private const val MAX_AGE_MS = 6L * 60 * 60 * 1000
class Feed(val id: String, val name: String, val url: String)
val DECOMP_BUDDY = Feed("decomp-buddy", "Decomp Buddy", "https://tanookistudios.com/decomp-buddy/catalog.json")
val DECOMP_BUDDY_PLANS = Feed("decomp-buddy-plans", "Decomp Buddy", "https://tanookistudios.com/decomp-buddy/plans.json")
val RECOMP_LAUNCHER = Feed("recomp-launcher", "Recomp Launcher", "https://recomplauncher.com/pc-catalog.json")
val RECOMPA = Feed("recompa", "Recompa", "https://recompa.app/index.json")
const val DECOMP_BUDDY_ENABLED = true
// Decomp Buddy also keeps copies of projects taken down by a legal notice; using them is off until that is decided.
const val DECOMP_BUDDY_MIRROR = false
val FEEDS = listOfNotNull(DECOMP_BUDDY.takeIf { DECOMP_BUDDY_ENABLED }, RECOMP_LAUNCHER, RECOMPA)
private val DOWNLOADS = listOfNotNull(
DECOMP_BUDDY.takeIf { DECOMP_BUDDY_ENABLED }, DECOMP_BUDDY_PLANS.takeIf { DECOMP_BUDDY_ENABLED }, RECOMP_LAUNCHER, RECOMPA,
)
// Decomp Buddy keeps a malware-scanned copy of each release file it plans, named by sha256. It is
// donation-funded, so the copy is used only when the project's own download is gone.
fun mirrorUrl(sha256: String, name: String) = "https://files.decompbuddy.com/$sha256/${android.net.Uri.encode(name)}"
val mirrorEnabled get() = DECOMP_BUDDY_ENABLED && DECOMP_BUDDY_MIRROR
enum class Platform(val key: String) {
LINUX_ARM64("linux-arm64"), LINUX_X64("linux-x64"), WINDOWS_X64("windows-x64"), ANDROID("android");
companion object {
fun of(key: String) = entries.firstOrNull { it.key == key }
}
}
// Native arm64 Linux first, then an Android APK, then x86-64 Linux through FEX, then Windows through Proton.
val PREFERENCE = listOf(Platform.LINUX_ARM64, Platform.ANDROID, Platform.LINUX_X64, Platform.WINDOWS_X64)
class Build(
val platform: Platform, val asset: Regex, val entry: String = "",
val file: String? = null, val sha256: String? = null, val url: String? = null,
val pkg: String? = null, val signer: String? = null, val tag: String? = null, val published: String = "",
val mirrored: Boolean = false,
)
enum class DataKind { ROM, DUMP, NONE }
class Hash(val algo: String, val value: String)
// [file] is a file the port needs inside the game's folder (a relative path), which finds that folder in a
// store install; [hashes] and [size], when a catalog gives them, tell the right version of it from another.
class Data(
val kind: DataKind, val label: String, val sha1: List<String> = emptyList(), val note: String = "", val file: String? = null,
val hashes: List<Hash> = emptyList(), val size: Long = 0,
)
class Entry(
val id: String, val name: String, val game: String, val origin: String, val type: String,
val repo: String, val license: String, val homepage: String, val art: String?,
val builds: List<Build>, val data: Data,
val sources: List<String>, val popularity: Long = 0, val setup: String? = null, val igdb: String? = null,
val cover: String? = null, val updated: String = "", val listed: String = "",
) {
fun build(platform: Platform) = builds.firstOrNull { it.platform == platform }
fun preferred(): Build? = PREFERENCE.firstNotNullOfOrNull { build(it) }
// The preferred build, passing over an Android one whose package cannot install on this device.
fun preferred(incompatible: Set<String>): Build? =
PREFERENCE.firstNotNullOfOrNull { p -> build(p)?.takeIf { it.pkg == null || it.pkg !in incompatible } }
val android get() = build(Platform.ANDROID)
val pc get() = origin in PC_ORIGINS
}
@Volatile private var cached: List<Entry>? = null
fun load(context: Context, refresh: Boolean = false): List<Entry> {
if (!refresh) cached?.let { return it }
val dir = File(context.filesDir, "recomps").apply { mkdirs() }
val files = DOWNLOADS.associateWith { feed -> runCatching { fetch(feed, dir, refresh) }.onFailure { Log.w(TAG, "${feed.id}: $it") }.getOrNull() }
fun <T> read(feed: Feed, parse: (File) -> List<T>): List<T> =
files[feed]?.let { f -> runCatching { parse(f) }.onFailure { Log.w(TAG, "${feed.id}: $it") }.getOrNull() }.orEmpty()
val plans = files[DECOMP_BUDDY_PLANS]?.let { f -> runCatching { DecompBuddyPlans.read(f) }.onFailure { Log.w(TAG, "plans: $it") }.getOrNull() }.orEmpty()
val list = shareIgdb(merge(
read(DECOMP_BUDDY) { fromDecompBuddy(JSONObject(it.readText()), plans) },
read(RECOMP_LAUNCHER) { fromRecompLauncher(JSONObject(it.readText())) },
read(RECOMPA) { fromRecompa(JSONObject(it.readText())) },
))
if (list.isNotEmpty()) cached = list
return list
}
private fun fetch(feed: Feed, dir: File, force: Boolean): File? {
val file = File(dir, "${feed.id}.json")
val etag = File(dir, "${feed.id}.etag")
if (!force && file.isFile && System.currentTimeMillis() - file.lastModified() < MAX_AGE_MS) return file
val conn = (URL(feed.url).openConnection() as HttpURLConnection).apply {
connectTimeout = 15_000; readTimeout = 60_000
setRequestProperty("User-Agent", "DroidDeck")
if (file.isFile) FileUtils.readString(etag)?.trim()?.takeIf { it.isNotEmpty() }?.let { setRequestProperty("If-None-Match", it) }
}
return try {
when (conn.responseCode) {
HttpURLConnection.HTTP_NOT_MODIFIED -> { file.setLastModified(System.currentTimeMillis()); file }
HttpURLConnection.HTTP_OK -> {
val tmp = File(dir, "${feed.id}.json.part")
conn.inputStream.use { input -> tmp.outputStream().use { input.copyTo(it) } }
tmp.renameTo(file)
conn.getHeaderField("ETag")?.let { FileUtils.writeString(etag, it) }
file
}
else -> file.takeIf { it.isFile }
}
} catch (e: Exception) {
Log.w(TAG, "${feed.id}: $e")
file.takeIf { it.isFile }
} finally {
conn.disconnect()
}
}
private val ORIGINS = mapOf(
"pc" to "PC", "n64" to "N64", "x360" to "Xbox 360", "xbox360" to "Xbox 360", "xbox" to "Xbox", "ps1" to "PS1", "ps2" to "PS2",
"ps3" to "PS3", "ps4" to "PS4", "switch" to "Switch", "switch2" to "Switch 2", "snes" to "SNES", "nes" to "NES", "gc" to "GameCube",
"wii" to "Wii", "gba" to "GBA", "nds" to "DS", "ds" to "DS", "3ds" to "3DS", "arcade" to "Arcade", "dreamcast" to "Dreamcast",
"saturn" to "Saturn", "genesis" to "Genesis", "psp" to "PSP", "vita" to "Vita", "gb" to "Game Boy", "gbc" to "Game Boy Color",
)
private val ARCHIVE = Regex("\\.(zip|7z|tar|tgz|tar\\.(gz|xz|bz2|zst)|appimage|exe)$", RegexOption.IGNORE_CASE)
private val REPO = Regex("[\\w.-]+/[\\w.-]+")
private val SHA256 = Regex("[0-9a-f]{64}")
private val SHA1 = Regex("[0-9a-f]{40}")
private val PACKAGE = Regex("[A-Za-z][\\w]*(\\.[A-Za-z][\\w]*)+")
private val GITHUB = Regex("^https?://github\\.com/([\\w.-]+/[\\w.-]+?)(?:\\.git)?/?$")
private val HUBS = setOf("io.github.kalasyan.recompa")
private fun origin(code: String) = code.lowercase().let { ORIGINS[it] ?: if (it == "other") "" else it.uppercase() }
private fun safeName(s: String?) = s?.takeIf { it.isNotEmpty() && '/' !in it && it != "." && it != ".." }
// A file path inside the game's folder: relative, forward slashes, no parent steps.
internal fun safePath(s: String?): String? = s?.replace('\\', '/')?.trim('/')
?.takeIf { p -> p.isNotEmpty() && p.split('/').none { it.isEmpty() || it == "." || it == ".." } && ':' !in p }
private val HASH_ALGOS = mapOf("sha1" to 40, "sha256" to 64, "md5" to 32, "crc32" to 8)
internal fun hash(algo: String?, value: String?): Hash? {
val a = algo?.lowercase() ?: return null
val v = value?.lowercase()?.takeIf { HASH_ALGOS[a] == it.length && it.all { c -> c in "0123456789abcdef" } } ?: return null
return Hash(a, v)
}
private val IGDB_URL = Regex("^https?://(?:www\\.)?igdb\\.com/games/([a-z0-9-]+)/?$")
private fun sha256(s: String?) = s?.lowercase()?.takeIf { SHA256.matches(it) }
internal fun globRegex(glob: String) =
Regex("^" + glob.split('*').joinToString(".*") { Regex.escape(it) } + "$", RegexOption.IGNORE_CASE)
private fun JSONObject.str(key: String) = optString(key).takeIf { it.isNotEmpty() && it != "null" }
private val PC_ORIGINS = setOf("PC", "DOS")
private val CONSOLES = mapOf(
"PC (Windows)" to "PC", "IBM PC (MS-DOS)" to "DOS", "PlayStation" to "PS1", "PlayStation 2" to "PS2", "PlayStation 3" to "PS3",
"PlayStation 4" to "PS4", "PlayStation Portable" to "PSP", "PlayStation Vita" to "Vita", "Nintendo 64" to "N64",
"Nintendo Switch" to "Switch", "Nintendo Switch 2" to "Switch 2", "Game Boy Advance" to "GBA", "Game Boy" to "Game Boy",
"Game Boy Color" to "Game Boy Color", "Nintendo DS" to "DS", "Nintendo 3DS" to "3DS", "Others" to "",
)
// Decomp Buddy's games with a published plan: the plan names the exact release file, its program and the
// game files it needs. Linux plans name the x86-64 file; its arm64 twin is looked for at install.
internal fun fromDecompBuddy(json: JSONObject, plans: Map<String, DecompBuddyPlans.Plan>): List<Entry> {
val games = json.optJSONArray("games") ?: return emptyList()
return (0 until games.length()).mapNotNull { i -> runCatching { decompBuddyGame(games.getJSONObject(i), plans) }.getOrNull() }
}
private fun decompBuddyGame(g: JSONObject, plans: Map<String, DecompBuddyPlans.Plan>): Entry? {
if (g.str("host") != "github") return null
val repo = g.str("repo")?.takeIf { REPO.matches(it) } ?: return null
val plan = plans[g.str("id")?.lowercase() ?: return null] ?: return null
fun build(platform: Platform, t: DecompBuddyPlans.Target?): Build? {
t ?: return null
if (t.method != "release") return null
val file = safeName(t.asset) ?: return null
if (platform == Platform.ANDROID && !file.endsWith(".apk", ignoreCase = true)) return null
if (platform == Platform.WINDOWS_X64 && Regex("arm64|aarch64|win32|x86(?![_-]64)|i[36]86", RegexOption.IGNORE_CASE).containsMatchIn(file)) return null
val exe = t.executable?.substringAfterLast('/')?.substringAfterLast('\\')
return Build(platform, Regex("^" + Regex.escape(file) + "$", RegexOption.IGNORE_CASE), safeName(exe).orEmpty(), file,
sha256(t.sha256), pkg = t.pkg?.takeIf { platform == Platform.ANDROID && PACKAGE.matches(it) },
tag = t.tag ?: plan.tag, published = g.str("updatedAt").orEmpty(), mirrored = sha256(t.sha256) != null)
}
val targets = plan.targets
val builds = listOfNotNull(
build(Platform.LINUX_ARM64, targets["linux-arm64"]),
build(Platform.LINUX_X64, targets["linux"])?.takeIf { b -> !Regex("arm64|aarch64", RegexOption.IGNORE_CASE).containsMatchIn(b.file!!) },
build(Platform.WINDOWS_X64, targets["windows"]),
build(Platform.ANDROID, targets["android"])?.takeIf { it.pkg != null },
)
if (builds.isEmpty()) return null
val first = targets["linux"] ?: targets["windows"] ?: targets.values.first()
val needs = first.files.firstOrNull { it.kind == null || it.kind == "game" }
val origin = g.str("console").orEmpty().let { CONSOLES[it] ?: it }
val data = when {
needs == null -> Data(DataKind.NONE, "")
else -> Data(if (origin in PC_ORIGINS) DataKind.DUMP else DataKind.ROM, needs.label, note = g.str("description").orEmpty(),
file = needs.filename?.takeIf { needs.how == "folder" || needs.how == "command_line" }?.let { safePath(it) },
hashes = needs.hashes.mapNotNull { (a, v) -> hash(a, v) }, size = needs.size)
}
val id = g.str("slug") ?: return null
return Entry(
id, g.str("title") ?: id, first.gameTitle ?: g.str("title") ?: id, origin,
if ("recomp" in repo.lowercase()) "recomp" else "port", repo, "", g.str("repoUrl") ?: "https://github.com/$repo",
g.str("iconUrl") ?: g.str("boxartUrl"), builds, data, listOf(DECOMP_BUDDY.id), g.optLong("downloads"),
cover = g.str("boxartUrl"), updated = g.str("updatedAt").orEmpty(), listed = g.str("listedAt").orEmpty(),
)
}
internal fun fromRecompLauncher(json: JSONObject): List<Entry> {
val apps = json.optJSONArray("apps") ?: return emptyList()
return (0 until apps.length()).mapNotNull { i -> runCatching { recompLauncherApp(apps.getJSONObject(i)) }.getOrNull() }
}
private fun recompLauncherApp(a: JSONObject): Entry? {
if (a.optBoolean("archived") || a.optBoolean("soon")) return null
if ((a.str("host") ?: "github") != "github") return null
val repo = a.str("repo")?.takeIf { REPO.matches(it) } ?: return null
val boot = a.optJSONObject("boot") ?: JSONObject()
if (boot.str("kind") in setOf("installer", "not-a-game", "source")) return null
val assets = a.optJSONObject("assets") ?: return null
val files = a.optJSONObject("files") ?: JSONObject()
val tag = a.str("tag")
val published = a.str("released_at").orEmpty()
val builds = listOf("linux", "windows").mapNotNull { os ->
val glob = assets.str(os) ?: return@mapNotNull null
if (glob.contains("flatpak", ignoreCase = true) || !ARCHIVE.containsMatchIn(glob)) return@mapNotNull null
val platform = when {
os == "linux" && Regex("aarch64|arm64", RegexOption.IGNORE_CASE).containsMatchIn(glob) -> Platform.LINUX_ARM64
os == "linux" -> Platform.LINUX_X64
Regex("arm64|aarch64|win32|x86(?![_-]64)", RegexOption.IGNORE_CASE).containsMatchIn(glob) -> return@mapNotNull null
else -> Platform.WINDOWS_X64
}
val start = if (os == "linux") boot.str("start_linux") else boot.str("start")?.takeIf { it.endsWith(".exe", ignoreCase = true) }
val pin = files.optJSONObject(os)
val file = safeName(pin?.str("name")) ?: safeName(glob.takeIf { '*' !in it && tag != null })
Build(platform, globRegex(glob), safeName(start).orEmpty(), file, sha256(pin?.str("sha256")), tag = tag, published = published)
}
if (builds.isEmpty()) return null
val what = boot.optJSONObject("files")?.str("what") ?: a.str("needs")
val inputs = a.optJSONObject("launcher")?.optJSONArray("inputs")
val game = (0 until (inputs?.length() ?: 0)).mapNotNull { inputs!!.optJSONObject(it) }
.firstOrNull { (it.str("role") ?: "game") == "game" || it.str("id") == "game" }
val check = game?.optJSONObject("check")?.str("file")?.let { safePath(it) }
val igdb = a.optJSONObject("about")?.str("url")?.let { IGDB_URL.find(it)?.groupValues?.get(1) }
val steps = a.optJSONArray("setup_steps")
val id = a.str("id") ?: return null
val setup = if (!a.optBoolean("setup_required")) null
else (0 until (steps?.length() ?: 0)).take(2).joinToString(" ") { steps!!.getString(it) }.ifEmpty { "" }
return Entry(
id, a.str("name") ?: id, a.str("game") ?: a.str("name") ?: id, origin(a.str("origin").orEmpty()),
if ("recomp" in (id + repo).lowercase()) "recomp" else "port", repo, a.str("license").orEmpty(),
"https://github.com/$repo", a.str("icon") ?: a.str("cover"), builds,
if (what != null) Data(DataKind.DUMP, what, note = a.str("blurb").orEmpty(), file = check) else Data(DataKind.NONE, ""),
listOf(RECOMP_LAUNCHER.id), a.optLong("downloads"), setup, igdb,
cover = a.str("cover"), updated = published, listed = a.str("added").orEmpty(),
)
}
internal fun fromRecompa(json: JSONObject): List<Entry> {
val ports = json.optJSONArray("ports") ?: return emptyList()
return (0 until ports.length()).mapNotNull { i -> runCatching { recompaPort(ports.getJSONObject(i)) }.getOrNull() }
}
private fun recompaPort(p: JSONObject): Entry? {
val req = p.optJSONObject("requirements") ?: JSONObject()
val abi = req.optJSONArray("abi")
if (abi != null && abi.length() > 0 && (0 until abi.length()).none { abi.getString(it) == "arm64-v8a" }) return null
if (req.optInt("min_sdk", 0) > android.os.Build.VERSION.SDK_INT) return null
val forks = p.optJSONArray("forks") ?: return null
val fork = (0 until forks.length()).map { forks.getJSONObject(it) }.filter { f ->
val asset = f.optJSONObject("release")?.optJSONObject("asset")
sha256(asset?.str("sha256")) != null && sha256(f.str("signer_sha256")) != null &&
f.str("package")?.let { PACKAGE.matches(it) } == true && asset?.str("url")?.startsWith("https://") == true
}.maxByOrNull { it.optLong("downloads") } ?: return null
if (fork.getString("package") in HUBS) return null
val release = fork.getJSONObject("release")
val asset = release.getJSONObject("asset")
val android = Build(
Platform.ANDROID, Regex("^" + Regex.escape(asset.getString("name")) + "$"), "", safeName(asset.str("name")),
sha256(asset.str("sha256")), asset.getString("url"), fork.getString("package"), sha256(fork.str("signer_sha256")),
release.str("tag"), release.str("published_at").orEmpty(),
)
val platform = p.str("original_platform").orEmpty()
val needs = p.optJSONArray("assets")?.optJSONObject(0)
val data = if (needs == null) Data(DataKind.NONE, "") else {
val accepted = needs.optJSONArray("accepted")
Data(
if (platform == "pc" || platform == "other") DataKind.DUMP else DataKind.ROM, needs.str("label").orEmpty(),
(0 until (accepted?.length() ?: 0)).mapNotNull { accepted!!.optJSONObject(it)?.str("sha1")?.lowercase()?.takeIf { s -> SHA1.matches(s) } },
needs.str("instructions_md")?.replace(Regex("[`*_#>\\[\\]]"), "")?.trim()?.lineSequence()?.firstOrNull().orEmpty(),
)
}
val repo = p.str("upstream")?.let { GITHUB.find(it)?.groupValues?.get(1) } ?: fork.str("repo")?.takeIf { REPO.matches(it) } ?: return null
val id = p.str("id") ?: return null
return Entry(
id, fork.str("name") ?: p.str("name") ?: id, p.str("game") ?: p.str("name") ?: id, origin(platform), p.str("type") ?: "port",
repo, "", "https://github.com/$repo", p.optJSONObject("art")?.str("icon") ?: p.optJSONObject("art")?.str("cover"), listOf(android), data,
listOf(RECOMPA.id), fork.optLong("downloads"),
cover = p.optJSONObject("art")?.str("cover"), updated = release.str("published_at").orEmpty(),
)
}
// An IGDB slug names the game, not the port, so other ports of a PC game take it from the one that has it,
// when the game's title leads to a single slug.
internal fun shareIgdb(list: List<Entry>): List<Entry> {
val slugs = list.filter { it.pc && it.igdb != null }.groupBy { RecompData.norm(it.game) }
.mapValues { (_, v) -> v.mapNotNull { it.igdb }.distinct().singleOrNull() }
return list.map { e ->
if (!e.pc || e.igdb != null) e
else slugs[RecompData.norm(e.game)]?.let { slug ->
Entry(e.id, e.name, e.game, e.origin, e.type, e.repo, e.license, e.homepage, e.art, e.builds, e.data, e.sources,
e.popularity, e.setup, slug, e.cover, e.updated, e.listed)
} ?: e
}
}
// An earlier catalog wins every field it sets; a later one with the same repo (or id) adds builds it lacks.
internal fun merge(vararg catalogs: List<Entry>): List<Entry> {
val out = LinkedHashMap<String, Entry>()
val byRepo = HashMap<String, String>()
for (e in catalogs.flatMap { it }) {
val base = (byRepo[e.repo.lowercase()] ?: e.id.takeIf { it in out })?.let { out[it] }
if (base == null) {
out[e.id] = e
byRepo.putIfAbsent(e.repo.lowercase(), e.id)
continue
}
val builds = base.builds.map { b ->
e.build(b.platform)?.takeIf { b.platform == Platform.ANDROID && b.signer == null && it.signer != null && it.pkg == b.pkg } ?: b
} + e.builds.filter { b -> base.builds.none { it.platform == b.platform } }
val b = base.data
val data = if (b.kind == DataKind.NONE) e.data else Data(
b.kind, b.label, b.sha1.ifEmpty { e.data.sha1 }, b.note,
b.file ?: e.data.file, if (b.file != null) b.hashes else e.data.hashes, if (b.file != null) b.size else e.data.size,
)
out[base.id] = Entry(
base.id, base.name, base.game, base.origin.ifEmpty { e.origin }, base.type, base.repo, base.license.ifEmpty { e.license },
base.homepage, base.art ?: e.art, builds, data,
(base.sources + e.sources).distinct(), maxOf(base.popularity, e.popularity), base.setup ?: e.setup, base.igdb ?: e.igdb,
base.cover ?: e.cover, maxOf(base.updated, e.updated), listOf(base.listed, e.listed).filter { it.isNotEmpty() }.minOrNull().orEmpty(),
)
}
return out.values.toList()
}
}
@@ -0,0 +1,196 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.steam.SteamClient
import com.droiddeck.launcher.stores.steam.SteamLibraryFolders
import org.json.JSONObject
import java.io.File
import java.security.MessageDigest
import java.util.zip.CRC32
// Whether the player already has the PC game a port needs. A store whose release IDs are known for the game
// (RecompStoreIds) is matched by ID only; any other store by title. A match counts once the file the catalog
// names is in the install, and is the right version when a catalog gives its hash or size.
object RecompData {
sealed class State {
object NotNeeded : State()
class BringYourOwn(val data: RecompCatalog.Data) : State()
class Found(val store: Store, val host: File, val guest: String, val exact: Boolean, val checked: Boolean) : State()
class Incomplete(val store: Store, val host: File, val file: String, val wrongVersion: Boolean) : State()
class Owned(val store: Store, val item: CatalogItem?, val exact: Boolean) : State()
}
class Install(val store: Store, val id: String?, val title: String, val host: File, val guest: String)
class Owner(val store: Store, val id: String?, val title: String, val item: CatalogItem?)
class Inputs(
val installs: List<Install>, val owned: List<Owner>,
val ids: Map<String, RecompStoreIds.Ids> = emptyMap(), val gogSlugs: Map<String, String> = emptyMap(),
val hasher: (File, String) -> String? = ::hashOf, val done: () -> Unit = {}, val cachedOnly: Boolean = false,
)
// Decomp Buddy's rules (src/stores.js): "Fallout 2: A Post Nuclear Role Playing Game" is Fallout 2, "Fallout 2" is
// not Fallout, a possessive in front ("Sid Meier's Civilization II") is dropped, and only store editions such as
// GOTY or Gold may follow the title.
private val EDITION = Regex("^ (?:goty|game of the year|gold|complete|deluxe|definitive|anniversary|steam)(?: edition)?$")
internal fun norm(title: String): String = title.lowercase().replace(Regex("[™®©]"), "").replace("&", " and ")
.replace(Regex("\\([^)]*\\)"), " ").replace(Regex("^[\\w.]+(?: [\\w.]+)?'s "), "")
.replace(Regex("[^a-z0-9:–-]+"), " ").replace(Regex("\\s+"), " ").trim()
internal fun sameGame(wanted: String, store: String): Boolean {
val t = norm(wanted).takeIf { it.isNotEmpty() } ?: return false
val n = norm(store)
return n == t || listOf(":", " -", " –", " :").any { n.startsWith(t + it) } || (n.startsWith("$t ") && EDITION.matches(n.substring(t.length)))
}
enum class Match { EXACT, TITLE }
internal fun match(entry: RecompCatalog.Entry, inputs: Inputs, store: Store, id: String?, title: String): Match? {
val known = entry.igdb?.let { inputs.ids[it] }?.of(store).orEmpty()
if (known.isEmpty()) return if (sameGame(entry.game, title)) Match.TITLE else null
val key = when (store) {
Store.STEAM -> id
Store.GOG -> id?.let { inputs.gogSlugs[it] }
else -> null
} ?: return if (store == Store.EPIC && sameGame(entry.game, title)) Match.TITLE else null
return if (key.lowercase() in known) Match.EXACT else null
}
// The file a catalog names, as a relative path matched without case, up to 4 folders below [dir].
internal fun locate(dir: File, path: String): File? {
val parts = path.split('/').filter { it.isNotEmpty() }
if (parts.isEmpty()) return null
var level = listOf(dir)
repeat(5) {
for (d in level) resolve(d, parts)?.let { return it }
level = level.flatMap { d -> d.listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty() }
}
return null
}
private fun resolve(base: File, parts: List<String>): File? {
var cur = base
for ((i, part) in parts.withIndex()) {
val next = File(cur, part).takeIf { it.exists() } ?: cur.listFiles()?.firstOrNull { it.name.equals(part, ignoreCase = true) } ?: return null
if (i < parts.lastIndex && !next.isDirectory) return null
cur = next
}
return cur.takeIf { it.isFile }
}
private fun folderOf(found: File, path: String): File {
var dir = found.parentFile!!
repeat(path.split('/').filter { it.isNotEmpty() }.size - 1) { dir = dir.parentFile ?: dir }
return dir
}
// null: a hash is needed but not known yet (the bulk pass reads only hashes already cached).
private fun rightVersion(data: RecompCatalog.Data, file: File, inputs: Inputs): Boolean? {
if (data.size > 0 && file.length() != data.size) return false
if (data.hashes.isEmpty()) return true
var unknown = false
for (h in data.hashes) {
val got = inputs.hasher(file, h.algo)
if (got == null) unknown = true else if (got.equals(h.value, ignoreCase = true)) return true
}
return if (unknown && inputs.cachedOnly) null else false
}
fun resolve(entry: RecompCatalog.Entry, inputs: Inputs): State {
if (entry.pc) {
val file = entry.data.file
var incomplete: State.Incomplete? = null
val installs = inputs.installs.mapNotNull { i -> match(entry, inputs, i.store, i.id, i.title)?.let { i to it } }
.sortedBy { it.second.ordinal }
for ((install, how) in installs) {
if (file == null) return State.Found(install.store, install.host, install.guest, how == Match.EXACT, checked = false)
val found = locate(install.host, file)
if (found == null) {
incomplete = incomplete ?: State.Incomplete(install.store, install.host, file, wrongVersion = false)
continue
}
val right = rightVersion(entry.data, found, inputs)
if (right == false) {
incomplete = State.Incomplete(install.store, install.host, file, wrongVersion = true)
continue
}
val dir = folderOf(found, file)
val rel = dir.relativeTo(install.host).invariantSeparatorsPath.trim('/')
return State.Found(install.store, dir, if (rel.isEmpty() || rel == ".") install.guest else "${install.guest.trimEnd('/')}/$rel",
how == Match.EXACT, checked = right == true)
}
incomplete?.let { return it }
inputs.owned.mapNotNull { o -> match(entry, inputs, o.store, o.id, o.title)?.let { o to it } }.minByOrNull { it.second.ordinal }
?.let { (o, how) -> return State.Owned(o.store, o.item, how == Match.EXACT) }
}
return if (entry.data.kind == RecompCatalog.DataKind.NONE) State.NotNeeded else State.BringYourOwn(entry.data)
}
fun inputs(
context: Context, steamOwned: Collection<Pair<Int, String>>, entries: List<RecompCatalog.Entry>, offline: Boolean = false,
cachedOnly: Boolean = false,
): Inputs {
val root = LinuxRuntime.rootDir(context)
val installs = mutableListOf<Install>()
StoresState.installed.forEach { game ->
installs += Install(game.sidecar.store, game.sidecar.id, game.sidecar.title, game.folder, guestPath(context, root, game.folder))
}
runCatching {
SteamLibraryFolders.installed(SteamClient.libraries(context)).forEach { (appId, app) ->
val dir = app.installDir ?: return@forEach
installs += Install(Store.STEAM, appId.toString(), app.name, File(app.library.host, "steamapps/common/$dir"),
"${app.library.guest.trimEnd('/')}/steamapps/common/$dir")
}
}
val owned = StoresState.library.flatMap { (store, list) -> list.filter { it.accessible }.map { Owner(store, it.id, it.title, it) } } +
steamOwned.map { (appId, name) -> Owner(Store.STEAM, appId.toString(), name, null) }
val ids = runCatching { RecompStoreIds.forGames(context, entries.filter { it.pc }.mapNotNull { it.igdb }, offline) }.getOrDefault(emptyMap())
val gogIds = installs.filter { it.store == Store.GOG }.mapNotNull { it.id } + owned.filter { it.store == Store.GOG }.mapNotNull { it.id }
val gogSlugs = if (ids.values.any { it.gog.isNotEmpty() }) runCatching { RecompStoreIds.gogSlugs(context, gogIds, offline) }.getOrDefault(emptyMap()) else emptyMap()
val hashes = HashCache(File(File(context.filesDir, "recomps"), "hashes.json"))
return Inputs(installs, owned, ids, gogSlugs, { f, algo -> if (cachedOnly) hashes.cached(f, algo) else hashes.get(f, algo) }, hashes::save, cachedOnly)
}
private fun guestPath(context: Context, root: File, host: File): String {
val r = root.absolutePath.trimEnd('/')
val h = host.absolutePath
return if (h.startsWith("$r/")) h.removePrefix(r) else StoreInstallRoot.guestPath(context, host)
}
internal fun hashOf(file: File, algo: String): String? = runCatching {
if (algo == "crc32") {
val crc = CRC32()
file.inputStream().buffered(1 shl 16).use { input -> val buf = ByteArray(1 shl 16); while (true) { val n = input.read(buf); if (n < 0) break; crc.update(buf, 0, n) } }
"%08x".format(crc.value)
} else {
val md = MessageDigest.getInstance(when (algo) { "sha1" -> "SHA-1"; "sha256" -> "SHA-256"; "md5" -> "MD5"; else -> return@runCatching null })
file.inputStream().buffered(1 shl 16).use { input -> val buf = ByteArray(1 shl 16); while (true) { val n = input.read(buf); if (n < 0) break; md.update(buf, 0, n) } }
md.digest().joinToString("") { "%02x".format(it) }
}
}.getOrNull()
// Hashing a large game file is slow, so each answer is kept until the file's size or modified time changes.
private class HashCache(private val file: File) {
private val json = runCatching { JSONObject(file.readText()) }.getOrDefault(JSONObject())
private var dirty = false
fun cached(f: File, algo: String): String? = json.optString("${f.absolutePath}|${f.length()}|${f.lastModified()}|$algo").takeIf { it.isNotEmpty() }
fun get(f: File, algo: String): String? {
val key = "${f.absolutePath}|${f.length()}|${f.lastModified()}|$algo"
json.optString(key).takeIf { it.isNotEmpty() }?.let { return it }
return hashOf(f, algo)?.also { json.put(key, it); dirty = true }
}
fun save() {
if (dirty) runCatching { file.parentFile?.mkdirs(); FileUtils.writeString(file, json.toString()) }
}
}
}
@@ -0,0 +1,307 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.system.Os
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.GameExePicker
import com.droiddeck.launcher.stores.StoreInstallRoot
import org.json.JSONArray
import java.io.File
import java.io.RandomAccessFile
object RecompInstaller {
const val META_ID = "recomp-id"
const val META_TAG = "recomp-tag"
const val META_PUBLISHED = "recomp-published"
const val META_PLATFORM = "recomp-platform"
const val META_REPO = "recomp-repo"
const val WRAPPER = "droiddeck-recomp"
private const val WINDOWS_DIR = "Recomps"
private const val NESTED_LIMIT = 3
private val ARCHIVE = Regex("\\.(zip|7z|tar|tgz|deb|tar\\.(gz|xz|bz2|zst))$", RegexOption.IGNORE_CASE)
class Release(val tag: String, val published: String, val asset: String, val url: String, val sha256: String?)
class Installed(val id: String, val appKey: String, val tag: String?, val published: String?, val platform: String?, val dir: File, val repo: String? = null)
fun installed(context: Context): Map<String, Installed> {
val out = HashMap<String, Installed>()
fun scan(root: File, prefix: String) = root.listFiles()?.forEach { dir ->
val id = FileUtils.readString(File(dir, META_ID))?.trim()?.takeIf { it.isNotEmpty() } ?: return@forEach
out[id] = Installed(id, "$prefix:${dir.name}", read(dir, META_TAG), read(dir, META_PUBLISHED), read(dir, META_PLATFORM), dir, read(dir, META_REPO))
}
scan(UserApps.root(context), "script")
AppImageManager.dir(context, "x").parentFile?.let { scan(it, "appimage") }
windowsRoots(context).forEach { scan(it, "added") }
return out
}
private fun windowsRoots(context: Context): List<File> =
(AddedGames.roots(context).map { it.host } + StoreInstallRoot.installRoot(context)).map { File(it, WINDOWS_DIR) }.distinct()
private fun windowsTarget(context: Context, entry: RecompCatalog.Entry): File =
File(AddedGames.roots(context).firstOrNull()?.host?.takeIf { it.canWrite() } ?: StoreInstallRoot.installRoot(context), "$WINDOWS_DIR/${entry.id}")
fun remove(context: Context, installed: Installed) {
AddedGames.remove(context, installed.dir)
FileUtils.delete(installed.dir)
}
// The build being replaced by another one. An Android app is left for the player to remove, since its
// uninstall needs their confirmation.
private fun uninstall(context: Context, inst: Installed) {
when {
inst.appKey.startsWith("added:") -> remove(context, inst)
inst.appKey.startsWith("android:") -> {}
else -> UserApps.list(context).firstOrNull { it.key == inst.appKey }?.let { UserApps.remove(context, it) { _, _ -> } }
?: FileUtils.delete(inst.dir)
}
}
private fun read(dir: File, name: String) = FileUtils.readString(File(dir, name))?.trim()?.takeIf { it.isNotEmpty() }
// A feed that names the release file lets the install skip the releases API, which allows 60
// unauthenticated calls an hour per address, shared by every device on it.
fun pinned(entry: RecompCatalog.Entry, build: RecompCatalog.Build): Release? {
val tag = build.tag ?: return null
val file = build.file ?: return null
val url = build.url ?: "https://github.com/${entry.repo}/releases/download/${android.net.Uri.encode(tag)}/${android.net.Uri.encode(file)}"
return Release(tag, build.published, file, url, build.sha256)
}
// The arm64 file released beside an x86-64 Linux one under the same name with the other CPU (Decomp Buddy's
// armSibling rule), found with a plain request to the release download, which is not rate-limited.
internal fun armNames(name: String): List<String> =
listOf(Regex("x86[-_]64", RegexOption.IGNORE_CASE), Regex("amd64", RegexOption.IGNORE_CASE), Regex("\\bx64\\b", RegexOption.IGNORE_CASE))
.filter { it.containsMatchIn(name) }.flatMap { re -> listOf("aarch64", "arm64", "ARM64").map { name.replace(re, it) } }.distinct()
private fun armTwin(entry: RecompCatalog.Entry, release: Release): Release? {
if (!release.url.startsWith("https://github.com/")) return null
val base = release.url.substringBeforeLast('/')
for (name in armNames(release.asset)) {
val url = "$base/${android.net.Uri.encode(name)}"
val found = runCatching {
val c = (java.net.URL(url).openConnection() as java.net.HttpURLConnection).apply {
requestMethod = "HEAD"; connectTimeout = 10_000; readTimeout = 10_000; instanceFollowRedirects = true
}
try { c.responseCode == 200 } finally { c.disconnect() }
}.getOrDefault(false)
if (found) return Release(release.tag, release.published, name, url, null)
}
return null
}
fun latest(entry: RecompCatalog.Entry, build: RecompCatalog.Build): Release? {
val body = Downloader.downloadString("https://api.github.com/repos/${entry.repo}/releases?per_page=15") ?: return null
return pickRelease(body, build.asset, false)
}
internal fun pickRelease(body: String, asset: Regex, prerelease: Boolean): Release? {
val releases = runCatching { JSONArray(body) }.getOrNull() ?: return null
val candidates = (0 until releases.length()).mapNotNull { i ->
val r = releases.getJSONObject(i)
if (r.optBoolean("draft")) return@mapNotNull null
val assets = r.optJSONArray("assets") ?: return@mapNotNull null
val a = (0 until assets.length()).map { assets.getJSONObject(it) }.firstOrNull { asset.containsMatchIn(it.getString("name")) }
?: return@mapNotNull null
r.optBoolean("prerelease") to Release(r.optString("tag_name"), r.optString("published_at"), a.getString("name"),
a.getString("browser_download_url"), Hashes.githubSha256(a.optString("digest")))
}
return (candidates.firstOrNull { prerelease || !it.first } ?: candidates.firstOrNull())?.second
}
fun isNewer(release: Release, installed: Installed): Boolean =
installed.tag != null && release.tag != installed.tag && isAfter(release, installed)
private fun isAfter(release: Release, installed: Installed): Boolean =
if (!installed.published.isNullOrEmpty() && release.published.isNotEmpty()) release.published > installed.published
else release.tag != installed.tag
fun install(
context: Context, entry: RecompCatalog.Entry, build: RecompCatalog.Build, wanted: Release?, onProgress: (String, Int) -> Unit,
allowTwin: Boolean = true,
): String? {
val android = build.platform == RecompCatalog.Platform.ANDROID
if (!android && !LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val release = wanted ?: pinned(entry, build) ?: run {
onProgress(context.getString(R.string.user_apps_github_checking, entry.repo), -1)
val body = Downloader.downloadString("https://api.github.com/repos/${entry.repo}/releases?per_page=15")
?: return context.getString(R.string.user_apps_github_unreachable, entry.repo)
pickRelease(body, build.asset, false) ?: return context.getString(R.string.recomps_no_build, entry.repo)
}
val twin = if (allowTwin && build.platform == RecompCatalog.Platform.LINUX_X64) armTwin(entry, release) else null
val platform = if (twin != null) RecompCatalog.Platform.LINUX_ARM64 else build.platform
return fetchAndInstall(context, entry, build, platform, twin ?: release, onProgress)
}
private fun fetchAndInstall(
context: Context, entry: RecompCatalog.Entry, build: RecompCatalog.Build, platform: RecompCatalog.Platform, release: Release,
onProgress: (String, Int) -> Unit,
): String? {
val android = platform == RecompCatalog.Platform.ANDROID
val work = File(context.cacheDir, "recomps").apply { mkdirs() }
val download = File(work, release.asset)
val stage = File(work, "stage-${entry.id}")
try {
val label = context.getString(R.string.user_apps_downloading, release.asset)
val progress = java.util.function.Consumer<Float> { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
val mirror = release.sha256?.takeIf { RecompCatalog.mirrorEnabled && build.mirrored && release.asset == build.file }
?.let { RecompCatalog.mirrorUrl(it, release.asset) }
val ok = Downloader.downloadFile(release.url, download, true, release.sha256, progress) ||
mirror != null && Downloader.downloadFile(mirror, download.also { it.delete() }, false, release.sha256, progress)
if (!ok) return context.getString(R.string.user_apps_download_failed)
val meta = mapOf(META_ID to entry.id, META_TAG to release.tag, META_PUBLISHED to release.published, META_PLATFORM to platform.key, META_REPO to entry.repo)
if (android) return RecompAndroid.install(context, entry, build, release, download)
val previous = installed(context)[entry.id]
val problem = if (platform == RecompCatalog.Platform.WINDOWS_X64) {
installWindows(context, entry, build, download, meta, previous, onProgress)
} else if (download.name.endsWith(".appimage", ignoreCase = true)) {
AppImageManager.import(context, download, entry.name, null, meta) { onProgress(it, -1) }
} else {
FileUtils.delete(stage)
stage.mkdirs()
onProgress(context.getString(R.string.recomps_unpacking, release.asset), -1)
unpack(context, download, stage)
val found = (if (build.entry.isEmpty()) guessEntry(stage, entry) else findEntry(stage, build.entry))
?: return context.getString(R.string.recomps_entry_missing, build.entry.ifEmpty { entry.name })
if (found.name.endsWith(".appimage", ignoreCase = true)) {
AppImageManager.import(context, found, entry.name, null, meta) { onProgress(it, -1) }
} else {
UserApps.addPrepared(context, entry.name, null, meta) { dir ->
val files = File(dir, "files")
if (!stage.renameTo(files)) throw IllegalStateException(context.getString(R.string.user_apps_failed))
markExecutables(files)
val rel = found.relativeTo(stage).invariantSeparatorsPath
FileUtils.writeString(File(files, WRAPPER), wrapper(rel))
File(files, WRAPPER).setExecutable(true, false)
WRAPPER
}
}
}
if (problem == null && previous != null) {
if (previous.platform != platform.key) uninstall(context, previous)
else if (previous.dir != windowsTarget(context, entry)) FileUtils.delete(previous.dir)
}
if (problem == null && platform != RecompCatalog.Platform.WINDOWS_X64) {
installed(context)[entry.id]?.let { runCatching { RecompShortcuts.prepare(entry, it) } }
}
return problem
} catch (e: Exception) {
return e.message ?: context.getString(R.string.user_apps_failed)
} finally {
download.delete()
FileUtils.delete(stage)
}
}
private fun installWindows(
context: Context, entry: RecompCatalog.Entry, build: RecompCatalog.Build, download: File, meta: Map<String, String>,
previous: Installed?, onProgress: (String, Int) -> Unit,
): String? {
val target = windowsTarget(context, entry)
if (previous?.dir == target) AddedGames.remove(context, target)
FileUtils.delete(target)
target.mkdirs()
onProgress(context.getString(R.string.recomps_unpacking, download.name), -1)
if (download.name.endsWith(".exe", ignoreCase = true)) download.copyTo(File(target, download.name), true)
else unpack(context, download, target)
val exe = (if (build.entry.isNotEmpty()) findEntry(target, build.entry) else GameExePicker.rank(target).exes.firstOrNull())
?: return context.getString(R.string.recomps_entry_missing, build.entry.ifEmpty { entry.name })
meta.forEach { (k, v) -> FileUtils.writeString(File(target, k), v) }
return when (AddedGames.addExe(context, exe)) {
is AddedGames.AddResult.Added, is AddedGames.AddResult.Existing, is AddedGames.AddResult.Switched -> null
else -> context.getString(R.string.recomps_add_failed)
}
}
private fun unpack(context: Context, archive: File, into: File) {
var file = archive
val binds = if (listOf(context.filesDir, context.cacheDir).any { into.absolutePath.startsWith(it.absolutePath + "/") }) null
else listOf(into.absolutePath)
repeat(NESTED_LIMIT) { depth ->
val tail = ArrayDeque<String>()
val code = GuestCommand.run(context, listOf("/usr/bin/bsdtar", "-xf", file.absolutePath, "-C", into.absolutePath),
logName = "recomps", extraBinds = binds, fastPath = true) { line ->
if (!line.startsWith("proot ")) { if (tail.size == 4) tail.removeFirst(); tail.addLast(line) }
}
if (code != 0) throw IllegalStateException(context.getString(R.string.recomps_unpack_failed, code) + tail.joinToString(" | ", ": "))
if (depth > 0) file.delete()
// A .deb unpacks to debian-binary, control.tar.* and data.tar.*; the program is in data.tar.
val debData = into.listFiles()?.takeIf { files -> files.any { it.name == "debian-binary" } }?.firstOrNull { it.name.startsWith("data.tar") }
if (debData != null) {
into.listFiles()?.filter { it.name == "debian-binary" || it.name.startsWith("control.tar") }?.forEach { it.delete() }
file = debData
return@repeat
}
val only = into.listFiles()?.singleOrNull()?.takeIf { it.isFile && ARCHIVE.containsMatchIn(it.name) } ?: return
file = only
}
}
// Catalogs that do not name the program: an AppImage if there is one, else the executable ELF (not a
// shared library) whose name is closest to the project's, nearest the top, then the largest.
internal fun guessEntry(root: File, entry: RecompCatalog.Entry): File? {
val files = root.walkTopDown().maxDepth(4).filter { it.isFile && !java.nio.file.Files.isSymbolicLink(it.toPath()) }.toList()
files.filter { it.name.endsWith(".appimage", ignoreCase = true) }.minByOrNull { it.path.length }?.let { return it }
val words = listOf(entry.id, entry.name, entry.repo.substringAfter('/')).map { key(it) }.filter { it.isNotEmpty() }
return files.filter { !Regex("\\.so(\\.|$)").containsMatchIn(it.name) && isElf(it) && elfType(it) != SHARED_OBJECT_ONLY }
.sortedWith(compareByDescending<File> { f -> val n = key(f.name); words.count { w -> n.isNotEmpty() && (w.contains(n) || n.contains(w)) } }
.thenBy { it.relativeTo(root).path.count { c -> c == '/' } }
.thenByDescending { it.length() })
.firstOrNull()
}
private const val SHARED_OBJECT_ONLY = -1
private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
// ET_DYN libraries without a program interpreter are shared objects, not programs.
private fun elfType(f: File): Int = runCatching {
RandomAccessFile(f, "r").use { raf ->
val head = ByteArray(64)
if (raf.read(head) < 64) return@use 0
val little = head[5].toInt() == 1
fun u16(o: Int) = if (little) (head[o].toInt() and 0xff) or ((head[o + 1].toInt() and 0xff) shl 8) else ((head[o].toInt() and 0xff) shl 8) or (head[o + 1].toInt() and 0xff)
val type = u16(16)
if (type != 3) return@use type
val bytes = raf.length().coerceAtMost(1L shl 16).toInt()
raf.seek(0)
val buf = ByteArray(bytes)
raf.readFully(buf)
if (String(buf, Charsets.ISO_8859_1).contains("/ld-linux")) type else SHARED_OBJECT_ONLY
}
}.getOrDefault(0)
internal fun findEntry(root: File, name: String): File? {
if (name.isEmpty()) return null
var level = listOf(root)
repeat(4) {
level.forEach { dir -> dir.listFiles()?.firstOrNull { it.isFile && it.name == name }?.let { return it } }
level.forEach { dir -> dir.listFiles()?.firstOrNull { it.isFile && it.name.equals(name, ignoreCase = true) }?.let { return it } }
level = level.flatMap { dir -> dir.listFiles()?.filter { it.isDirectory }?.sortedBy { it.name }.orEmpty() }
}
return null
}
private fun markExecutables(root: File) {
root.walkTopDown().maxDepth(6).filter { it.isFile && !java.nio.file.Files.isSymbolicLink(it.toPath()) && isElf(it) }
.forEach { runCatching { Os.chmod(it.path, 0b111_101_101) } }
}
private fun isElf(f: File): Boolean = runCatching {
RandomAccessFile(f, "r").use { val b = ByteArray(4); it.read(b) == 4 && b[0] == 0x7f.toByte() && b[1] == 'E'.code.toByte() && b[2] == 'L'.code.toByte() && b[3] == 'F'.code.toByte() }
}.getOrDefault(false)
private fun quote(s: String) = "'" + s.replace("'", "'\\''") + "'"
// The program starts from its own folder, as it would after unpacking the release by hand.
internal fun wrapper(entry: String): String {
val dir = entry.substringBeforeLast('/', "")
val enter = if (dir.isEmpty()) "" else "cd ${quote(dir)} || exit 127\n"
return "#!/bin/sh\n$enter" + "exec ./${quote(entry.substringAfterLast('/'))} \"\$@\"\n"
}
}
@@ -0,0 +1,101 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.system.Os
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import org.json.JSONObject
import java.io.File
import java.util.zip.CRC32
// Each Linux recomp (a script app or an AppImage) is also a non-Steam game: a native shortcut, without a
// compatibility tool, to a small `play` script beside the install. Windows recomps are added games, so Steam
// already has them; Android apps cannot be Steam shortcuts.
object RecompShortcuts {
private const val TAG = "RecompShortcuts"
const val SOURCE = "recomp"
private const val PLAY = "play"
private const val COVER = "cover"
private const val ICON = "icon.png"
class Shortcut(
val id: String, val name: String, val appKey: String, val exe: String, val dir: String, val appId: Long,
val cover: File?, val icon: File?, val host: File,
) {
val gameId: Long get() = (appId shl 32) or 0x02000000L
}
// Steam's own ID for a non-Steam shortcut: a CRC32 of the quoted program and the name, with the top bit set.
fun appId(exe: String, name: String): Long = CRC32().apply { update("\"$exe\"$name".toByteArray()) }.value or 0x80000000L
private fun guestDir(inst: RecompInstaller.Installed): String? = when {
inst.appKey.startsWith("script:") -> "${UserApps.GUEST_DIR}/${inst.dir.name}"
inst.appKey.startsWith("appimage:") -> "${AppImageManager.GUEST_DIR}/${inst.dir.name}"
else -> null
}
internal fun playScript(inst: RecompInstaller.Installed, guest: String): String {
val launcher = if (inst.appKey.startsWith("appimage:")) AppImageManager.LAUNCHER else UserApps.SCRIPT_LAUNCHER
return "#!/bin/sh\nexec $launcher '$guest' \"\$@\"\n"
}
private fun writePlay(inst: RecompInstaller.Installed, guest: String): File? = runCatching {
File(inst.dir, PLAY).also { f ->
val text = playScript(inst, guest)
if (FileUtils.readString(f) != text) FileUtils.writeString(f, text)
runCatching { Os.chmod(f.path, 0b111_101_101) }
f.setExecutable(true, false)
}
}.onFailure { Log.w(TAG, "play ${inst.dir}: $it") }.getOrNull()
// Writes the play script and saves the catalog's art beside the install, for Steam's library and the Library tab.
fun prepare(entry: RecompCatalog.Entry, inst: RecompInstaller.Installed) {
val guest = guestDir(inst) ?: return
writePlay(inst, guest)
fun save(url: String?, name: String) {
if (url.isNullOrEmpty() || File(inst.dir, name).isFile) return
val tmp = File(inst.dir, "$name.part")
if (runCatching { Downloader.downloadFile(url, tmp, false) { } }.getOrDefault(false)) tmp.renameTo(File(inst.dir, name)) else tmp.delete()
}
save(entry.cover, COVER + "." + (entry.cover?.substringAfterLast('.')?.substringBefore('?')?.lowercase()?.takeIf { it in setOf("png", "jpg", "jpeg", "webp") } ?: "jpg"))
if (!File(inst.dir, ICON).isFile) save(entry.art, ICON)
}
fun all(context: Context): List<Shortcut> = RecompInstaller.installed(context).values.mapNotNull { inst ->
val guest = guestDir(inst) ?: return@mapNotNull null
val play = File(inst.dir, PLAY).takeIf { it.isFile } ?: writePlay(inst, guest) ?: return@mapNotNull null
val name = FileUtils.readString(File(inst.dir, "name"))?.trim()?.takeIf { it.isNotEmpty() } ?: inst.id
val exe = "$guest/${play.name}"
Shortcut(inst.id, name, inst.appKey, exe, guest, appId(exe, name),
inst.dir.listFiles()?.firstOrNull { it.name.startsWith("$COVER.") && it.isFile }, File(inst.dir, ICON).takeIf { it.isFile }, inst.dir)
}
// Entries for the session's shortcut listing (droiddeck-steam-shortcuts): native, so no compatibility tool.
fun listing(context: Context): List<JSONObject> = runCatching { all(context) }.getOrDefault(emptyList()).map { s ->
JSONObject().put("name", s.name).put("exe", s.exe).put("folder", s.dir).put("dir", s.dir).put("appid", s.appId)
.put("seen", 0).put("native", true).also { o ->
val art = JSONObject()
s.cover?.let { art.put("p", it.absolutePath) }
s.icon?.let { art.put("icon", it.absolutePath) }
if (art.length() > 0) o.put("art", art)
}
}
fun library(context: Context, lastPlayed: (appId: Long, gameId: Long) -> Long = { _, _ -> 0L }): List<Library.SteamGame> =
runCatching { all(context) }.getOrDefault(emptyList()).map { s ->
Library.SteamGame(
s.appId.toInt(), s.name, s.cover ?: s.icon, SOURCE, s.gameId, lastPlayed = lastPlayed(s.appId, s.gameId), icon = s.icon,
source = SOURCE, storeId = s.appKey, installedAt = s.host.lastModified(),
)
}
// Adds the shortcut to a running Steam client now; the listing covers the next session either way.
fun addLive(context: Context, id: String) {
all(context).firstOrNull { it.id == id }?.let { s -> SteamLiveShortcuts.ensure(context, s.name, s.exe, s.dir, compat = false, appId = s.appId) }
}
fun removeLive(context: Context, appId: Long) = runCatching { SteamLiveShortcuts.remove(context, appId) }
}
@@ -0,0 +1,145 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.stores.Store
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
// None of the recomp catalogs names the store release a PC port needs, but Recomp Launcher's gives each game's
// IGDB slug. Wikidata links IGDB slugs (P5794) to Steam app IDs (P1733), GOG slugs (P2725) and Epic store slugs
// (P6278), and GOG's public products API gives the slug of each GOG product the player owns. Both answers are
// cached, so a game is looked up again only after [MAX_AGE_MS].
object RecompStoreIds {
private const val TAG = "RecompStoreIds"
private const val MAX_AGE_MS = 14L * 24 * 60 * 60 * 1000
private const val BATCH = 150
private const val GOG_BATCH = 50
private const val WIKIDATA = "https://query.wikidata.org/sparql"
class Ids(val steam: Set<String>, val gog: Set<String>, val epic: Set<String>) {
fun of(store: Store): Set<String> = when (store) {
Store.STEAM -> steam
Store.GOG -> gog
Store.EPIC -> epic
else -> emptySet()
}
val empty get() = steam.isEmpty() && gog.isEmpty() && epic.isEmpty()
}
private fun file(context: Context, name: String) = File(File(context.filesDir, "recomps").apply { mkdirs() }, name)
// IGDB slug -> the store IDs Wikidata has for that game; a slug Wikidata does not know maps to empty IDs.
fun forGames(context: Context, slugs: Collection<String>, offline: Boolean = false): Map<String, Ids> {
val cacheFile = file(context, "store-ids.json")
val cache = runCatching { JSONObject(cacheFile.readText()) }.getOrDefault(JSONObject())
val now = System.currentTimeMillis()
val stale = slugs.distinct().filter { now - (cache.optJSONObject(it)?.optLong("at") ?: 0L) > MAX_AGE_MS }
if (!offline && stale.isNotEmpty()) {
var changed = false
for (chunk in stale.chunked(BATCH)) {
val found = runCatching { query(chunk) }.onFailure { Log.w(TAG, "wikidata: $it") }.getOrNull() ?: break
for (slug in chunk) {
val ids = found[slug] ?: Ids(emptySet(), emptySet(), emptySet())
cache.put(slug, JSONObject().put("at", now).put("steam", JSONArray(ids.steam.toList()))
.put("gog", JSONArray(ids.gog.toList())).put("epic", JSONArray(ids.epic.toList())))
}
changed = true
}
if (changed) FileUtils.writeString(cacheFile, cache.toString())
}
return slugs.mapNotNull { slug -> cache.optJSONObject(slug)?.let { slug to idsOf(it) } }.toMap()
}
private fun idsOf(o: JSONObject): Ids {
fun set(key: String) = o.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.getString(it) }.toSet() }.orEmpty()
return Ids(set("steam"), set("gog"), set("epic"))
}
internal fun sparql(slugs: List<String>): String {
val values = slugs.filter { Regex("[a-z0-9-]+").matches(it) }.joinToString(" ") { "\"$it\"" }
return "SELECT ?igdb ?steam ?gog ?epic WHERE { VALUES ?igdb { $values } ?item wdt:P5794 ?igdb . " +
"OPTIONAL { ?item wdt:P1733 ?steam } OPTIONAL { ?item wdt:P2725 ?gog } OPTIONAL { ?item wdt:P6278 ?epic } }"
}
private fun query(slugs: List<String>): Map<String, Ids> {
val body = "query=" + URLEncoder.encode(sparql(slugs), "UTF-8") + "&format=json"
val conn = (URL(WIKIDATA).openConnection() as HttpURLConnection).apply {
requestMethod = "POST"; doOutput = true; connectTimeout = 15_000; readTimeout = 60_000
setRequestProperty("User-Agent", "DroidDeck (https://github.com/Droid-Deck/DroidDeck)")
setRequestProperty("Accept", "application/sparql-results+json")
setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
}
return try {
conn.outputStream.use { it.write(body.toByteArray()) }
if (conn.responseCode != 200) throw IllegalStateException("HTTP ${conn.responseCode}")
parseSparql(conn.inputStream.bufferedReader().use { it.readText() })
} finally {
conn.disconnect()
}
}
internal fun parseSparql(json: String): Map<String, Ids> {
val rows = JSONObject(json).getJSONObject("results").getJSONArray("bindings")
val out = HashMap<String, Triple<MutableSet<String>, MutableSet<String>, MutableSet<String>>>()
for (i in 0 until rows.length()) {
val row = rows.getJSONObject(i)
val slug = row.optJSONObject("igdb")?.optString("value") ?: continue
val (steam, gog, epic) = out.getOrPut(slug) { Triple(HashSet(), HashSet(), HashSet()) }
row.optJSONObject("steam")?.optString("value")?.takeIf { Regex("[0-9]+").matches(it) }?.let { steam += it }
row.optJSONObject("gog")?.optString("value")?.let { gogSlug(it) }?.let { gog += it }
row.optJSONObject("epic")?.optString("value")?.takeIf { it.isNotBlank() }?.let { epic += it.lowercase() }
}
return out.mapValues { (_, v) -> Ids(v.first, v.second, v.third) }
}
// Wikidata writes GOG IDs as "game/<slug>" (or "movie/<slug>"); GOG's API gives the bare slug.
internal fun gogSlug(value: String): String? = value.substringAfterLast('/').lowercase().takeIf { Regex("[a-z0-9_]+").matches(it) }
// GOG product ID -> slug, for the GOG products the player owns. Slugs do not change, so answers are kept.
fun gogSlugs(context: Context, ids: Collection<String>, offline: Boolean = false): Map<String, String> {
val cacheFile = file(context, "gog-slugs.json")
val cache = runCatching { JSONObject(cacheFile.readText()) }.getOrDefault(JSONObject())
val missing = ids.filter { Regex("[0-9]+").matches(it) && !cache.has(it) }.distinct()
if (!offline && missing.isNotEmpty()) {
var changed = false
for (chunk in missing.chunked(GOG_BATCH)) {
val body = runCatching { get("https://api.gog.com/products?ids=${chunk.joinToString(",")}&locale=en-US") }
.onFailure { Log.w(TAG, "gog: $it") }.getOrNull() ?: break
val found = parseGogProducts(body)
for (id in chunk) cache.put(id, found[id] ?: "")
changed = true
}
if (changed) FileUtils.writeString(cacheFile, cache.toString())
}
return ids.mapNotNull { id -> cache.optString(id).takeIf { it.isNotEmpty() }?.let { id to it } }.toMap()
}
internal fun parseGogProducts(json: String): Map<String, String> {
val arr = runCatching { JSONArray(json) }.getOrNull() ?: return emptyMap()
return (0 until arr.length()).mapNotNull { i ->
val o = arr.optJSONObject(i) ?: return@mapNotNull null
val id = o.opt("id")?.toString() ?: return@mapNotNull null
o.optString("slug").lowercase().takeIf { it.isNotEmpty() }?.let { id to it }
}.toMap()
}
private fun get(url: String): String {
val conn = (URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = 15_000; readTimeout = 30_000
setRequestProperty("User-Agent", "DroidDeck")
}
return try {
if (conn.responseCode != 200) throw IllegalStateException("HTTP ${conn.responseCode}")
conn.inputStream.bufferedReader().use { it.readText() }
} finally {
conn.disconnect()
}
}
}
@@ -74,7 +74,7 @@ object UserApps {
class ScriptPlan(val folder: File, val copy: Boolean, val bytes: Long)
private fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_DIR.substring(1))
internal fun root(context: Context) = File(LinuxRuntime.rootDir(context), GUEST_DIR.substring(1))
private fun overrides(context: Context, flatpakId: String) = File(root(context), "$FLATPAK_OVERRIDES/$flatpakId")
@@ -247,6 +247,27 @@ object UserApps {
}
}
// [prepare] fills the new app folder's `files` and returns the entry's name there, or throws.
internal fun addPrepared(context: Context, name: String, icon: File?, meta: Map<String, String>, prepare: (File) -> String): String? {
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
val base = root(context).apply { mkdirs() }
val dir = File(base, AppImageManager.idFor(name, base.list()?.toSet() ?: emptySet()))
return try {
dir.mkdirs()
val entry = prepare(dir)
FileUtils.writeString(File(dir, "entry"), entry)
FileUtils.writeString(File(dir, "name"), name)
if (icon != null && !saveIcon(icon, File(dir, "icon.png"))) Log.w(TAG, "icon ${icon.path} could not be read")
meta.forEach { (k, v) -> FileUtils.writeString(File(dir, k), v) }
writeScriptEntry(context, dir)
null
} catch (e: Exception) {
Log.e(TAG, "prepared $name", e)
FileUtils.delete(dir)
e.message ?: context.getString(R.string.user_apps_failed)
}
}
private fun writeScriptEntry(context: Context, dir: File) {
val id = dir.name
val icon = if (File(dir, "icon.png").isFile) "$GUEST_DIR/$id/icon.png" else "utilities-terminal"
@@ -154,7 +154,6 @@ object SessionFiles {
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
"usr/local/bin/droiddeck-user" to "usr/local/bin/droiddeck-user",
"usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text",
"usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd",
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
@@ -359,7 +358,6 @@ object SessionFiles {
Log.e(TAG, "could not write steam-compatibility-label")
}
writeCjkFontConfig(root, etc)
writeSessionBusPolicy(etc)
writeDesktopStrings(context, File(etc, "droiddeck").apply { mkdirs() })
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
@@ -882,24 +880,6 @@ object SessionFiles {
}
}
/**
* A session bus admits only its owner, and with droiddeck-user (the native hook's ordinary
* user) a root process and a user's share the bus while the kernel sees one Android uid.
*/
private fun writeSessionBusPolicy(etc: File) {
val xml = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy context="default">
<allow user="*"/>
</policy>
</busconfig>
"""
val conf = File(etc, "dbus-1/session.d/droiddeck-users.conf")
conf.parentFile?.mkdirs()
if (!FileUtils.writeString(conf, xml)) Log.e(TAG, "could not write the session bus policy")
}
private fun writeCjkFontConfig(root: File, etc: File) {
try {
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
@@ -63,24 +63,6 @@ object SessionPrefs {
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
fun orientation(context: Context, mode: String?): Int {
val key = when (mode) {
"steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam"
"desktop", SessionService.MODE_DESKTOP -> "orientation.desktop"
else -> null
} ?: return orientation(context)
val stored = prefs(context).getInt(key, Int.MIN_VALUE)
return if (stored == Int.MIN_VALUE) orientation(context)
else stored.takeIf { value -> orientationOptions.any { it.first == value } } ?: orientation(context)
}
fun setOrientation(context: Context, mode: String, orientation: Int) {
require(mode == "steam" || mode == "desktop")
require(orientationOptions.any { it.first == orientation })
val key = if (mode == "steam") "orientation.steam" else "orientation.desktop"
prefs(context).edit().putInt(key, orientation).apply()
}
/** The session menu's width in dp the user dragged it to; null keeps the default. */
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
@@ -93,19 +75,11 @@ object SessionPrefs {
prefs(context).edit().putInt("orientation", orientation).apply()
}
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int, mode: String? = null): Int {
val modeKey = when (mode) {
"steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam"
"desktop", SessionService.MODE_DESKTOP -> "orientation.desktop"
else -> null
}
val preferences = prefs(context)
if (modeKey != null && preferences.contains(modeKey)) return orientation(context, mode)
return if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !preferences.contains("orientation"))
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int): Int =
if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !prefs(context).contains("orientation"))
ActivityInfo.SCREEN_ORIENTATION_USER else orientation(context)
}
fun portrait(context: Context, mode: String? = null): Boolean = when (orientation(context, mode)) {
fun portrait(context: Context): Boolean = when (orientation(context)) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> true
ActivityInfo.SCREEN_ORIENTATION_USER ->
context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
@@ -519,17 +493,6 @@ object SessionPrefs {
prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply()
}
fun drawerSections(context: Context): Map<String, Boolean> =
idList(prefs(context).getString("drawerSections", null)).mapNotNull { entry ->
val at = entry.lastIndexOf('=').takeIf { it > 0 } ?: return@mapNotNull null
entry.substring(0, at) to (entry.substring(at + 1) == "1")
}.toMap()
fun setDrawerSections(context: Context, sections: Map<String, Boolean>) {
prefs(context).edit().putString("drawerSections", sections.entries.filter { ',' !in it.key }
.joinToString(",") { "${it.key}=${if (it.value) 1 else 0}" }).apply()
}
fun setNavTabHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
}
@@ -1141,13 +1104,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
}
/** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
fun setDesktopAsUser(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
}
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
@@ -1851,15 +1807,16 @@ object SessionPrefs {
const val PIP_FPS = 30
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false, hostCap: Int = 0): Int {
val limit = listOf(mirrorRefreshLimit, sessionLimit, hostCap).filter { it > 0 }.minOrNull() ?: FPS_UNPACED
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false): Int {
val limit = when {
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
mirrorRefreshLimit <= 0 -> sessionLimit
sessionLimit <= 0 -> mirrorRefreshLimit
else -> minOf(mirrorRefreshLimit, sessionLimit)
}
return if (pip && mirrorRefreshLimit <= 0 && (limit <= 0 || limit > PIP_FPS)) PIP_FPS else limit
}
/** The per-app rate Android holds this window to (Game Mode's FPS override), or 0 when the panel's rate applies. */
fun hostFrameCap(overrideHz: Float, panelHz: Float): Int =
if (overrideHz > 1f && panelHz - overrideHz > 1f) Math.round(overrideHz) else 0
val upscalerChoices = listOf(
2 to "Nearest", 0 to "Linear", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only",
@@ -661,7 +661,7 @@ class SessionService : Service() {
Log.i(TAG, "game resolution: ${w}x$h on a ${size.first}x${size.second} output")
}
if (SessionState.followScreen || size.first < size.second ||
SessionPrefs.orientation(this, SessionState.mode) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
guest.add("DD_FOLLOW_OUTPUT=1")
if (SessionState.hdr) {
guest.add("DD_HDR=1")
@@ -709,7 +709,6 @@ class SessionService : Service() {
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
GameStorage.effective(this)?.let { guest.add("DD_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("DD_STEAM_UI=desktop")
if (SessionPrefs.desktopAsUser(this)) guest.add("DD_DESKTOP_USER=1")
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
if (GraphicsReport.detailed(this)) guest.add("DD_GAME_LOGS=1")
@@ -18,7 +18,7 @@ object SettingsReset {
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
@@ -0,0 +1,163 @@
package com.droiddeck.launcher.store
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.RecompAndroid
import com.droiddeck.launcher.runtime.RecompCatalog
import com.droiddeck.launcher.runtime.RecompData
import com.droiddeck.launcher.runtime.RecompInstaller
object RecompsState {
private val main = Handler(Looper.getMainLooper())
var entries by mutableStateOf<List<RecompCatalog.Entry>>(emptyList())
private set
var installed by mutableStateOf<Map<String, RecompInstaller.Installed>>(emptyMap())
private set
var data by mutableStateOf<Map<String, RecompData.State>>(emptyMap())
private set
var updates by mutableStateOf<Map<String, RecompInstaller.Release>>(emptyMap())
private set
var loading by mutableStateOf(false)
private set
var incompatible by mutableStateOf<Set<String>>(emptySet())
private set
// The last install failure of each recomp, kept on its page until the next attempt.
var errors by mutableStateOf<Map<String, String>>(emptyMap())
private set
private var seq = 0
private var checked = false
private var lastSteam: List<Pair<Int, String>> = emptyList()
internal var fixed = false
private set
internal fun show(
list: List<RecompCatalog.Entry>, have: Map<String, RecompInstaller.Installed>, states: Map<String, RecompData.State>,
newer: Map<String, RecompInstaller.Release>,
) {
fixed = true
entries = list; installed = have; data = states; updates = newer; loading = false
}
fun refresh(context: Context, steamOwned: Collection<Pair<Int, String>>, reloadCatalog: Boolean = false) {
if (fixed) return
val app = context.applicationContext
lastSteam = steamOwned.toList()
RecompAndroid.onChanged = { main.post { refresh(app, lastSteam) } }
RecompAndroid.onFailed = { pkg, message ->
main.post { entries.filter { it.android?.pkg == pkg }.forEach { errors = errors + (it.id to message) } }
}
val n = ++seq
loading = entries.isEmpty()
Thread({
synchronized(refreshLock) {
if (n != seq) return@Thread
val list = runCatching { RecompCatalog.load(app, reloadCatalog) }.getOrDefault(emptyList())
val apps = runCatching { RecompAndroid.installed(app, list) }.getOrDefault(emptyMap())
val files = runCatching { RecompInstaller.installed(app) }.getOrDefault(emptyMap())
// Catalogs can rename an entry; an install also belongs to the entry with its repo.
val byRepo = files.values.filter { it.repo != null }.associateBy { it.repo!!.lowercase() }
val chosen = choices(app)
// Installs from before the shortcut work, or whose art download failed, get their cover now.
list.forEach { e -> (files[e.id] ?: byRepo[e.repo.lowercase()])?.let { inst -> runCatching { com.droiddeck.launcher.runtime.RecompShortcuts.prepare(e, inst) } } }
val have = list.mapNotNull { e ->
val both = listOfNotNull(files[e.id] ?: byRepo[e.repo.lowercase()], apps[e.id])
(both.firstOrNull { it.platform == chosen[e.id] } ?: both.firstOrNull())?.let { e.id to it }
}.toMap()
// The list shows as soon as the catalog is read; game-file checks follow without hashing anything new.
main.post { if (n == seq && entries.isEmpty()) { entries = list; installed = have; loading = false } }
if (n != seq) return@Thread
val inputs = runCatching { RecompData.inputs(app, steamOwned, list, cachedOnly = true) }.getOrNull()
val states = list.associate { e -> e.id to (inputs?.let { RecompData.resolve(e, it) } ?: RecompData.State.BringYourOwn(e.data)) }
inputs?.done?.invoke()
val apks = runCatching { RecompAndroid.incompatible(app) }.getOrDefault(emptySet())
main.post {
if (n != seq) return@post
entries = list; installed = have; data = states; incompatible = apks; loading = false
}
if (!checked && have.isNotEmpty()) {
checked = true
val found = list.filter { it.id in have }.mapNotNull { e ->
val i = have.getValue(e.id)
val build = RecompCatalog.Platform.of(i.platform.orEmpty())?.let { buildFor(e, it) } ?: return@mapNotNull null
val newest = (RecompInstaller.pinned(e, build) ?: runCatching { RecompInstaller.latest(e, build) }.getOrNull())
?.takeIf { RecompInstaller.isNewer(it, i) }
newest?.let { e.id to it }
}.toMap()
main.post { updates = found }
}
}
}, "recomps-refresh").start()
}
private val refreshLock = Any()
// Checks one recomp's game files against the catalog's hashes, which can take a while for large files.
fun verify(context: Context, entry: RecompCatalog.Entry, steamOwned: Collection<Pair<Int, String>>) {
if (fixed || !entry.pc || data[entry.id].let { it is RecompData.State.Found && it.checked }) return
val app = context.applicationContext
Thread({
val inputs = runCatching { RecompData.inputs(app, steamOwned, listOf(entry)) }.getOrNull() ?: return@Thread
val state = RecompData.resolve(entry, inputs)
inputs.done()
main.post { data = data + (entry.id to state) }
}, "recomps-verify").start()
}
// [chosen] is a build the player picked; it is installed as it is, without swapping in an arm64 twin.
fun install(
context: Context, entry: RecompCatalog.Entry, steamOwned: Collection<Pair<Int, String>>, release: RecompInstaller.Release? = null,
chosen: RecompCatalog.Build? = null,
) {
val build = chosen ?: installed[entry.id]?.platform?.let { RecompCatalog.Platform.of(it) }?.let { buildFor(entry, it) }
?: entry.preferred(incompatible) ?: return
errors = errors - entry.id
val done = if (build.platform == RecompCatalog.Platform.ANDROID) R.string.recomps_android_started else R.string.recomps_installed
if (chosen != null) choose(context, entry.id, chosen.platform)
UserAppsState.run(context, entry.name, done, after = {
updates = updates - entry.id
UserAppsState.lastError?.takeIf { it.startsWith(entry.name + ":") }?.let { errors = errors + (entry.id to it.removePrefix(entry.name + ":").trim()) }
refresh(context, steamOwned)
com.droiddeck.launcher.frontend.AddedGamesPublisher.later(context) { com.droiddeck.launcher.runtime.RecompShortcuts.addLive(context.applicationContext, entry.id) }
}) { app, progress -> RecompInstaller.install(app, entry, build, release, progress, allowTwin = chosen == null) }
}
// Removes an installed recomp and, once it is gone, its non-Steam shortcut.
fun remove(context: Context, entry: RecompCatalog.Entry, steamOwned: Collection<Pair<Int, String>>, inst: RecompInstaller.Installed) {
val app = context.applicationContext
if (inst.appKey.startsWith("android:")) {
RecompAndroid.uninstall(app, inst.appKey.removePrefix("android:"))
return
}
val shortcut = runCatching { com.droiddeck.launcher.runtime.RecompShortcuts.all(app).firstOrNull { it.appKey == inst.appKey }?.appId }.getOrNull()
UserAppsState.run(app, entry.name, R.string.recomps_removed, after = {
refresh(app, steamOwned)
com.droiddeck.launcher.frontend.AddedGamesPublisher.later(app) { shortcut?.let { com.droiddeck.launcher.runtime.RecompShortcuts.removeLive(app, it) } }
}) { c, p ->
if (inst.appKey.startsWith("added:")) { RecompInstaller.remove(c, inst); null }
else com.droiddeck.launcher.runtime.UserApps.list(c).firstOrNull { it.key == inst.appKey }?.let { com.droiddeck.launcher.runtime.UserApps.remove(c, it, p) }
}
}
private fun choicesFile(context: Context) = java.io.File(java.io.File(context.filesDir, "recomps").apply { mkdirs() }, "choices.json")
private fun choices(context: Context): Map<String, String> = runCatching {
val o = org.json.JSONObject(choicesFile(context).readText())
o.keys().asSequence().associateWith { o.getString(it) }
}.getOrDefault(emptyMap())
// The build the player last picked shows on the card when two builds of a recomp are installed.
private fun choose(context: Context, id: String, platform: RecompCatalog.Platform) {
val o = runCatching { org.json.JSONObject(choicesFile(context).readText()) }.getOrDefault(org.json.JSONObject())
com.droiddeck.launcher.core.FileUtils.writeString(choicesFile(context), o.put(id, platform.key).toString())
}
// An arm64 install found as the twin of an x86-64 Linux release updates through that release.
private fun buildFor(entry: RecompCatalog.Entry, platform: RecompCatalog.Platform) =
entry.build(platform) ?: entry.build(RecompCatalog.Platform.LINUX_X64).takeIf { platform == RecompCatalog.Platform.LINUX_ARM64 }
}
@@ -69,7 +69,7 @@ object UserAppsState {
UserApps.update(app, target, release, progress).also { if (it == null) main.post { updates = updates - target.key } }
}
private fun run(context: Context, label: String, done: Int, work: (Context, (String, Int) -> Unit) -> String?) {
internal fun run(context: Context, label: String, done: Int, after: () -> Unit = {}, work: (Context, (String, Int) -> Unit) -> String?) {
if (working != null) return
val app = context.applicationContext
working = label; stage = null; percent = -1; lastError = null
@@ -85,6 +85,7 @@ object UserAppsState {
if (problem == null) Toast.makeText(app, app.getString(done, label), Toast.LENGTH_SHORT).show()
refresh(app)
StoreState.refresh(app)
after()
}
}, "user-apps-work").start()
}
@@ -1,142 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/**
* Inside the session menu every top-level settings group folds to its header and a summary of its values.
* Groups start folded; a group the player opens or folds stays that way across sessions.
*/
internal object DrawerSectionState {
private val chosen = mutableStateMapOf<String, Boolean>()
fun load(context: Context) {
if (DevPreview.drawer != null) return
chosen.clear()
chosen.putAll(SessionPrefs.drawerSections(context))
}
fun isOpen(key: String) = chosen[key] ?: false
fun toggle(context: Context, key: String) {
chosen[key] = !isOpen(key)
if (DevPreview.drawer == null) SessionPrefs.setDrawerSections(context, chosen.toMap())
}
}
internal class DrawerSections(val context: Context, val track: (String) -> Modifier)
internal val LocalDrawerSections = compositionLocalOf<DrawerSections?> { null }
@Composable
internal fun DrawerSection(
sections: DrawerSections, key: String, title: String, summary: String?, tag: String?,
content: @Composable ColumnScope.() -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val open = DrawerSectionState.isOpen(key)
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val rotation by animateFloatAsState(if (open) 180f else 0f, Motion.tw(180), label = "sectionArrow")
val state = stringResource(if (open) R.string.widgets_expanded else R.string.widgets_collapsed)
val toggle = { DrawerSectionState.toggle(sections.context, key) }
val shape = RoundedCornerShape(14.dp)
Column(
Modifier.fillMaxWidth().padding(top = 6.dp).clip(shape)
.background(colors.surface).border(1.dp, if (open) pal.line2 else pal.line, shape),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)
.then(sections.track("section-$key"))
.testTag("drawer-section-$key")
.background(if (hot) pal.signal.copy(alpha = 0.12f) else androidx.compose.ui.graphics.Color.Transparent)
.glideBorder(hot, shape, pal.signal)
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = toggle)
.controllerConfirm(onClick = toggle)
.semantics { contentDescription = title; stateDescription = state }
.padding(start = 12.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Text(title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp,
color = if (open) colors.onBackground else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false))
if (tag != null) Text(
tag, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(pal.signal.copy(alpha = 0.14f))
.padding(horizontal = 6.dp, vertical = 2.dp),
)
}
if (!open && !summary.isNullOrEmpty()) Text(
summary, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 2.dp),
)
}
Icon(Icons.Outlined.ExpandMore, contentDescription = null, tint = colors.onSurfaceVariant,
modifier = Modifier.size(22.dp).rotate(rotation))
}
AnimatedVisibility(open, enter = expandVertically(Motion.tw(200)) + fadeIn(Motion.tw(160)),
exit = shrinkVertically(Motion.tw(160)) + fadeOut(Motion.tw(120))) {
Column(Modifier.fillMaxWidth()) {
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
// Only top-level groups fold; groups and dialogs opened from inside one draw normally.
CompositionLocalProvider(LocalDrawerSections provides null) { content() }
}
}
}
}
@@ -26,8 +26,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
fun on(key: String) = cfg[key] == "1"
fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback
SettingsGroup(stringResource(R.string.drawer_hud), key = "performance-hud",
detail = stringResource(if (a.hudOn) R.string.widgets_on else R.string.widgets_off)) {
SettingsGroup(stringResource(R.string.drawer_hud)) {
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud)
if (a.hudOn) ToggleRow(
host, "hud-only-during-game", stringResource(R.string.hud_only_during_game),
@@ -63,7 +62,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
if (a.dashboardAvailable && a.secondScreenDisplays.isNotEmpty()) BottomStripSettings(host, track)
if (!a.hudOn) return
SettingsGroup(stringResource(R.string.hud_group_look), key = "performance-hud-look") {
SettingsGroup(stringResource(R.string.hud_group_look)) {
SliderRow(stringResource(R.string.hud_scale), null, int("hudScale", 100), 50..150, step = 5, format = { "$it%" },
modifier = track("hud-scale")) { a.onHudSetting("hudScale", it.toString()) }
SliderRow(stringResource(R.string.drawer_hud_opacity), null, int("hudOpacity", 80), 0..100, step = 5, format = { "$it%" },
@@ -86,7 +85,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
}
var editing by remember { mutableStateOf(false) }
SettingsGroup(stringResource(R.string.hud_group_metrics), key = "performance-hud-metrics") {
SettingsGroup(stringResource(R.string.hud_group_metrics)) {
ActionRow(stringResource(R.string.hud_group_metrics), null, stringResource(R.string.common_edit),
onClick = { editing = true }, modifier = track("hud-readings"))
val rows = DroidDeckHudSize.rowsFor(DroidDeckHudSize.from(cfg["hudSize"]), cfg)
@@ -104,7 +103,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
)
}
if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps), key = "performance-hud-temps") {
if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps)) {
ChoiceRow(host, "hud-temp-unit", stringResource(R.string.hud_temp_unit), null,
listOf("c" to "°C", "f" to "°F"), if (cfg["tempUnit"].equals("f", true)) "f" else "c",
chipModifier = track("hud-temp-unit")) { a.onHudSetting("tempUnit", it) }
@@ -130,7 +129,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
}
}
SettingsGroup(stringResource(R.string.hud_group_more), key = "performance-hud-more") {
SettingsGroup(stringResource(R.string.hud_group_more)) {
ActionRow(stringResource(R.string.hud_export), stringResource(R.string.hud_export_hint),
stringResource(R.string.hud_export_button), onClick = a.onHudExport, modifier = track("hud-export"))
ActionRow(stringResource(R.string.hud_reset), null, stringResource(R.string.hud_reset_button),
@@ -146,7 +145,7 @@ private fun BottomStripSettings(host: MenuHost, track: (String) -> Modifier) {
var hudOn by remember { mutableStateOf(SessionPrefs.bottomHud(context)) }
var onTabs by remember { mutableStateOf(SessionPrefs.bottomStripOnTabs(context)) }
var shown by remember { mutableStateOf(SessionPrefs.bottomStripMetrics(context)) }
SettingsGroup(stringResource(R.string.bottom_hud_group), key = "performance-bottom-hud") {
SettingsGroup(stringResource(R.string.bottom_hud_group)) {
ToggleRow(host, "bottom-hud", stringResource(R.string.bottom_hud_group), null, hudOn,
chipModifier = track("bottom-hud")) { on ->
hudOn = on
@@ -267,6 +267,10 @@ private fun Content(
SteamTabPage(selected, a, modifier.padding(horizontal = padH).padding(top = padV))
return
}
if (selected == "recomps") {
RecompsPage(s, a, onSelect, modifier.padding(horizontal = padH).padding(top = padV))
return
}
if (selected == "updates") {
UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV))
return
@@ -56,6 +56,7 @@ import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material.icons.filled.Apps
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.SdStorage
import androidx.compose.material.icons.filled.Memory
import androidx.compose.material.icons.filled.Movie
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material.icons.filled.MoreHoriz
@@ -208,6 +209,7 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
"sync" -> R.string.rail_sync to Icons.Filled.Sync
"decky" -> R.string.rail_decky to DeckyIcon
"boot-movies" -> R.string.rail_boot_movies to Icons.Filled.Movie
"recomps" -> R.string.rail_recomps to Icons.Filled.Memory
NavTabs.MORE -> R.string.rail_more to Icons.Filled.MoreHoriz
else -> R.string.rail_updates to updatesIcon(RunningBuild.kind())
}
@@ -1,9 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.FocusRequester
import android.os.Build
@@ -53,7 +50,6 @@ import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@@ -156,19 +152,6 @@ internal fun SetupPanel(
) {
val host = rememberMenuHost()
val ctx = LocalContext.current
var steamOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "steam")) }
var desktopOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "desktop")) }
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner, ctx) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
steamOrientation = SessionPrefs.orientation(ctx, "steam")
desktopOrientation = SessionPrefs.orientation(ctx, "desktop")
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
var hideHomeFromRecents by remember { mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.hideHomeFromRecents(ctx)) }
var processLimitBusy by remember { mutableStateOf(false) }
var processLimitMessage by remember { mutableStateOf<String?>(null) }
@@ -533,27 +516,7 @@ internal fun SetupPanel(
ChoiceRow(
host, "orientation", stringResource(R.string.setup_session_orientation), stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
s.orientation, onPick = { value ->
a.onOrientation(value)
steamOrientation = SessionPrefs.orientation(ctx, "steam")
desktopOrientation = SessionPrefs.orientation(ctx, "desktop")
},
)
ChoiceRow(
host, "orientation-steam", stringResource(R.string.setup_session_orientation) + " (Steam)", stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
steamOrientation, onPick = { value ->
steamOrientation = value
SessionPrefs.setOrientation(ctx, "steam", value)
},
)
ChoiceRow(
host, "orientation-desktop", stringResource(R.string.setup_session_orientation) + " (Desktop)", stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
desktopOrientation, onPick = { value ->
desktopOrientation = value
SessionPrefs.setOrientation(ctx, "desktop", value)
},
s.orientation, onPick = a.onOrientation,
)
ToggleRow(
host, "launcher-fullscreen", stringResource(R.string.setup_fullscreen),
@@ -88,7 +88,7 @@ internal fun VrControllerGroups(host: MenuHost, track: (String) -> Modifier = {
androidx.compose.runtime.LaunchedEffect(Unit) { com.droiddeck.launcher.input.VrControllers.load(context) }
val c by com.droiddeck.launcher.input.VrControllers.settings.collectAsState()
val emulate = com.droiddeck.launcher.input.VrControllers.Emulate.entries
SettingsGroup(stringResource(R.string.vr_controllers_group), key = "vr-controllers") {
SettingsGroup(stringResource(R.string.vr_controllers_group)) {
ChoiceRow(host, "vr-emulate", stringResource(R.string.vr_controllers_emulate), stringResource(R.string.vr_controllers_emulate_hint),
emulate.map { it to stringResource(when (it) {
com.droiddeck.launcher.input.VrControllers.Emulate.OFF -> R.string.vr_controllers_off
@@ -142,13 +142,13 @@ internal fun GlassesGroups(
val directView = usesGlasses && picture == GlassesRendering.Picture.STEREO
val menuScreen = !inSession && g.usable && s.gameOnGlasses && s.screen3dof
if (g.canControl && onRecenter != null && s.headTracking && (virtualScreen || menuScreen || (directView && steamVrRunning))) {
SettingsGroup(stringResource(R.string.glasses_quick_actions), compact = true, key = "vr-glasses-quick") {
SettingsGroup(stringResource(R.string.glasses_quick_actions), compact = true) {
ActionRow(stringResource(R.string.glasses_recenter),
if (virtualScreen || menuScreen) stringResource(R.string.glasses_recenter_screen_hint) else null,
stringResource(R.string.cardboard_recenter_button), onRecenter)
}
}
if (display) SettingsGroup(g.model, key = "vr-glasses") {
if (display) SettingsGroup(g.model) {
if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource(
if (g.supportsDisplayModeControl) R.string.glasses_xreal_experimental else R.string.glasses_pro2_experimental)) {}
val status = if (g.hasDisplay) stringResource(R.string.glasses_status, g.width, g.height, kotlin.math.round(g.hz).toInt(),
@@ -170,7 +170,7 @@ internal fun GlassesGroups(
s.gameOnGlasses, chipModifier = track("glasses-game")) { Glasses.setGameOnGlasses(it) }
}
if (display && g.canControl && g.supportsDisplayModeControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) {
SettingsGroup(stringResource(R.string.glasses_display_mode), key = "vr-glasses-mode") {
SettingsGroup(stringResource(R.string.glasses_display_mode)) {
if (g.sbsSupport == GlassesState.SBS_FAILS && !g.sbs) {
ActionRow(stringResource(R.string.glasses_3d), stringResource(R.string.glasses_3d_failed),
stringResource(R.string.stores_dl_retry), { Glasses.set3d(true) })
@@ -182,12 +182,12 @@ internal fun GlassesGroups(
val profiles = if (inSession) listOf(GlassesDisplayModes.profile(g.sbs, false))
else listOf(GlassesDisplayProfile.TWO_D, GlassesDisplayProfile.THREE_D)
for (profile in profiles) SettingsGroup(stringResource(if (profile == GlassesDisplayProfile.TWO_D)
R.string.glasses_output_2d else R.string.glasses_output_3d), key = "vr-glasses-output-${profile.name.lowercase()}") {
R.string.glasses_output_2d else R.string.glasses_output_3d)) {
GlassesResolutionRow(host, g, s, profile, track)
if ((profile == GlassesDisplayProfile.THREE_D) == g.sbs) GlassesRefreshRow(host, g, s, track)
}
}
if (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_picture_group), key = "vr-glasses-picture") {
if (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_picture_group)) {
ChoiceRow(host, "glasses-picture", stringResource(R.string.glasses_picture), stringResource(R.string.glasses_picture_hint),
listOf(
GlassesSettings.PICTURE_AUTO to stringResource(R.string.glasses_picture_auto),
@@ -213,7 +213,7 @@ internal fun GlassesGroups(
format = { SpatialMeasurements.distance(it / 10f) }, modifier = track("glasses-distance")) { Glasses.setScreenDistanceDm(it) }
}
}
if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr), key = "vr-glasses-steamvr") {
if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr)) {
steamVr()
if (g.supportsDisplayModeControl) ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d),
stringResource(R.string.glasses_auto3d_hint), s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) }
@@ -226,7 +226,7 @@ internal fun GlassesGroups(
format = { "$it°" }, modifier = track("glasses-vr-fov")) { Glasses.setVrFovDeg(it) }
}
if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) {
SettingsGroup(stringResource(R.string.glasses_head_tracking), key = "vr-glasses-tracking") {
SettingsGroup(stringResource(R.string.glasses_head_tracking)) {
val trackingHint = when {
inSession && !usesGlasses -> R.string.glasses_screen_no_output
spatialVr -> R.string.glasses_head_tracking_spatial_vr_hint
@@ -240,13 +240,13 @@ internal fun GlassesGroups(
chipModifier = track("glasses-tracking")) { Glasses.setHeadTracking(it) }
}
val calibration by Glasses.calibration.collectAsState()
if (calibration.supported) SettingsGroup(stringResource(R.string.glasses_calibration), key = "vr-glasses-calibration") {
if (calibration.supported) SettingsGroup(stringResource(R.string.glasses_calibration)) {
GlassesCalibrationControls(calibration,
onStart = Glasses::startCalibration, onCancel = Glasses::cancelCalibration,
onReset = Glasses::resetCalibration, onDone = { onRecenter?.invoke() })
}
}
if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.glasses_hardware), key = "vr-glasses-hardware") {
if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.glasses_hardware)) {
if (g.brightnessMax > 0) SliderRow(stringResource(R.string.glasses_brightness), null, g.brightness.coerceAtLeast(0), 0..g.brightnessMax, step = 1,
modifier = track("glasses-brightness")) { Glasses.setBrightness(it) }
if (g.volumeMax > 0) SliderRow(stringResource(R.string.glasses_volume), null, g.volume.coerceAtLeast(0), 0..g.volumeMax, step = 1,
@@ -259,7 +259,7 @@ internal fun GlassesGroups(
androidx.compose.runtime.LaunchedEffect(Unit) { HandTracking.load(context) }
if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) {
if (g.spatialConnected) {
SettingsGroup(stringResource(R.string.glasses_experimental), key = "vr-glasses-experimental") {
SettingsGroup(stringResource(R.string.glasses_experimental)) {
val spatial by SpatialTracking.status.collectAsState()
ToggleRow(host, "glasses-position", stringResource(R.string.glasses_position), stringResource(R.string.glasses_position_hint),
s.positionalTracking, chipModifier = track("glasses-position")) { Glasses.setPositionalTracking(it) }
@@ -282,7 +282,7 @@ internal fun GlassesGroups(
s.joyConTracking, enabled = s.positionalTracking, chipModifier = track("glasses-joycons")) { Glasses.setJoyConTracking(it) }
}
}
if (hands.usable) SettingsGroup(stringResource(R.string.phone_camera_tracking_group), key = "vr-hand-camera") {
if (hands.usable) SettingsGroup(stringResource(R.string.phone_camera_tracking_group)) {
HandCameraRows(host, track, inSession)
}
}
@@ -44,7 +44,6 @@ import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.max
import kotlin.math.min
@SuppressLint("ViewConstructor")
@@ -64,7 +63,6 @@ class InputSurfaceView(
private val art by lazy(LazyThreadSafetyMode.NONE) { PadArt(context) }
private var artworkDpad = emptyList<HoldButton>()
private val artworkDpadBounds = RectF()
private var crossDpads = emptyList<Pair<List<HoldButton>, RectF>>()
private var requestedLayout = customLayout
init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
@@ -187,7 +185,6 @@ class InputSurfaceView(
private fun renderCustom(pad: PadBridge?) {
artworkDpad = emptyList()
crossDpads = emptyList()
val canvas = object : ViewGroup(context) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val layout = customLayout
@@ -206,7 +203,6 @@ class InputSurfaceView(
child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight)
}
updateArtworkDpad(this)
updateCrossDpad(this)
}
override fun dispatchDraw(canvas: Canvas) {
@@ -248,39 +244,11 @@ class InputSurfaceView(
canvas.getChildAt(index) as? HoldButton
}
val previous = artworkDpad
artworkDpad = if (crossed(buttons, artworkDpadBounds)) buttons else emptyList()
artworkDpad = if (crossed(buttons)) buttons else emptyList()
if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() }
}
private fun updateCrossDpad(canvas: ViewGroup) {
val buttons = (0 until canvas.childCount).map(canvas::getChildAt).filterIsInstance<HoldButton>()
val (ups, rights, downs, lefts) = DIRECTIONS.map { direction -> buttons.filter { (it.tag as? InputSurfaceElement)?.control == direction } }
crossDpads = ups.flatMap { up -> rights.flatMap { right -> downs.flatMap { down ->
lefts.mapNotNull { left -> listOf(up, right, down, left).let { arms -> hole(arms)?.let { arms to it } } } } } }
}
private fun hole(buttons: List<HoldButton>): RectF? {
val (up, right, down, left) = buttons
val hole = RectF(left.right.toFloat(), up.bottom.toFloat(), right.left.toFloat(), down.top.toFloat())
val across = max(up.left, down.left) to min(up.right, down.right)
val along = max(left.top, right.top) to min(left.bottom, right.bottom)
return hole.takeIf {
!it.isEmpty && across.first < across.second && along.first < along.second &&
across.first < it.right && across.second > it.left && along.first < it.bottom && along.second > it.top
}
}
private fun crossTarget(x: Float, y: Float): HoldButton? {
val first = crossDpads.firstOrNull()?.first?.first() ?: return null
val hx = x - (originX(first) - first.left)
val hy = y - (originY(first) - first.top)
return crossDpads.filter { (arms, hole) -> arms.all { it.visibility == VISIBLE } && hole.contains(hx, hy) }
.flatMap { it.first }.distinct().minByOrNull { arm ->
hypot(max(max(arm.left - hx, hx - arm.right), 0f), max(max(arm.top - hy, hy - arm.bottom), 0f))
}
}
private fun crossed(buttons: List<HoldButton>, bounds: RectF): Boolean {
private fun crossed(buttons: List<HoldButton>): Boolean {
if (buttons.size != DIRECTIONS.size) return false
val (up, right, down, left) = buttons
val centerX = (left.left + right.right) / 2f
@@ -290,7 +258,7 @@ class InputSurfaceView(
kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f ||
kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f ||
up.bottom >= down.top || left.right >= right.left) return false
bounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
return true
}
@@ -316,7 +284,6 @@ class InputSurfaceView(
val views = (canvas.childCount - 1 downTo 0).map(canvas::getChildAt).filter { it.visibility == VISIBLE }
views.firstOrNull { !(it is StickView && it.adaptive) && hits(it, x, y, 0f) }?.let { return it }
views.filter { it is HoldButton && hits(it, x, y, slack(it)) }.minByOrNull { distance(it, x, y) }?.let { return it }
crossTarget(x, y)?.let { return it }
if (views.any { it is HoldButton && hits(it, x, y, slack(it) + ADAPTIVE_CLEARANCE_PX) }) return null
return views.filter { it is StickView && it.adaptive && it !in owners.values && (hits(it, x, y, 0f) || it.captures(x - originX(it), y - originY(it))) }
.minByOrNull { distance(it, x, y) }
@@ -282,7 +282,7 @@ private fun NotInstalledRow(count: Int, expanded: Boolean, keys: Modifier, onFoc
internal fun libraryColumns(width: Int, base: Int, gap: Int, level: Int): Int =
(((width + gap) / (base + gap)).coerceAtLeast(1) + LibraryDisplay.DEFAULT_LEVEL - level).coerceAtLeast(1)
private class LevelCells(private val base: androidx.compose.ui.unit.Dp, private val level: Int) : GridCells {
internal class LevelCells(private val base: androidx.compose.ui.unit.Dp, private val level: Int) : GridCells {
override fun androidx.compose.ui.unit.Density.calculateCrossAxisCellSizes(availableSize: Int, spacing: Int): List<Int> {
val count = libraryColumns(availableSize, base.roundToPx(), spacing, level)
val usable = (availableSize - spacing * (count - 1)).coerceAtLeast(0)
@@ -935,6 +935,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
val label = when (id) {
LIBRARY_ALL -> stringResource(R.string.stores_tab_all)
Library.ADDED -> stringResource(R.string.library_custom_games)
com.droiddeck.launcher.runtime.RecompShortcuts.SOURCE -> stringResource(R.string.rail_recomps)
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> store?.shortLabel ?: sourceLabel(id)
@@ -967,6 +968,7 @@ private fun LibraryFilters(sources: List<String>, source: String, onSource: (Str
private fun sourceTitle(src: String): String = when (src) {
LIBRARY_ALL -> stringResource(R.string.library_all_games)
Library.ADDED -> stringResource(R.string.library_custom_games)
com.droiddeck.launcher.runtime.RecompShortcuts.SOURCE -> stringResource(R.string.rail_recomps)
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> Store.byId(src)?.label ?: sourceLabel(src)
@@ -119,12 +119,12 @@ internal object StoreTabsState {
}
/** The Library tabs that are not stores but sort among them in Manage stores. Only Favorites, Custom games and Hidden can be turned off; Hidden starts off. */
internal val LIBRARY_OWN_TABS = listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, Library.ADDED, LIBRARY_HIDDEN)
internal val LIBRARY_HIDEABLE_TABS = setOf(LIBRARY_FAVORITES, Library.ADDED, LIBRARY_HIDDEN)
internal val LIBRARY_OWN_TABS = listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, Library.ADDED, com.droiddeck.launcher.runtime.RecompShortcuts.SOURCE, LIBRARY_HIDDEN)
internal val LIBRARY_HIDEABLE_TABS = setOf(LIBRARY_FAVORITES, Library.ADDED, com.droiddeck.launcher.runtime.RecompShortcuts.SOURCE, LIBRARY_HIDDEN)
/** Favorites, then Steam, ahead of the stores; Custom games and Hidden after them (null: the end). */
internal val DEFAULT_LIBRARY_PLACES: List<Pair<String, String?>> =
listOf(LIBRARY_FAVORITES to "", Library.SOURCE_STEAM to LIBRARY_FAVORITES, Library.ADDED to null, LIBRARY_HIDDEN to null)
listOf(LIBRARY_FAVORITES to "", Library.SOURCE_STEAM to LIBRARY_FAVORITES, Library.ADDED to null, com.droiddeck.launcher.runtime.RecompShortcuts.SOURCE to Library.ADDED, LIBRARY_HIDDEN to null)
/**
* Puts the Library's own tabs into a store tab order. Each goes after the tab it follows ("" for first; null or a tab that is gone
@@ -339,6 +339,7 @@ private fun LibraryTabSortRow(id: String, held: Boolean, offset: Float, hint: St
val label = when (id) {
LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites)
Library.ADDED -> stringResource(R.string.library_custom_games)
com.droiddeck.launcher.runtime.RecompShortcuts.SOURCE -> stringResource(R.string.rail_recomps)
LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden)
else -> stringResource(R.string.source_steam)
}
@@ -26,10 +26,10 @@ internal object DeveloperTools {
internal object NavTabs {
const val MORE = "more"
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "agent")
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "recomps", "android-apps", "agent")
val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "recomps", "agent")
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "agent")
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "recomps", "agent")
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync")
private const val LAYOUT_VERSION = 2
@@ -116,7 +116,10 @@ internal object NavTabs {
fun more(s: FrontEndState) = listed(s).filter { place(s, it) == TabPlace.MORE }
fun bar(s: FrontEndState): List<String> = listed(s).filter { place(s, it) == TabPlace.BAR } + MORE
fun bar(s: FrontEndState): List<String> {
val shown = listed(s).filter { place(s, it) == TabPlace.BAR }
return if (more(s).isEmpty()) shown else shown + MORE
}
fun setHidden(context: Context, key: String, hide: Boolean) {
hidden = if (hide && hideable(key)) hidden + key else hidden - key
@@ -11,7 +11,7 @@ internal fun PenSettingsGroup(
host: MenuHost, pen: SessionPrefs.Pen, track: (String) -> Modifier = { Modifier },
onPick: (key: String, value: String) -> Unit,
) {
SettingsGroup(stringResource(R.string.mode_pen), key = "controller-pen") {
SettingsGroup(stringResource(R.string.mode_pen)) {
ChoiceRow(host, "pen", stringResource(R.string.mode_pen), null,
listOf(SessionPrefs.PEN_MOUSE to stringResource(R.string.mode_pen_mouse),
SessionPrefs.PEN_TOUCH to stringResource(R.string.mode_pen_touch)),
@@ -49,7 +49,6 @@ fun PerformancePage(
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
nativeUserland: Boolean,
desktopAsUser: Boolean,
cursorComposite: Boolean,
guestHostname: String,
phantomWarning: String?,
@@ -68,7 +67,6 @@ fun PerformancePage(
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onNativeUserland: (Boolean) -> Unit,
onDesktopAsUser: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
onClientCore: (Int, Boolean) -> Unit,
@@ -196,12 +194,6 @@ fun PerformancePage(
modifier = Modifier.width(220.dp).focusGlide(),
)
}
ToggleRow(
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native),
desktopAsUser && nativeUserland, enabled = nativeUserland,
onChange = onDesktopAsUser,
)
}
if (phantomWarning != null) {
Spacer(Modifier.height(16.dp))
@@ -226,7 +218,7 @@ fun PerformancePage(
@Composable
internal fun GpuClockGroup(host: MenuHost, on: Boolean, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) {
SettingsGroup(stringResource(R.string.perf_gpu), key = "performance-gpu") {
SettingsGroup(stringResource(R.string.perf_gpu)) {
ToggleRow(
host, "gpuclock", stringResource(R.string.perf_gpuclock),
null,
@@ -0,0 +1,588 @@
package com.droiddeck.launcher.ui
import android.content.Intent
import android.net.Uri
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.FilterAlt
import androidx.compose.material.icons.filled.Sort
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.boundsInRoot
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.runtime.RecompAndroid
import com.droiddeck.launcher.runtime.RecompCatalog
import com.droiddeck.launcher.runtime.RecompData
import com.droiddeck.launcher.runtime.RecompInstaller
import com.droiddeck.launcher.store.RecompsState
import com.droiddeck.launcher.store.UserAppsState
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
// The first five narrow by your state; the HAS_ ones by which builds a project publishes. Every ticked filter must
// hold, so Linux ARM64 + Linux x86-64 + Windows leaves only projects with all three.
internal enum class RecompFilter(val build: RecompCatalog.Platform? = null) {
INSTALLED, OWNED, NATIVE, UPDATE, NO_SETUP,
HAS_LINUX_ARM64(RecompCatalog.Platform.LINUX_ARM64), HAS_LINUX_X64(RecompCatalog.Platform.LINUX_X64),
HAS_WINDOWS(RecompCatalog.Platform.WINDOWS_X64), HAS_ANDROID(RecompCatalog.Platform.ANDROID),
}
internal enum class RecompSort { BEST, POPULAR, UPDATED, LISTED, TITLE }
// Kept while the app runs, like the Library's search and sort, so leaving the tab and coming back keeps your place.
internal object RecompsView {
var query by mutableStateOf("")
var filters by mutableStateOf(emptySet<RecompFilter>())
var sort by mutableStateOf(RecompSort.BEST)
var system by mutableStateOf<String?>(null)
var open by mutableStateOf<String?>(null)
}
internal class RecompRow(
val entry: RecompCatalog.Entry, val data: RecompData.State, val installed: RecompInstaller.Installed?,
val update: RecompInstaller.Release?, val incompatible: Set<String> = emptySet(),
) {
val platform get() = installed?.platform?.let { RecompCatalog.Platform.of(it) } ?: entry.preferred(incompatible)?.platform
fun runs(build: RecompCatalog.Build) = build.pkg == null || build.pkg !in incompatible
}
internal fun recompRows(): List<RecompRow> = RecompsState.entries.map { e ->
RecompRow(e, RecompsState.data[e.id] ?: RecompData.State.BringYourOwn(e.data), RecompsState.installed[e.id], RecompsState.updates[e.id],
RecompsState.incompatible)
}
private val NATIVE = setOf(RecompCatalog.Platform.LINUX_ARM64, RecompCatalog.Platform.ANDROID)
private fun RecompRow.owned() = data is RecompData.State.Found || data is RecompData.State.Owned || data is RecompData.State.Incomplete
internal fun RecompRow.matches(filter: RecompFilter): Boolean = when (filter) {
RecompFilter.INSTALLED -> installed != null
RecompFilter.OWNED -> owned()
RecompFilter.NATIVE -> platform in NATIVE
RecompFilter.UPDATE -> update != null
RecompFilter.NO_SETUP -> entry.setup == null
else -> entry.build(filter.build!!) != null
}
internal fun RecompRow.matches(query: String): Boolean = query.isBlank() || query.trim().split(Regex("\\s+")).all { word ->
listOf(entry.name, entry.game, entry.origin, entry.repo).any { it.contains(word, ignoreCase = true) }
}
// The original systems present in the list, most entries first; a system with one entry is not worth a chip.
internal fun recompSystems(rows: List<RecompRow>): List<Pair<String, Int>> =
rows.groupingBy { it.entry.origin }.eachCount().filter { (origin, n) -> origin.isNotEmpty() && n > 1 }
.toList().sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first })
// Best for you: installed, then games you have on a store, then native builds, each by popularity.
internal fun RecompRow.rank(): Int = when {
installed != null -> 0
data is RecompData.State.Found -> 1
owned() -> 2
platform in NATIVE -> 3
else -> 4
}
internal fun recompOrder(sort: RecompSort): Comparator<RecompRow> = when (sort) {
RecompSort.BEST -> compareBy<RecompRow> { it.rank() }.thenByDescending { it.entry.popularity }
RecompSort.POPULAR -> compareByDescending { it.entry.popularity }
RecompSort.UPDATED -> compareByDescending { it.entry.updated }
RecompSort.LISTED -> compareByDescending { it.entry.listed }
RecompSort.TITLE -> compareBy { it.entry.name.lowercase() }
}.thenBy { it.entry.name.lowercase() }
internal fun visibleRecomps(rows: List<RecompRow>, query: String, filters: Set<RecompFilter>, system: String?, sort: RecompSort): List<RecompRow> =
rows.filter { r -> r.matches(query) && filters.all { r.matches(it) } && (system == null || r.entry.origin == system) }.sortedWith(recompOrder(sort))
private val RecompTileWidth = 116.dp
@Composable
internal fun RecompsPage(s: FrontEndState, a: FrontEndActions, onSelect: (String) -> Unit, modifier: Modifier) {
val ctx = LocalContext.current
val steamOwned = s.steamGames.filter { it.source == Library.SOURCE_STEAM }.map { it.appId to it.name }
LaunchedEffect(steamOwned.size, StoresState.installed.size, StoresState.library.size) {
RecompsState.refresh(ctx, steamOwned)
UserAppsState.refresh(ctx)
}
val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
val observer = androidx.lifecycle.LifecycleEventObserver { _, event ->
if (event == androidx.lifecycle.Lifecycle.Event.ON_RESUME) RecompsState.refresh(ctx, steamOwned)
}
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
val rows = remember(RecompsState.entries, RecompsState.data, RecompsState.installed, RecompsState.updates, RecompsState.incompatible) { recompRows() }
val opened = RecompsView.open?.let { id -> rows.firstOrNull { it.entry.id == id } }
if (opened != null) {
BackHandler { RecompsView.open = null }
RecompDetail(opened, s, a, onSelect, steamOwned, modifier)
return
}
val searched = remember(rows, RecompsView.query) { rows.filter { it.matches(RecompsView.query) } }
val shown = remember(searched, RecompsView.filters, RecompsView.system, RecompsView.sort) {
visibleRecomps(searched, "", RecompsView.filters, RecompsView.system, RecompsView.sort)
}
val systems = remember(searched, RecompsView.filters) { recompSystems(searched.filter { r -> RecompsView.filters.all { r.matches(it) } }) }
val colors = MaterialTheme.colorScheme
Column(modifier) {
ModeHeader(
stringResource(R.string.rail_recomps), RecompsView.query, { RecompsView.query = it },
placeholder = stringResource(R.string.recomps_search), inlineWhenStacked = true,
lead = {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(end = 4.dp)) {
Text(stringResource(R.string.rail_recomps), fontSize = if (LocalNarrowPane.current) 20.sp else 24.sp, fontWeight = FontWeight.Bold,
color = colors.onBackground, maxLines = 1)
Text(shown.size.toString(), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.testTag("recomps-count"))
}
},
) {
RecompFilterButton(searched)
RecompSortButton()
DisplayButton()
}
ActiveFilters()
if (systems.size > 1) Row(
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(top = 8.dp, bottom = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
TabChip(stringResource(R.string.recomps_every_system), RecompsView.system == null, Modifier.testTag("recomps-system-all")) { RecompsView.system = null }
systems.forEach { (origin, n) ->
TabChip("$origin · $n", RecompsView.system == origin, Modifier.testTag("recomps-system-$origin")) {
RecompsView.system = if (RecompsView.system == origin) null else origin
}
}
}
UserAppsState.lastError?.let { Box(Modifier.padding(top = 8.dp)) { Note(it) } }
when {
RecompsState.loading -> Text("…", color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 16.dp))
rows.isEmpty() -> Box(Modifier.padding(top = 12.dp)) { Note(stringResource(R.string.recomps_empty)) }
shown.isEmpty() -> Box(Modifier.padding(top = 12.dp)) { Note(stringResource(R.string.recomps_none_here)) }
else -> {
val level = LibraryDisplay.level
LazyVerticalGrid(
columns = remember(level) { LevelCells(RecompTileWidth, level) }, state = rememberLazyGridState(),
horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
contentPadding = PaddingValues(top = 8.dp, bottom = 24.dp),
modifier = Modifier.fillMaxSize().testTag("recomps-list"),
) {
items(shown, key = { it.entry.id }) { row -> RecompTile(row, first = row === shown.first()) { RecompsView.open = row.entry.id } }
item(key = "credits", span = { GridItemSpan(maxLineSpan) }) {
Text(stringResource(R.string.recomps_credits), fontSize = 11.sp, color = colors.onSurfaceVariant,
modifier = Modifier.padding(top = 12.dp).testTag("recomps-credits"))
}
}
}
}
}
}
@Composable
private fun filterLabel(f: RecompFilter) = stringResource(when (f) {
RecompFilter.INSTALLED -> R.string.recomps_filter_installed
RecompFilter.OWNED -> R.string.recomps_filter_owned
RecompFilter.NATIVE -> R.string.recomps_filter_native
RecompFilter.UPDATE -> R.string.recomps_filter_update
RecompFilter.NO_SETUP -> R.string.recomps_filter_no_setup
RecompFilter.HAS_LINUX_ARM64 -> R.string.recomps_has_linux_arm64
RecompFilter.HAS_LINUX_X64 -> R.string.recomps_has_linux_x64
RecompFilter.HAS_WINDOWS -> R.string.recomps_has_windows
RecompFilter.HAS_ANDROID -> R.string.recomps_has_android
})
@Composable
private fun sortLabel(sort: RecompSort) = stringResource(when (sort) {
RecompSort.BEST -> R.string.recomps_sort_best
RecompSort.POPULAR -> R.string.recomps_sort_popular
RecompSort.UPDATED -> R.string.recomps_sort_updated
RecompSort.LISTED -> R.string.recomps_sort_listed
RecompSort.TITLE -> R.string.recomps_sort_title
})
@Composable
private fun RecompFilterButton(rows: List<RecompRow>) {
val pal = LocalPalette.current
val title = stringResource(R.string.library_filter)
var at by remember { mutableStateOf<Rect?>(null) }
val counts = remember(rows) { RecompFilter.entries.associateWith { f -> rows.count { it.matches(f) } } }
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }.testTag("recomps-filter")) {
HeaderIconButton(title, Icons.Filled.FilterAlt, "recomps-filter") {
val from = at ?: return@HeaderIconButton
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = RecompFilter.entries.size + 2,
handle = { Icon(Icons.Filled.FilterAlt, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
) {
StepTitle(title)
StepList {
var item = 0
listOf(R.string.recomps_filter_show to RecompFilter.entries.filter { it.build == null },
R.string.recomps_filter_builds to RecompFilter.entries.filter { it.build != null }).forEach { (heading, group) ->
Text(stringResource(heading), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.stepItem(item++).padding(start = 4.dp, top = 8.dp, bottom = 2.dp))
group.forEach { f ->
StepChoice(
filterLabel(f), selected = f in RecompsView.filters, enabled = open, trailing = counts[f]?.toString(),
modifier = Modifier.fillMaxWidth().stepItem(item++).testTag("recomps-filter-${f.name.lowercase()}")
.then(if (f.ordinal == 0) Modifier.focusRequester(first) else Modifier),
) {
RecompsView.filters = if (f in RecompsView.filters) RecompsView.filters - f else RecompsView.filters + f
}
}
}
}
})
}
if (RecompsView.filters.isNotEmpty()) Box(Modifier.align(Alignment.TopEnd).size(8.dp).clip(CircleShape).background(pal.signal))
}
}
@Composable
private fun RecompSortButton() {
val pal = LocalPalette.current
val title = stringResource(R.string.stores_sort)
var at by remember { mutableStateOf<Rect?>(null) }
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }.testTag("recomps-sort")) {
HeaderIconButton(title + " · " + sortLabel(RecompsView.sort), Icons.Filled.Sort, "recomps-sort") {
val from = at ?: return@HeaderIconButton
Steps.ask(StepAsk(
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = RecompSort.entries.size,
handle = { Icon(Icons.Filled.Sort, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
) {
StepTitle(title)
StepList {
RecompSort.entries.forEachIndexed { i, sort ->
StepChoice(
sortLabel(sort), selected = sort == RecompsView.sort, enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(i).testTag("recomps-sort-${sort.name.lowercase()}")
.then(if (sort == RecompsView.sort) Modifier.focusRequester(first) else Modifier),
) {
RecompsView.sort = sort
Steps.fold()
}
}
}
})
}
}
}
// The filters in use, each one a tap to remove, so a filtered grid never looks like the whole list.
@Composable
private fun ActiveFilters() {
val filters = RecompsView.filters
if (filters.isEmpty() && RecompsView.sort == RecompSort.BEST) return
Row(
Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(top = 6.dp),
horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically,
) {
if (RecompsView.sort != RecompSort.BEST) Text(sortLabel(RecompsView.sort), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(end = 6.dp))
filters.sortedBy { it.ordinal }.forEach { f ->
TabChip(filterLabel(f) + " ✕", true, Modifier.testTag("recomps-active-${f.name.lowercase()}")) { RecompsView.filters = RecompsView.filters - f }
}
if (filters.size > 1) TabChip(stringResource(R.string.recomps_clear_filters), false) { RecompsView.filters = emptySet() }
}
}
@Composable
private fun platformShort(platform: RecompCatalog.Platform?) = when (platform) {
RecompCatalog.Platform.LINUX_ARM64 -> stringResource(R.string.recomps_runs_native)
RecompCatalog.Platform.ANDROID -> stringResource(R.string.recomps_runs_android)
RecompCatalog.Platform.LINUX_X64 -> stringResource(R.string.recomps_runs_fex)
RecompCatalog.Platform.WINDOWS_X64 -> stringResource(R.string.recomps_runs_proton)
null -> ""
}
@Composable
private fun RecompTile(row: RecompRow, first: Boolean, onOpen: () -> Unit) {
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val e = row.entry
val installing = UserAppsState.working == e.name
Column(
Modifier.fillMaxWidth().testTag("recomp-${e.id}").paneItem("recomp:${e.id}").then(if (first) Modifier.paneEntry() else Modifier)
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onOpen)
.controllerConfirm(onClick = onOpen),
) {
ArtCard(
e.name, wide = e.art, tall = e.cover ?: e.art, download = null, hot = hot, capsule = true,
chip = if (installing) stringResource(R.string.recomps_installing) else null,
badge = { TileBadges(row) },
) {
Text(listOf(e.origin, platformShort(row.platform)).filter { it.isNotEmpty() }.joinToString(" · "),
fontSize = 10.sp, color = Color.White.copy(alpha = 0.75f), maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
@Composable
private fun androidx.compose.foundation.layout.BoxScope.TileBadges(row: RecompRow) {
val pal = LocalPalette.current
Column(Modifier.align(Alignment.TopStart).padding(6.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
if (row.installed != null) Icon(Icons.Filled.CheckCircle, stringResource(R.string.recomps_filter_installed), tint = pal.good,
modifier = Modifier.size(18.dp).clip(CircleShape).background(Color.Black.copy(alpha = 0.55f)))
val store = when (val d = row.data) {
is RecompData.State.Found -> d.store
is RecompData.State.Owned -> d.store
is RecompData.State.Incomplete -> d.store
else -> null
}
if (store != null) Text(store.shortLabel, fontSize = 9.sp, fontWeight = FontWeight.Bold, color = Color.White,
modifier = Modifier.clip(RoundedCornerShape(4.dp)).background(Color.Black.copy(alpha = 0.6f)).padding(horizontal = 5.dp, vertical = 2.dp))
}
if (row.update != null) Box(Modifier.align(Alignment.TopEnd).padding(7.dp).size(9.dp).clip(CircleShape).background(AttentionAmber))
}
@Composable
private fun buildLabel(platform: RecompCatalog.Platform?) = stringResource(when (platform) {
RecompCatalog.Platform.LINUX_ARM64 -> R.string.recomps_build_linux_arm64
RecompCatalog.Platform.LINUX_X64 -> R.string.recomps_build_linux_x64
RecompCatalog.Platform.WINDOWS_X64 -> R.string.recomps_build_windows_x64
RecompCatalog.Platform.ANDROID -> R.string.recomps_build_android
else -> R.string.recomps_build_none
})
private fun storeName(store: Store) = store.shortLabel
private fun sourceName(source: String): String? = listOf(RecompCatalog.DECOMP_BUDDY, RecompCatalog.RECOMP_LAUNCHER, RecompCatalog.RECOMPA)
.firstOrNull { it.id == source }?.name
@Composable
private fun dataLine(data: RecompData.State): Pair<String, Boolean>? = when (data) {
RecompData.State.NotNeeded -> null
is RecompData.State.Found -> when {
data.checked -> stringResource(R.string.recomps_data_found_checked, storeName(data.store)) to true
data.exact -> stringResource(R.string.recomps_data_found, storeName(data.store)) to true
else -> stringResource(R.string.recomps_data_found_by_name, storeName(data.store)) to false
}
is RecompData.State.Incomplete -> stringResource(
if (data.wrongVersion) R.string.recomps_data_wrong_version else R.string.recomps_data_missing_file,
storeName(data.store), data.file.substringAfterLast('/'),
) to false
is RecompData.State.Owned -> stringResource(R.string.recomps_data_owned, storeName(data.store)) to false
is RecompData.State.BringYourOwn -> stringResource(R.string.recomps_data_bring, data.data.label.replace(Regex("^(your own |your )", RegexOption.IGNORE_CASE), "")) to false
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun RecompDetail(
row: RecompRow, s: FrontEndState, a: FrontEndActions, onSelect: (String) -> Unit, steamOwned: List<Pair<Int, String>>, modifier: Modifier,
) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val e = row.entry
val open: (String) -> Unit = { url -> runCatching { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } }
var picked by remember(e.id, row.installed?.platform) { mutableStateOf<RecompCatalog.Platform?>(null) }
LaunchedEffect(e.id) { RecompsState.verify(ctx, e, steamOwned) }
BoxWithConstraints(modifier) {
val stacked = maxWidth < 640.dp
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 24.dp).testTag("recomp-detail-${e.id}")) {
BackLink(stringResource(R.string.rail_recomps)) { RecompsView.open = null }
val cover: @Composable () -> Unit = {
Box(Modifier.width(if (stacked) 132.dp else 180.dp).aspectRatio(5f / 7f).clip(RoundedCornerShape(12.dp)).background(artBrush(hueOf(e.name))),
contentAlignment = Alignment.Center) {
Text(e.name.take(1), fontSize = 40.sp, fontWeight = FontWeight.Bold, color = colors.onBackground.copy(alpha = 0.5f))
(e.cover ?: e.art)?.let { AsyncImage(model = it, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize()) }
}
}
val heading: @Composable () -> Unit = {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(e.name, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
val kind = stringResource(if (e.type == "recomp") R.string.recomps_kind_recomp else R.string.recomps_kind_port, e.origin)
Text(listOf(e.game.takeIf { it != e.name }, kind).filterNotNull().joinToString(" · "), fontSize = 14.sp, color = colors.onSurfaceVariant)
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Chip(buildLabel(row.platform), ok = row.platform in NATIVE)
dataLine(row.data)?.let { (t, ok) -> Chip(t, ok) }
if (e.setup != null) Chip(stringResource(R.string.recomps_setup), ok = false)
}
Spacer(Modifier.height(4.dp))
RecompActions(row, s, a, onSelect, steamOwned, open, picked)
}
}
if (stacked) Column(verticalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.padding(top = 8.dp)) { cover(); heading() }
else Row(horizontalArrangement = Arrangement.spacedBy(22.dp), modifier = Modifier.padding(top = 8.dp)) {
cover(); Box(Modifier.weight(1f)) { heading() }
}
RecompsState.errors[e.id]?.let { Box(Modifier.padding(top = 12.dp).testTag("recomp-error")) { Note(it) } }
if (UserAppsState.working == e.name && UserAppsState.stage != null) {
Text(UserAppsState.stage.orEmpty(), fontSize = 12.sp, color = pal.signal, modifier = Modifier.padding(top = 10.dp))
}
DetailSection(stringResource(R.string.recomps_section_needs)) {
val found = row.data as? RecompData.State.Found
when {
found != null -> DetailText(stringResource(R.string.recomps_data_folder, found.guest))
row.data is RecompData.State.NotNeeded -> DetailText(stringResource(R.string.recomps_needs_nothing))
else -> DetailText(e.data.label)
}
e.data.file?.let { DetailText(stringResource(R.string.recomps_needs_file, it)) }
if (row.data is RecompData.State.BringYourOwn && e.data.note.isNotEmpty() && e.data.note != e.data.label) DetailText(e.data.note)
e.setup?.takeIf { it.isNotBlank() }?.let { DetailText(it) }
}
DetailSection(stringResource(R.string.recomps_section_builds)) {
val installedAs = row.installed?.platform?.let { RecompCatalog.Platform.of(it) }
e.builds.sortedBy { RecompCatalog.PREFERENCE.indexOf(it.platform).let { i -> if (i < 0) 99 else i } }.forEach { b ->
val status = when {
installedAs == b.platform -> stringResource(R.string.recomps_build_installed)
!row.runs(b) -> stringResource(R.string.recomps_not_for_device)
installedAs == RecompCatalog.Platform.LINUX_ARM64 && b.platform == RecompCatalog.Platform.LINUX_X64 &&
e.build(RecompCatalog.Platform.LINUX_ARM64) == null -> stringResource(R.string.recomps_build_installed_arm)
else -> b.tag
}
BuildChoice(buildLabel(b.platform), status, selected = (picked ?: row.platform) == b.platform,
modifier = Modifier.testTag("recomp-build-${b.platform.key}")) { picked = b.platform }
}
DetailText(stringResource(R.string.recomps_builds_hint))
}
DetailSection(stringResource(R.string.recomps_section_about)) {
DetailText(e.repo)
if (e.license.isNotEmpty()) DetailText(e.license)
DetailText(e.sources.mapNotNull { sourceName(it) }.joinToString(" · ") { ctx.getString(R.string.recomps_via, it) })
}
}
}
}
@Composable
private fun DetailSection(title: String, content: @Composable () -> Unit) {
Column(Modifier.fillMaxWidth().padding(top = 18.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(headingUppercase(title), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 2.dp))
content()
}
}
@Composable
private fun DetailText(text: String, strong: Boolean = false) =
Text(text, fontSize = 13.sp, color = if (strong) MaterialTheme.colorScheme.onBackground else MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = if (strong) FontWeight.SemiBold else FontWeight.Normal)
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun RecompActions(
row: RecompRow, s: FrontEndState, a: FrontEndActions, onSelect: (String) -> Unit, steamOwned: List<Pair<Int, String>>, open: (String) -> Unit,
picked: RecompCatalog.Platform?,
) {
val ctx = LocalContext.current
val e = row.entry
val busy = UserAppsState.working
val mine = busy == e.name
val inst = row.installed
val chosen = picked?.let { e.build(it) }
val switching = inst != null && chosen != null && picked != row.platform
val progress = if (mine) UserAppsState.percent.takeIf { it >= 0 }?.let { it / 100f } else null
val focus = Modifier.paneEntry()
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
when {
inst == null || switching -> PrimaryButton(
when {
switching -> stringResource(R.string.recomps_install_instead, buildLabel(picked))
picked != null -> stringResource(R.string.recomps_install_build, buildLabel(picked))
else -> stringResource(R.string.recomps_install)
},
enabled = (chosen ?: e.preferred()) != null && busy == null && s.ready, main = true,
progress = progress, modifier = focus.testTag("recomp-install-${e.id}"),
) { RecompsState.install(ctx, e, steamOwned, chosen = chosen) }
inst.appKey.startsWith("android:") -> PrimaryButton(stringResource(R.string.recomps_play), main = true,
modifier = focus.testTag("recomp-play-${e.id}")) { RecompAndroid.launch(ctx, inst.appKey.removePrefix("android:")) }
inst.appKey.startsWith("added:") -> PrimaryButton(stringResource(R.string.recomps_open_games), main = true, modifier = focus) { onSelect("games") }
else -> PrimaryButton(stringResource(R.string.recomps_play), main = true, enabled = !s.busy, modifier = focus.testTag("recomp-play-${e.id}")) {
UserAppsState.items.firstOrNull { it.key == inst.appKey }?.let(a.onUserApp)
}
}
if (inst != null && row.update != null) SecondaryButton(stringResource(R.string.recomps_update, row.update.tag), enabled = busy == null,
progress = progress) { RecompsState.install(ctx, e, steamOwned, row.update) }
(row.data as? RecompData.State.Owned)?.item?.let { item ->
SecondaryButton(stringResource(R.string.recomps_install_game)) { StoresState.requestInstall(ctx, item) }
}
SecondaryButton(stringResource(R.string.recomps_project)) { open(e.homepage) }
if (inst != null) SecondaryButton(stringResource(R.string.recomps_remove), enabled = busy == null) {
RecompsState.remove(ctx, e, steamOwned, inst)
}
}
}
@Composable
private fun BuildChoice(label: String, status: String?, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val shape = RoundedCornerShape(10.dp)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = modifier.fillMaxWidth().clip(shape)
.background(if (selected) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal, if (selected) pal.signal.copy(alpha = 0.5f) else pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.RadioButton, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp, vertical = 10.dp),
) {
Box(Modifier.size(18.dp).clip(CircleShape).background(if (selected) pal.signal else Color.Transparent)
.glideBorder(false, CircleShape, pal.signal, if (selected) pal.signal else colors.onSurfaceVariant), contentAlignment = Alignment.Center) {
if (selected) Box(Modifier.size(7.dp).clip(CircleShape).background(colors.background))
}
Text(label, fontSize = 14.sp, fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, color = colors.onBackground,
modifier = Modifier.weight(1f))
if (!status.isNullOrEmpty()) Text(status, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
@@ -6,18 +6,17 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionPrefs
/** HUD holds the Performance page and GAMES the Game page; the names stay because saved page orders use them. */
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("section-controller-input"),
HUD("section-performance-pacing"),
DISPLAY("section-display"),
EFFECTS("section-effects-look"),
GAMES("section-game-profile"),
VR("section-vr-steamvr"),
SESSION("pause"),
MORE("more-edit"),
ACHIEVEMENTS("achievements"),
CONTROLLER("input-profile"),
GLASSES("glasses-game"),
DISPLAY("fg"),
HUD("hud"),
EFFECTS("look"),
GAMES("anisotropy"),
AGENT("agent-input"),
SESSION("suspend"),
MORE("more-edit"),
VR("steamvr"),
}
internal object DrawerPages {
@@ -72,16 +71,16 @@ internal object DrawerPages {
}
internal fun offeredDrawerPages(
hasAchievements: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> =
DrawerPages.order.filter {
(hasAchievements || it != SessionDrawerPage.ACHIEVEMENTS) &&
(hasGlasses || it != SessionDrawerPage.GLASSES) &&
(hasAgent || it != SessionDrawerPage.AGENT)
}
internal fun sessionDrawerPages(
hasAchievements: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> = offeredDrawerPages(hasAchievements, hasAgent).filter { it !in DrawerPages.hidden }
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden }
/** The pages shown as tabs: everything up to and including the More tab. */
internal fun List<SessionDrawerPage>.strip(): List<SessionDrawerPage> {
File diff suppressed because it is too large. Load diff
@@ -89,7 +89,6 @@ internal object SettingsIndex {
s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"),
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
s(SettingsSection.CONTROLLER, R.string.setup_tab_controller, "gamepad", "buttons", "mapping", "profile", "remap"),
SettingsEntry(SettingsPlace.TAB, R.string.rail_storage, tab = "storage", words = listOf("sd card", "space", "uninstall", "disk")),
@@ -443,11 +443,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
}
@Composable
fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, key: String? = null, tag: String? = null, content: @Composable ColumnScope.() -> Unit) {
LocalDrawerSections.current?.let { sections ->
DrawerSection(sections, key ?: title, title, detail, tag, content)
return
}
fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, content: @Composable ColumnScope.() -> Unit) {
val tight = compact || LocalCompactSettings.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -56,7 +56,6 @@ import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
@@ -359,67 +358,6 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t
}
}
/** The Achievements page of the session menu: the same list as the full panel, inside the menu's own scroll. */
@Composable
internal fun DrawerAchievementsPage(game: StoreAchievements.Game, title: String?, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val label = StoreAchievements.forSource(game.source)?.label.orEmpty()
val state = rememberAchievements(game) ?: AchievementsState.READING
val kinds = remember(state.list) {
val list = state.list.orEmpty()
val split = groups(list)
if (split.size < 2) emptyList() else listOf(R.string.stores_tab_all to list) + split
}
var pick by remember { mutableIntStateOf(0) }
if (pick >= kinds.size) pick = 0
var noteHadFocus by remember { mutableStateOf(false) }
val firstRow = remember { FocusRequester() }
val loaded = !state.list.isNullOrEmpty()
LaunchedEffect(loaded) {
if (loaded && noteHadFocus) {
noteHadFocus = false
withFrameNanos { }
runCatching { firstRow.requestFocus() }
}
}
Column(Modifier.fillMaxWidth().padding(top = 8.dp, start = 4.dp, end = 4.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Text(title.orEmpty(), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
state.list?.takeIf { it.isNotEmpty() }?.let { list ->
if (state.all) Trophy(18.dp, Modifier.padding(end = 6.dp))
Text(stringResource(R.string.achievements_count_short, state.done, list.size), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = pal.signal)
}
}
val list = state.list
if (list.isNullOrEmpty()) {
Text(achievementsNote(state, label).orEmpty(), fontSize = 13.sp, color = colors.onSurfaceVariant,
modifier = Modifier.padding(top = 12.dp).then(track("achievements"))
.onFocusChanged { if (it.isFocused) noteHadFocus = true }.focusable())
return@Column
}
LinearProgressIndicator(
progress = { state.done / list.size.toFloat() }, color = pal.signal, trackColor = pal.line,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().height(4.dp).clip(RoundedCornerShape(2.dp)),
)
if (kinds.isNotEmpty()) TabStrip(
kinds.map { (name, group) -> if (name == R.string.stores_tab_all) stringResource(name) + " · " + group.size else stringResource(name, group.size) },
pick, { pick = it }, Modifier.padding(top = 10.dp), bumpers = false, compact = true,
)
val shown = kinds.getOrNull(pick)?.second ?: list
val sections = if (pick == 0) groups(shown).filter { it.second.isNotEmpty() } else listOf(null to shown)
val first = sections.firstOrNull()?.second?.firstOrNull()?.id
Column(Modifier.padding(top = 6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
for ((group, items) in sections) {
if (group != null) AchievementGroupLabel(stringResource(group, items.size))
for (a in items) androidx.compose.runtime.key(a.id) {
AchievementRow(a, compact = true, if (a.id == first) track("achievements").focusRequester(firstRow) else Modifier)
}
}
}
}
}
@Composable
internal fun DrawerAchievementsRow(progress: Pair<Int, Int>?, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -49,6 +49,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
internal fun sourceLabel(source: String): String = when (source) {
Library.SOURCE_STEAM, Store.STEAM.id -> stringResource(R.string.source_steam)
Library.SOURCE_COLLECTION -> stringResource(R.string.soundtracks_collections)
com.droiddeck.launcher.runtime.RecompShortcuts.SOURCE -> stringResource(R.string.rail_recomps)
Store.GOG.id -> Store.GOG.label
Store.EPIC.id -> Store.EPIC.label
Store.AMAZON.id -> Store.AMAZON.label
-3
View File
@@ -654,9 +654,6 @@
<string name="perf_hostname">اسم المضيف</string>
<string name="perf_hostname_hint">الاسم الذي يراه Steam لهذا الجهاز. اتركه خاليًا للاستعادة إلى %1$s.</string>
<string name="perf_hostname_invalid">أحرف وأرقام وشرطات داخلية فقط، حتى 63 حرفًا.</string>
<string name="perf_desktop_as_user">تشغيل سطح المكتب كمستخدم</string>
<string name="perf_desktop_as_user_hint">يعمل سطح المكتب وتطبيقاته وطرفياته كمستخدم عادي باسم deck بدلًا من root، للتطبيقات التي ترفض root. يظل sudo يعمل. يسري على سطح المكتب التالي.</string>
<string name="perf_desktop_as_user_needs_native">يتطلب التشغيل دون proot.</string>
<string name="perf_phantom_warning">Android مهيَّأ لإنهاء هذه الجلسة</string>
<string name="driver_installed">مثبّت</string>
<string name="driver_available">متاح للتنزيل</string>
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nombre del host</string>
<string name="perf_hostname_hint">El nombre que Steam ve para este dispositivo. En blanco restaura %1$s.</string>
<string name="perf_hostname_invalid">Solo letras, dígitos y guiones internos, hasta 63 caracteres.</string>
<string name="perf_desktop_as_user">El escritorio se ejecuta como usuario</string>
<string name="perf_desktop_as_user_hint">El escritorio, sus apps y sus terminales se ejecutan como el usuario común deck en lugar de root, para las apps que rechazan root. sudo sigue funcionando. Se aplica al próximo escritorio.</string>
<string name="perf_desktop_as_user_needs_native">Requiere Ejecutar sin proot.</string>
<string name="perf_phantom_warning">Android está configurado para cerrar esta sesión</string>
<string name="driver_installed">Instalado</string>
<string name="driver_available">Disponible para descargar</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Име на хоста</string>
<string name="perf_hostname_hint">Името, което Steam вижда за това устройство. Оставено празно възстановява %1$s.</string>
<string name="perf_hostname_invalid">Само букви, цифри и тирета по средата, до 63 знака.</string>
<string name="perf_desktop_as_user">Работният плот работи като потребител</string>
<string name="perf_desktop_as_user_hint">Работният плот, приложенията и терминалите му работят като обикновения потребител deck вместо root, за приложения, които отказват root. sudo продължава да работи. Важи за следващия работен плот.</string>
<string name="perf_desktop_as_user_needs_native">Изисква Работа без proot.</string>
<string name="perf_phantom_warning">Android е настроен да прекратява тази сесия</string>
<string name="driver_installed">Инсталиран</string>
<string name="driver_available">Налично за изтегляне</string>
-3
View File
@@ -650,9 +650,6 @@
<string name="perf_hostname">Název hostitele</string>
<string name="perf_hostname_hint">Název, který Steam vidí pro toto zařízení. Prázdné obnoví %1$s.</string>
<string name="perf_hostname_invalid">Pouze písmena, číslice a vnitřní pomlčky, až 63 znaků.</string>
<string name="perf_desktop_as_user">Plocha běží jako uživatel</string>
<string name="perf_desktop_as_user_hint">Plocha, její aplikace a terminály běží jako běžný uživatel deck místo root, kvůli aplikacím, které root odmítají. sudo dál funguje. Projeví se u příští plochy.</string>
<string name="perf_desktop_as_user_needs_native">Vyžaduje Spouštět bez proot.</string>
<string name="perf_phantom_warning">Android je nastaven tak, aby tuto relaci ukončil</string>
<string name="driver_installed">Nainstalováno</string>
<string name="driver_available">K dispozici ke stažení</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Værtsnavn</string>
<string name="perf_hostname_hint">Navnet Steam ser for denne enhed. Tomt gendanner %1$s.</string>
<string name="perf_hostname_invalid">Kun bogstaver, tal og bindestreger i midten, op til 63 tegn.</string>
<string name="perf_desktop_as_user">Skrivebordet kører som bruger</string>
<string name="perf_desktop_as_user_hint">Skrivebordet, dets apps og terminaler kører som den almindelige bruger deck i stedet for root, til apps der afviser root. sudo virker stadig. Gælder fra næste skrivebord.</string>
<string name="perf_desktop_as_user_needs_native">Kræver Kør uden proot.</string>
<string name="perf_phantom_warning">Android er sat til at lukke denne session</string>
<string name="driver_installed">Installeret</string>
<string name="driver_available">Tilgængelig til download</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Hostname</string>
<string name="perf_hostname_hint">Der Name, den Steam für dieses Gerät sieht. Leer lassen stellt %1$s wieder her.</string>
<string name="perf_hostname_invalid">Nur Buchstaben, Ziffern und innere Bindestriche, bis zu 63 Zeichen.</string>
<string name="perf_desktop_as_user">Desktop läuft als Benutzer</string>
<string name="perf_desktop_as_user_hint">Der Desktop, seine Apps und Terminals laufen als normaler Benutzer deck statt als root, für Apps, die root ablehnen. sudo funktioniert weiterhin. Gilt ab dem nächsten Desktop.</string>
<string name="perf_desktop_as_user_needs_native">Erfordert Ohne proot ausführen.</string>
<string name="perf_phantom_warning">Android ist so eingestellt, dass es diese Sitzung beendet</string>
<string name="driver_installed">Installiert</string>
<string name="driver_available">Zum Download verfügbar</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Όνομα κεντρικού υπολογιστή</string>
<string name="perf_hostname_hint">Το όνομα που βλέπει το Steam για αυτή τη συσκευή. Αν το αφήσετε κενό, επανέρχεται σε %1$s.</string>
<string name="perf_hostname_invalid">Μόνο γράμματα, ψηφία και εσωτερικές παύλες, έως 63 χαρακτήρες.</string>
<string name="perf_desktop_as_user">Η επιφάνεια εργασίας εκτελείται ως χρήστης</string>
<string name="perf_desktop_as_user_hint">Η επιφάνεια εργασίας, οι εφαρμογές και τα τερματικά της εκτελούνται ως ο απλός χρήστης deck αντί για root, για εφαρμογές που αρνούνται το root. Το sudo εξακολουθεί να λειτουργεί. Ισχύει από την επόμενη επιφάνεια εργασίας.</string>
<string name="perf_desktop_as_user_needs_native">Απαιτεί Εκτέλεση χωρίς proot.</string>
<string name="perf_phantom_warning">Το Android είναι ρυθμισμένο να διακόπτει αυτή τη συνεδρία</string>
<string name="driver_installed">Εγκατεστημένο</string>
<string name="driver_available">Διαθέσιμο για λήψη</string>
-3
View File
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nombre del host</string>
<string name="perf_hostname_hint">El nombre que Steam ve para este dispositivo. En blanco restaura %1$s.</string>
<string name="perf_hostname_invalid">Solo letras, dígitos y guiones internos, hasta 63 caracteres.</string>
<string name="perf_desktop_as_user">El escritorio se ejecuta como usuario</string>
<string name="perf_desktop_as_user_hint">El escritorio, sus apps y sus terminales se ejecutan como el usuario normal deck en lugar de root, para las apps que rechazan root. sudo sigue funcionando. Se aplica al próximo escritorio.</string>
<string name="perf_desktop_as_user_needs_native">Requiere Ejecutar sin proot.</string>
<string name="perf_phantom_warning">Android está configurado para cerrar esta sesión</string>
<string name="driver_installed">Instalado</string>
<string name="driver_available">Disponible para descargar</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Isäntänimi</string>
<string name="perf_hostname_hint">Nimi, jonka Steam näkee tälle laitteelle. Tyhjä palauttaa arvon %1$s.</string>
<string name="perf_hostname_invalid">Vain kirjaimia, numeroita ja sisäisiä yhdysmerkkejä, enintään 63 merkkiä.</string>
<string name="perf_desktop_as_user">Työpöytä toimii käyttäjänä</string>
<string name="perf_desktop_as_user_hint">Työpöytä, sen sovellukset ja päätteet toimivat tavallisena käyttäjänä deck rootin sijaan, rootin torjuvia sovelluksia varten. sudo toimii edelleen. Koskee seuraavaa työpöytää.</string>
<string name="perf_desktop_as_user_needs_native">Vaatii Suorita ilman prootia.</string>
<string name="perf_phantom_warning">Android on asetettu lopettamaan tämä istunto</string>
<string name="driver_installed">Asennettu</string>
<string name="driver_available">Ladattavissa</string>
-3
View File
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nom d\'hôte</string>
<string name="perf_hostname_hint">Le nom sous lequel Steam voit cet appareil. Laisser vide pour restaurer %1$s.</string>
<string name="perf_hostname_invalid">Ne peut contenir que des lettres, des chiffres et des tirets au milieu, jusqu\'à 63 caractères.</string>
<string name="perf_desktop_as_user">Le bureau s’exécute en tant qu’utilisateur</string>
<string name="perf_desktop_as_user_hint">Le bureau, ses applications et ses terminaux s’exécutent en tant qu’utilisateur ordinaire deck au lieu de root, pour les applications qui refusent root. sudo fonctionne toujours. S’applique au prochain bureau.</string>
<string name="perf_desktop_as_user_needs_native">Nécessite Exécuter sans proot.</string>
<string name="perf_phantom_warning">Android est configuré pour terminer cette session</string>
<string name="driver_installed">Installé</string>
<string name="driver_available">Téléchargeable</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">होस्ट नाम</string>
<string name="perf_hostname_hint">वह नाम जो Steam इस डिवाइस के लिए देखता है। खाली छोड़ने पर %1$s वापस आ जाता है।</string>
<string name="perf_hostname_invalid">सिर्फ़ अक्षर, अंक और बीच के हाइफ़न, 63 वर्णों तक।</string>
<string name="perf_desktop_as_user">डेस्कटॉप उपयोगकर्ता के रूप में चलता है</string>
<string name="perf_desktop_as_user_hint">डेस्कटॉप, उसके ऐप और टर्मिनल root के बजाय सामान्य उपयोगकर्ता deck के रूप में चलते हैं, उन ऐप के लिए जो root को अस्वीकार करते हैं। sudo फिर भी काम करता है। अगले डेस्कटॉप पर लागू होता है।</string>
<string name="perf_desktop_as_user_needs_native">proot के बिना चलाएँ आवश्यक है।</string>
<string name="perf_phantom_warning">Android इस सेशन को बंद करने के लिए सेट है</string>
<string name="driver_installed">इंस्टॉल है</string>
<string name="driver_available">डाउनलोड के लिए उपलब्ध</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Hosztnév</string>
<string name="perf_hostname_hint">A név, amelyet a Steam ehhez az eszközhöz lát. Üresen hagyva visszaállítja: %1$s.</string>
<string name="perf_hostname_invalid">Csak betűk, számok és belső kötőjelek, legfeljebb 63 karakter.</string>
<string name="perf_desktop_as_user">Az asztal felhasználóként fut</string>
<string name="perf_desktop_as_user_hint">Az asztal, az alkalmazásai és a termináljai root helyett a deck nevű átlagos felhasználóként futnak, a root-ot elutasító alkalmazások miatt. A sudo továbbra is működik. A következő asztaltól érvényes.</string>
<string name="perf_desktop_as_user_needs_native">A Futtatás proot nélkül szükséges hozzá.</string>
<string name="perf_phantom_warning">Az Android be van állítva, hogy kilője ezt a munkamenetet</string>
<string name="driver_installed">Telepítve</string>
<string name="driver_available">Letölthető</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">Nama host</string>
<string name="perf_hostname_hint">Nama yang dilihat Steam untuk perangkat ini. Kosongkan untuk memulihkan %1$s.</string>
<string name="perf_hostname_invalid">Hanya huruf, angka, dan tanda hubung di tengah, hingga 63 karakter.</string>
<string name="perf_desktop_as_user">Desktop berjalan sebagai pengguna</string>
<string name="perf_desktop_as_user_hint">Desktop, aplikasi, dan terminalnya berjalan sebagai pengguna biasa deck, bukan root, untuk aplikasi yang menolak root. sudo tetap berfungsi. Berlaku untuk desktop berikutnya.</string>
<string name="perf_desktop_as_user_needs_native">Memerlukan Jalankan tanpa proot.</string>
<string name="perf_phantom_warning">Android diatur untuk menghentikan sesi ini</string>
<string name="driver_installed">Terinstal</string>
<string name="driver_available">Tersedia untuk diunduh</string>
-3
View File
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nome host</string>
<string name="perf_hostname_hint">Il nome con cui Steam vede questo dispositivo. Se vuoto, torna a %1$s.</string>
<string name="perf_hostname_invalid">Solo lettere, cifre e trattini interni, fino a 63 caratteri.</string>
<string name="perf_desktop_as_user">Il desktop viene eseguito come utente</string>
<string name="perf_desktop_as_user_hint">Il desktop, le sue app e i suoi terminali vengono eseguiti come utente normale deck invece che come root, per le app che rifiutano root. sudo funziona comunque. Si applica al prossimo desktop.</string>
<string name="perf_desktop_as_user_needs_native">Richiede Esegui senza proot.</string>
<string name="perf_phantom_warning">Android è impostato per terminare questa sessione</string>
<string name="driver_installed">Installati</string>
<string name="driver_available">Disponibili per il download</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">ホスト名</string>
<string name="perf_hostname_hint">Steamがこのデバイスを認識する名前。空にすると%1$sに戻ります。</string>
<string name="perf_hostname_invalid">英数字と中間のハイフンのみ使用でき、最大63文字です。</string>
<string name="perf_desktop_as_user">デスクトップをユーザーとして実行</string>
<string name="perf_desktop_as_user_hint">デスクトップとそのアプリやターミナルを root ではなく一般ユーザー deck として実行します。root を拒否するアプリ向けです。sudo は引き続き使えます。次回のデスクトップから適用されます。</string>
<string name="perf_desktop_as_user_needs_native">proot なしで実行が必要です。</string>
<string name="perf_phantom_warning">Androidがこのセッションを終了するように設定されています</string>
<string name="driver_installed">インストール済み</string>
<string name="driver_available">ダウンロード可能</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">호스트 이름</string>
<string name="perf_hostname_hint">Steam이 이 기기를 인식하는 이름입니다. 비워 두면 %1$s(으)로 복원됩니다.</string>
<string name="perf_hostname_invalid">영문, 숫자 및 중간 하이픈만 사용할 수 있으며 최대 63자입니다.</string>
<string name="perf_desktop_as_user">데스크톱을 사용자로 실행</string>
<string name="perf_desktop_as_user_hint">데스크톱과 앱, 터미널이 root 대신 일반 사용자 deck으로 실행됩니다. root를 거부하는 앱을 위한 설정입니다. sudo는 계속 사용할 수 있습니다. 다음 데스크톱부터 적용됩니다.</string>
<string name="perf_desktop_as_user_needs_native">proot 없이 실행이 필요합니다.</string>
<string name="perf_phantom_warning">Android가 이 세션을 종료하도록 설정했습니다</string>
<string name="driver_installed">설치됨</string>
<string name="driver_available">다운로드 가능</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">Nama hos</string>
<string name="perf_hostname_hint">Nama yang dilihat Steam untuk peranti ini. Kosongkan untuk memulihkan %1$s.</string>
<string name="perf_hostname_invalid">Huruf, digit dan tanda sempang dalaman sahaja, sehingga 63 aksara.</string>
<string name="perf_desktop_as_user">Desktop berjalan sebagai pengguna</string>
<string name="perf_desktop_as_user_hint">Desktop, aplnya dan terminalnya berjalan sebagai pengguna biasa deck dan bukan root, untuk apl yang menolak root. sudo masih berfungsi. Berkuat kuasa pada desktop seterusnya.</string>
<string name="perf_desktop_as_user_needs_native">Memerlukan Jalankan tanpa proot.</string>
<string name="perf_phantom_warning">Android ditetapkan untuk menamatkan sesi ini</string>
<string name="driver_installed">Dipasang</string>
<string name="driver_available">Tersedia untuk dimuat turun</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Vertsnavn</string>
<string name="perf_hostname_hint">Navnet Steam ser for denne enheten. Tomt gjenoppretter %1$s.</string>
<string name="perf_hostname_invalid">Bare bokstaver, tall og bindestreker inni navnet, opptil 63 tegn.</string>
<string name="perf_desktop_as_user">Skrivebordet kjører som bruker</string>
<string name="perf_desktop_as_user_hint">Skrivebordet, appene og terminalene kjører som den vanlige brukeren deck i stedet for root, for apper som avviser root. sudo virker fortsatt. Gjelder fra neste skrivebord.</string>
<string name="perf_desktop_as_user_needs_native">Krever Kjør uten proot.</string>
<string name="perf_phantom_warning">Android er satt til å avslutte denne sesjonen</string>
<string name="driver_installed">Installert</string>
<string name="driver_available">Tilgjengelig for nedlasting</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Hostnaam</string>
<string name="perf_hostname_hint">De naam die Steam voor dit apparaat ziet. Leeg herstelt %1$s.</string>
<string name="perf_hostname_invalid">Alleen letters, cijfers en koppeltekens binnen de naam, tot 63 tekens.</string>
<string name="perf_desktop_as_user">Bureaublad draait als gebruiker</string>
<string name="perf_desktop_as_user_hint">Het bureaublad, de apps en terminals draaien als de gewone gebruiker deck in plaats van root, voor apps die root weigeren. sudo werkt nog steeds. Geldt vanaf het volgende bureaublad.</string>
<string name="perf_desktop_as_user_needs_native">Vereist Uitvoeren zonder proot.</string>
<string name="perf_phantom_warning">Android is ingesteld om deze sessie te sluiten</string>
<string name="driver_installed">Geïnstalleerd</string>
<string name="driver_available">Beschikbaar om te downloaden</string>
-3
View File
@@ -650,9 +650,6 @@
<string name="perf_hostname">Nazwa hosta</string>
<string name="perf_hostname_hint">Nazwa tego urządzenia widoczna dla Steam. Puste pole przywraca %1$s.</string>
<string name="perf_hostname_invalid">Tylko litery, cyfry i łączniki w środku, do 63 znaków.</string>
<string name="perf_desktop_as_user">Pulpit działa jako użytkownik</string>
<string name="perf_desktop_as_user_hint">Pulpit, jego aplikacje i terminale działają jako zwykły użytkownik deck zamiast root, dla aplikacji, które odrzucają root. sudo nadal działa. Obowiązuje od następnego pulpitu.</string>
<string name="perf_desktop_as_user_needs_native">Wymaga Uruchamiaj bez proot.</string>
<string name="perf_phantom_warning">Android jest ustawiony tak, że zamknie tę sesję</string>
<string name="driver_installed">Zainstalowane</string>
<string name="driver_available">Do pobrania</string>
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nome do anfitrião</string>
<string name="perf_hostname_hint">O nome com que o Steam vê este dispositivo. Em branco, repõe %1$s.</string>
<string name="perf_hostname_invalid">Apenas letras, algarismos e hífenes interiores, até 63 carateres.</string>
<string name="perf_desktop_as_user">O ambiente de trabalho corre como utilizador</string>
<string name="perf_desktop_as_user_hint">O ambiente de trabalho, as suas apps e terminais correm como o utilizador comum deck em vez de root, para apps que recusam root. O sudo continua a funcionar. Aplica-se ao próximo ambiente de trabalho.</string>
<string name="perf_desktop_as_user_needs_native">Requer Executar sem proot.</string>
<string name="perf_phantom_warning">O Android está configurado para terminar esta sessão</string>
<string name="driver_installed">Instalado</string>
<string name="driver_available">Disponível para transferir</string>
-3
View File
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nome do host</string>
<string name="perf_hostname_hint">O nome que a Steam vê para este dispositivo. Em branco, volta a ser %1$s.</string>
<string name="perf_hostname_invalid">Só letras, dígitos e hifens internos, até 63 caracteres.</string>
<string name="perf_desktop_as_user">A área de trabalho roda como usuário</string>
<string name="perf_desktop_as_user_hint">A área de trabalho, seus apps e terminais rodam como o usuário comum deck em vez de root, para apps que recusam root. O sudo continua funcionando. Vale a partir da próxima área de trabalho.</string>
<string name="perf_desktop_as_user_needs_native">Requer Executar sem proot.</string>
<string name="perf_phantom_warning">O Android está configurado para encerrar esta sessão</string>
<string name="driver_installed">Instalados</string>
<string name="driver_available">Disponíveis para download</string>
-3
View File
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nume de host</string>
<string name="perf_hostname_hint">Numele pe care Steam îl vede pentru acest dispozitiv. Gol restaurează %1$s.</string>
<string name="perf_hostname_invalid">Doar litere, cifre și liniuțe interioare, până la 63 de caractere.</string>
<string name="perf_desktop_as_user">Desktopul rulează ca utilizator</string>
<string name="perf_desktop_as_user_hint">Desktopul, aplicațiile și terminalele sale rulează ca utilizatorul obișnuit deck în loc de root, pentru aplicațiile care refuză root. sudo funcționează în continuare. Se aplică la următorul desktop.</string>
<string name="perf_desktop_as_user_needs_native">Necesită Rulează fără proot.</string>
<string name="perf_phantom_warning">Android este setat să închidă această sesiune</string>
<string name="driver_installed">Instalat</string>
<string name="driver_available">Disponibil pentru descărcare</string>
-3
View File
@@ -650,9 +650,6 @@
<string name="perf_hostname">Имя хоста</string>
<string name="perf_hostname_hint">Имя, под которым Steam видит это устройство. Оставьте пустым, чтобы вернуть %1$s.</string>
<string name="perf_hostname_invalid">Только буквы, цифры и дефисы посередине, до 63 символов.</string>
<string name="perf_desktop_as_user">Рабочий стол от имени пользователя</string>
<string name="perf_desktop_as_user_hint">Рабочий стол, его приложения и терминалы работают от имени обычного пользователя deck вместо root — для приложений, которые отказываются работать от root. sudo по-прежнему работает. Применяется к следующему запуску рабочего стола.</string>
<string name="perf_desktop_as_user_needs_native">Требуется «Запуск без proot».</string>
<string name="perf_phantom_warning">Android настроен на завершение этой сессии</string>
<string name="driver_installed">Установлен</string>
<string name="driver_available">Доступен для скачивания</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Värdnamn</string>
<string name="perf_hostname_hint">Namnet Steam ser för den här enheten. Lämna tomt för att återställa till %1$s.</string>
<string name="perf_hostname_invalid">Endast bokstäver, siffror och bindestreck inuti, upp till 63 tecken.</string>
<string name="perf_desktop_as_user">Skrivbordet körs som användare</string>
<string name="perf_desktop_as_user_hint">Skrivbordet, dess appar och terminaler körs som den vanliga användaren deck i stället för root, för appar som vägrar root. sudo fungerar fortfarande. Gäller från nästa skrivbord.</string>
<string name="perf_desktop_as_user_needs_native">Kräver Kör utan proot.</string>
<string name="perf_phantom_warning">Android är inställt på att avsluta den här sessionen</string>
<string name="driver_installed">Installerad</string>
<string name="driver_available">Tillgänglig att ladda ned</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">ชื่อโฮสต์</string>
<string name="perf_hostname_hint">ชื่อที่ Steam มองเห็นสำหรับอุปกรณ์นี้ เว้นว่างไว้เพื่อคืนค่าเป็น %1$s</string>
<string name="perf_hostname_invalid">ใช้ได้เฉพาะตัวอักษร ตัวเลข และยัติภังค์ตรงกลาง ไม่เกิน 63 ตัวอักษร</string>
<string name="perf_desktop_as_user">เดสก์ท็อปทำงานในฐานะผู้ใช้</string>
<string name="perf_desktop_as_user_hint">เดสก์ท็อป แอป และเทอร์มินัลจะทำงานในฐานะผู้ใช้ทั่วไป deck แทน root สำหรับแอปที่ไม่ยอมทำงานด้วย root sudo ยังใช้งานได้ มีผลกับเดสก์ท็อปครั้งถัดไป</string>
<string name="perf_desktop_as_user_needs_native">ต้องเปิด เรียกใช้โดยไม่มี proot</string>
<string name="perf_phantom_warning">Android ถูกตั้งให้ปิดเซสชันนี้</string>
<string name="driver_installed">ติดตั้งแล้ว</string>
<string name="driver_available">พร้อมดาวน์โหลด</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Ana bilgisayar adı</string>
<string name="perf_hostname_hint">Steam\'in bu cihaz için gördüğü ad. Boş bırakılırsa %1$s geri yüklenir.</string>
<string name="perf_hostname_invalid">Yalnızca harf, rakam ve arada kısa çizgi; en fazla 63 karakter.</string>
<string name="perf_desktop_as_user">Masaüstü kullanıcı olarak çalışır</string>
<string name="perf_desktop_as_user_hint">Masaüstü, uygulamaları ve terminalleri root yerine sıradan kullanıcı deck olarak çalışır; root’u reddeden uygulamalar içindir. sudo çalışmaya devam eder. Bir sonraki masaüstünde geçerli olur.</string>
<string name="perf_desktop_as_user_needs_native">proot olmadan çalıştır gerekir.</string>
<string name="perf_phantom_warning">Android bu oturumu sonlandıracak şekilde ayarlı</string>
<string name="driver_installed">Yüklü</string>
<string name="driver_available">İndirilebilir</string>
-3
View File
@@ -650,9 +650,6 @@
<string name="perf_hostname">Ім’я хоста</string>
<string name="perf_hostname_hint">Ім’я, яке Steam бачить для цього пристрою. Порожнє значення відновлює %1$s.</string>
<string name="perf_hostname_invalid">Лише літери, цифри та дефіси всередині, до 63 символів.</string>
<string name="perf_desktop_as_user">Робочий стіл від імені користувача</string>
<string name="perf_desktop_as_user_hint">Робочий стіл, його застосунки й термінали працюють від імені звичайного користувача deck замість root — для застосунків, які відмовляються працювати від root. sudo і далі працює. Застосовується до наступного запуску робочого столу.</string>
<string name="perf_desktop_as_user_needs_native">Потрібен «Запуск без proot».</string>
<string name="perf_phantom_warning">Android налаштовано завершувати цей сеанс</string>
<string name="driver_installed">Встановлено</string>
<string name="driver_available">Доступно для завантаження</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">Tên máy chủ</string>
<string name="perf_hostname_hint">Tên mà Steam thấy cho thiết bị này. Để trống để khôi phục %1$s.</string>
<string name="perf_hostname_invalid">Chỉ chữ, số và gạch ngang ở giữa, tối đa 63 ký tự.</string>
<string name="perf_desktop_as_user">Màn hình nền chạy dưới dạng người dùng</string>
<string name="perf_desktop_as_user_hint">Màn hình nền, các ứng dụng và terminal của nó chạy dưới người dùng thường deck thay vì root, cho các ứng dụng từ chối root. sudo vẫn hoạt động. Áp dụng cho lần mở màn hình nền tiếp theo.</string>
<string name="perf_desktop_as_user_needs_native">Cần bật Chạy không cần proot.</string>
<string name="perf_phantom_warning">Android được đặt để tắt phiên này</string>
<string name="driver_installed">Đã cài</string>
<string name="driver_available">Có thể tải</string>
@@ -644,9 +644,6 @@
<string name="perf_hostname">主机名</string>
<string name="perf_hostname_hint">Steam 看到的本设备名称。留空恢复为 %1$s。</string>
<string name="perf_hostname_invalid">仅限字母、数字,连字符只能位于中间,最多 63 个字符。</string>
<string name="perf_desktop_as_user">桌面以普通用户运行</string>
<string name="perf_desktop_as_user_hint">桌面及其应用和终端以普通用户 deck 而非 root 运行,适用于拒绝以 root 运行的应用。sudo 仍可使用。下次启动桌面时生效。</string>
<string name="perf_desktop_as_user_needs_native">需要开启“不使用 proot 运行”。</string>
<string name="perf_phantom_warning">Android 将会终止此会话</string>
<string name="driver_installed">已安装</string>
<string name="driver_available">可下载</string>
@@ -644,9 +644,6 @@
<string name="perf_hostname">主機名稱</string>
<string name="perf_hostname_hint">Steam 看到的此裝置名稱。留空則還原為 %1$s。</string>
<string name="perf_hostname_invalid">只可使用字母、數字和中間的連字號,最多 63 個字元。</string>
<string name="perf_desktop_as_user">桌面以普通用戶執行</string>
<string name="perf_desktop_as_user_hint">桌面及其應用程式和終端機會以普通用戶 deck 而非 root 執行,適用於拒絕以 root 執行的應用程式。sudo 仍可使用。下次開啟桌面時生效。</string>
<string name="perf_desktop_as_user_needs_native">需要開啟「不使用 proot 執行」。</string>
<string name="perf_phantom_warning">Android 已設定為終止此會話</string>
<string name="driver_installed">已安裝</string>
<string name="driver_available">可供下載</string>
@@ -644,9 +644,6 @@
<string name="perf_hostname">主機名稱</string>
<string name="perf_hostname_hint">Steam 看到的此裝置名稱。留空可還原為 %1$s。</string>
<string name="perf_hostname_invalid">只能包含字母、數字和中間的連字號,最多 63 個字元。</string>
<string name="perf_desktop_as_user">桌面以一般使用者執行</string>
<string name="perf_desktop_as_user_hint">桌面及其應用程式和終端機會以一般使用者 deck 而非 root 執行,適用於拒絕以 root 執行的應用程式。sudo 仍可使用。下次開啟桌面時生效。</string>
<string name="perf_desktop_as_user_needs_native">需要開啟「不使用 proot 執行」。</string>
<string name="perf_phantom_warning">Android 已設定為結束此工作階段</string>
<string name="driver_installed">已安裝</string>
<string name="driver_available">可下載</string>
+85 -19
View File
@@ -678,9 +678,6 @@
<string name="perf_hostname">Host name</string>
<string name="perf_hostname_hint">The name Steam sees for this device. Blank restores %1$s.</string>
<string name="perf_hostname_invalid">Letters, digits and inner hyphens only, up to 63 characters.</string>
<string name="perf_desktop_as_user">Desktop runs as a user</string>
<string name="perf_desktop_as_user_hint">The desktop, its apps and its terminals run as the ordinary user deck instead of root, for apps that refuse root. sudo still works. Applies to the next desktop.</string>
<string name="perf_desktop_as_user_needs_native">Needs Run without proot.</string>
<string name="perf_phantom_warning">Android is set to kill this session</string>
<string name="driver_installed">Installed</string>
<string name="driver_available">Available to download</string>
@@ -710,22 +707,7 @@
<string name="drawer_next_page">Next page</string>
<string name="drawer_manage_pages">Arrange pages</string>
<string name="drawer_page_more">More</string>
<string name="drawer_page_performance">Performance</string>
<string name="drawer_page_game">Game</string>
<string name="drawer_page_vr">VR &amp; glasses</string>
<string name="drawer_section_pacing">Frame pacing</string>
<string name="drawer_section_mouse">Mouse</string>
<string name="drawer_section_keyboard_layout">Keyboard layout</string>
<string name="drawer_section_input">Input profile</string>
<string name="drawer_section_compat">Compatibility</string>
<string name="drawer_section_tuning">Fine tuning</string>
<string name="drawer_tag_controller">controller connected</string>
<string name="drawer_tag_no_controller">no controller</string>
<string name="drawer_tag_running">running</string>
<string name="drawer_tag_custom">custom look</string>
<string name="drawer_tag_attached">attached</string>
<string name="drawer_tag_downloading">downloading</string>
<string name="drawer_pause_game">Pause game</string> <string name="drawer_more_back">Back to %1$s</string>
<string name="drawer_more_back">Back to %1$s</string>
<string name="drawer_more_empty">Nothing is kept here. Arrange pages and move one below the More row.</string>
<string name="drawer_pages_reset">Reset</string>
<string name="drawer_pages_done">Done</string>
@@ -4423,6 +4405,90 @@
<string name="decky_release_channel">Release channel</string>
<string name="rail_decky">Decky</string>
<string name="rail_boot_movies">Boot movies</string>
<string name="rail_recomps">Recomps</string>
<string name="recomps_filter_owned">You own the game</string>
<string name="recomps_filter_native">Runs natively</string>
<string name="recomps_filter_update">Update available</string>
<string name="recomps_filter_no_setup">No setup steps</string>
<string name="recomps_filter_show">Show</string>
<string name="recomps_filter_builds">Has a build for</string>
<string name="recomps_has_linux_arm64">Linux ARM64</string>
<string name="recomps_has_linux_x64">Linux x86-64</string>
<string name="recomps_has_windows">Windows</string>
<string name="recomps_has_android">Android</string>
<string name="recomps_build_installed">Installed</string>
<string name="recomps_build_installed_arm">Installed as its ARM64 file</string>
<string name="recomps_builds_hint">Pick a build to install that one.</string>
<string name="recomps_install_instead">Install %1$s instead</string>
<string name="recomps_clear_filters">Clear all</string>
<string name="recomps_sort_best">Best for you</string>
<string name="recomps_sort_popular">Most popular</string>
<string name="recomps_sort_updated">Recently updated</string>
<string name="recomps_sort_listed">Newly listed</string>
<string name="recomps_sort_title">A–Z</string>
<string name="recomps_runs_native">Native</string>
<string name="recomps_runs_android">Android</string>
<string name="recomps_runs_fex">FEX</string>
<string name="recomps_runs_proton">Proton</string>
<string name="recomps_installing">Installing</string>
<string name="recomps_section_needs">What it needs</string>
<string name="recomps_section_builds">Builds</string>
<string name="recomps_section_about">About</string>
<string name="recomps_needs_nothing">No game files needed</string>
<string name="recomps_needs_file">Looks for %1$s</string>
<string name="recomps_every_system">Every system</string>
<string name="recomps_filter_installed">Installed</string>
<string name="recomps_empty">The recomp list couldn\'t be loaded.</string>
<string name="recomps_none_here">Nothing matches these filters.</string>
<string name="recomps_kind_recomp">%1$s recomp</string>
<string name="recomps_kind_port">%1$s port</string>
<string name="recomps_build_linux_arm64">Linux ARM64 · native</string>
<string name="recomps_build_linux_x64">Linux x86-64 · FEX</string>
<string name="recomps_build_windows_x64">Windows · Proton</string>
<string name="recomps_build_none">No build DroidDeck can run</string>
<string name="recomps_data_found">Installed on %1$s</string>
<string name="recomps_data_found_checked">Installed on %1$s · files checked</string>
<string name="recomps_data_found_by_name">Installed on %1$s · matched by name</string>
<string name="recomps_data_missing_file">Installed on %1$s, but %2$s is missing</string>
<string name="recomps_data_wrong_version">Installed on %1$s, but %2$s is a different version</string>
<string name="recomps_data_owned">You own it on %1$s. Install it first</string>
<string name="recomps_data_bring">Needs your own %1$s</string>
<string name="recomps_data_folder">Game folder: %1$s</string>
<string name="recomps_install">Install</string>
<string name="recomps_install_build">Install %1$s</string>
<string name="recomps_play">Play</string>
<string name="recomps_open_games">Open in Games</string>
<string name="recomps_update">Update to %1$s</string>
<string name="recomps_remove">Remove</string>
<string name="recomps_install_game">Install game</string>
<string name="recomps_project">Project page</string>
<string name="recomps_installed">%1$s installed</string>
<string name="recomps_removed">%1$s removed</string>
<string name="recomps_no_build">No release of %1$s has a build DroidDeck can run</string>
<string name="recomps_unpacking">Unpacking %1$s</string>
<string name="recomps_unpack_failed">Unpacking failed (exit %1$d)</string>
<string name="recomps_entry_missing">The download has no %1$s</string>
<string name="recomps_android_started">%1$s downloaded. Confirm the install.</string>
<string name="recomps_apk_wrong_cpu">This Android build only has code for %1$s, and this device needs %2$s. Pick another build.</string>
<string name="recomps_apk_failed_named">%1$s didn\'t install: %2$s</string>
<string name="recomps_apk_fail_cpu">it has no code for this device\'s processor (%1$s). Pick another build.</string>
<string name="recomps_apk_fail_conflict">another copy of this app, signed by someone else, is installed. Remove it first.</string>
<string name="recomps_apk_fail_downgrade">a newer version is already installed.</string>
<string name="recomps_apk_fail_storage">there isn\'t enough free space.</string>
<string name="recomps_apk_fail_cancelled">the install was cancelled.</string>
<string name="recomps_apk_fail_blocked">Android blocked the install.</string>
<string name="recomps_apk_fail_invalid">the APK is damaged or isn\'t a valid app.</string>
<string name="recomps_apk_fail_other">Android said %1$s.</string>
<string name="recomps_launch_missing">This recomp\'s files are gone. Install it again from Recomps.</string>
<string name="recomps_not_for_device">Not for this device</string>
<string name="recomps_apk_mismatch">The APK isn\'t the app the catalog lists, so it wasn\'t installed</string>
<string name="recomps_allow_installs">Allow DroidDeck to install apps, then press Install again</string>
<string name="recomps_build_android">Android app</string>
<string name="recomps_search">Search recomps</string>
<string name="recomps_setup">Needs setup first</string>
<string name="recomps_via">via %1$s</string>
<string name="recomps_credits">This list is the Decomp Buddy catalog (decompbuddy.com, by Maddie at Tanooki Studios), the Recomp Launcher catalog (recomplauncher.com, by elripalda, Xarishark and contributors) and the Recompa catalog (recompa.app, by kalasyan), read from their sites. Each game\'s build comes from its own developers. It never downloads ROMs or game files.</string>
<string name="recomps_add_failed">The Windows build couldn\'t be added to your games</string>
<string name="decky_tab_installed">Installed · %1$d</string>
<string name="decky_tab_store">Store</string>
<string name="decky_tab_zip">From ZIP</string>
@@ -44,40 +44,6 @@ class ElfSeccompPatchTest {
}
}
@Test
fun terminalRequestsUseTheOnesAndroidAllowsOnAPseudoTerminal() {
// glibc 2.43's tcsetattr: TCSETS2 into x0, TCGETS2 into x1, with an unrelated instruction between
val data = elfWith(
0xd28a8560.toInt(), 0x910123e2.toInt(), 0xf2a80580.toInt(),
0xd28a8541.toInt(), 0x93407ea0.toInt(), 0xf2b00581.toInt(),
0x528a85a3.toInt(), 0x72a80583.toInt(),
)
assertEquals(3, ElfSeccompPatch.patch(data))
val b = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)
val nop = 0xd503201f.toInt()
assertEquals(0xd28a8040.toInt(), b.getInt(0x100)) // mov x0, #0x5402 (TCSETS)
assertEquals(nop, b.getInt(0x108))
assertEquals(0xd28a8021.toInt(), b.getInt(0x10c)) // mov x1, #0x5401 (TCGETS)
assertEquals(nop, b.getInt(0x114))
assertEquals(0x528a8083.toInt(), b.getInt(0x118)) // mov w3, #0x5404 (TCSETSF)
assertEquals(nop, b.getInt(0x11c))
assertEquals(0, ElfSeccompPatch.patch(data))
}
@Test
fun aLookalikeConstantIsLeftAlone() {
// 0x542a with another high half, and one whose high half goes to another register
val data = elfWith(0xd28a8541.toInt(), 0xf2a00021.toInt(), 0xd28a8541.toInt(), 0xf2b00582.toInt())
assertEquals(0, ElfSeccompPatch.patch(data))
}
@Test
fun aSiteWhoseRegisterIsReadBeforeTheHighHalfIsLeftAlone() {
// movz x1, #0x542a; add x2, x1, #1; movk x1, #0x802c, lsl #16; movk x2, #0x402c, lsl #16
val data = elfWith(0xd28a8541.toInt(), 0x91000422.toInt(), 0xf2b00581.toInt(), 0xf2a80582.toInt())
assertEquals(0, ElfSeccompPatch.patch(data))
}
@Test
fun otherSystemCallsAreLeftAlone() {
val svc = 0xd4000001.toInt()
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.content.pm.PackageInstaller
import androidx.test.core.app.ApplicationProvider
import com.droiddeck.launcher.frontend.Library
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class RecompShortcutsTest {
private val ctx = ApplicationProvider.getApplicationContext<Context>()
private fun install(dir: String, id: String, name: String, root: String = UserApps.GUEST_DIR): File =
File(LinuxRuntime.rootDir(ctx), root.removePrefix("/") + "/" + dir).apply {
mkdirs()
File(this, RecompInstaller.META_ID).writeText(id)
File(this, "name").writeText(name)
File(this, RecompInstaller.META_PLATFORM).writeText("linux-arm64")
}
@Test fun theShortcutIdIsSteamsCrcOfTheQuotedProgramAndName() {
val crc = java.util.zip.CRC32().apply { update("\"/opt/droiddeck-apps/zelda/play\"Zelda 64".toByteArray()) }.value or 0x80000000L
assertEquals(crc, RecompShortcuts.appId("/opt/droiddeck-apps/zelda/play", "Zelda 64"))
}
@Test fun eachLinuxRecompIsANativeShortcutToItsPlayScript() {
val zelda = install("zelda-64", "zelda64recomp", "Zelda 64: Recompiled")
install("quake", "ironwail", "Ironwail", AppImageManager.GUEST_DIR).also { File(it, "app").mkdirs(); File(it, "app/AppRun").writeText("x") }
File(zelda, "icon.png").writeText("png")
val listing = RecompShortcuts.listing(ctx).associateBy { it.getString("name") }
val z = listing.getValue("Zelda 64: Recompiled")
assertEquals("/opt/droiddeck-apps/zelda-64/play", z.getString("exe"))
assertTrue(z.getBoolean("native"))
assertEquals(RecompShortcuts.appId(z.getString("exe"), z.getString("name")), z.getLong("appid"))
assertEquals(File(zelda, "icon.png").absolutePath, z.getJSONObject("art").getString("icon"))
assertEquals("#!/bin/sh\nexec ${UserApps.SCRIPT_LAUNCHER} '/opt/droiddeck-apps/zelda-64' \"\$@\"\n", File(zelda, "play").readText())
assertTrue(File(zelda, "play").canExecute())
val quake = listing.getValue("Ironwail")
assertEquals("${AppImageManager.GUEST_DIR}/quake/play", quake.getString("exe"))
val play = File(LinuxRuntime.rootDir(ctx), AppImageManager.GUEST_DIR.removePrefix("/") + "/quake/play").readText()
assertTrue(play.contains(AppImageManager.LAUNCHER))
}
@Test fun recompsJoinTheLibraryUnderTheirOwnSource() {
install("banjo", "banjorecomp", "Banjo: Recompiled")
val g = RecompShortcuts.library(ctx) { _, _ -> 42L }.single { it.name == "Banjo: Recompiled" }
assertEquals(RecompShortcuts.SOURCE, g.source)
assertEquals("script:banjo", g.storeId)
assertEquals(42L, g.lastPlayed)
val appId = RecompShortcuts.appId("/opt/droiddeck-apps/banjo/play", "Banjo: Recompiled")
assertEquals((appId shl 32) or 0x02000000L, g.gameId)
}
@Test fun anApkWithoutCodeForTheDevicesCpuIsCaughtBeforeAndroidRefusesIt() {
val apk = File(ctx.cacheDir, "t.apk")
ZipOutputStream(apk.outputStream()).use { z ->
listOf("AndroidManifest.xml", "lib/armeabi-v7a/libmain.so", "lib/x86/libmain.so").forEach { z.putNextEntry(ZipEntry(it)); z.write(1); z.closeEntry() }
}
assertEquals(setOf("armeabi-v7a", "x86"), RecompAndroid.apkAbis(apk))
assertTrue(!RecompAndroid.fits(setOf("armeabi-v7a", "x86"), listOf("arm64-v8a")))
assertTrue(RecompAndroid.fits(setOf("armeabi-v7a", "arm64-v8a"), listOf("arm64-v8a")))
assertTrue(RecompAndroid.fits(emptySet(), listOf("arm64-v8a")))
}
@Test fun installFailuresSayWhatHappened() {
assertTrue(RecompAndroid.failure(ctx, PackageInstaller.STATUS_FAILURE, "INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries").contains("processor"))
assertTrue(RecompAndroid.failure(ctx, PackageInstaller.STATUS_FAILURE_CONFLICT, null).contains("signed by someone else"))
assertTrue(RecompAndroid.failure(ctx, PackageInstaller.STATUS_FAILURE_STORAGE, null).contains("space"))
assertTrue(RecompAndroid.failure(ctx, 99, "odd").contains("odd"))
}
}
@@ -0,0 +1,364 @@
package com.droiddeck.launcher.runtime
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.Store
import java.io.File
import java.util.concurrent.TimeUnit
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class RecompsTest {
@get:Rule val temporary = TemporaryFolder()
private val launcherFeed = JSONObject("""{"apps":[
{"id":"zelda64recomp","name":"Zelda 64: Recompiled","game":"The Legend of Zelda: Majora's Mask","origin":"n64",
"repo":"Zelda64Recomp/Zelda64Recomp","tag":"v1.2.2","released_at":"2025-08-27T00:58:35Z","downloads":415396,
"assets":{"windows":"Zelda64Recompiled-*-Windows.zip","linux":"Zelda64Recompiled-*-Linux-X64.zip","macos":"Z-*-macOS.zip"},
"files":{"windows":{"name":"Zelda64Recompiled-v1.2.2-Windows.zip","sha256":"${"a".repeat(64)}"}},
"needs":"Your own copy of The Legend of Zelda: Majora's Mask","boot":{"kind":"portable","start":"Zelda64Recompiled.exe"}},
{"id":"ironwail","name":"Ironwail","game":"Quake","origin":"pc","repo":"andrei-drexler/ironwail","tag":"v0.8.2","downloads":10,
"assets":{"linux":"ironwail-*-linux-x64.tar.gz","windows":"ironwail-*-win32.zip"},"boot":{"start_linux":"ironwail"},
"needs":"Your Quake id1 folder","about":{"igdb":333,"url":"https://www.igdb.com/games/quake"}},
{"id":"otherm","name":"Other M","origin":"wii","repo":"o/otherm","tag":"1.0","assets":{"windows":"OtherM.zip","linux":"OtherM-Flatpak.zip"},
"setup_required":true,"setup_steps":["Run setup.bat once.","Then play."]},
{"id":"gone","name":"Gone","repo":"o/gone","archived":true,"assets":{"windows":"g.zip"}},
{"id":"tool","name":"Tool","repo":"o/tool","boot":{"kind":"not-a-game"},"assets":{"windows":"t.zip"}},
{"id":"lab","name":"Lab","repo":"git.example/x/y","host":"gitlab","assets":{"windows":"l.zip"}}
]}""")
private val recompaFeed = JSONObject("""{"ports":[
{"id":"zelda","name":"Majora","upstream":"https://github.com/Zelda64Recomp/Zelda64Recomp","original_platform":"n64",
"requirements":{"abi":["arm64-v8a"],"min_sdk":24},"forks":[
{"repo":"x/Zelda-Android","name":"Zelda Android","package":"com.z.mm","signer_sha256":"${"b".repeat(64)}","downloads":9,
"release":{"tag":"a1","published_at":"p","asset":{"name":"z.apk","url":"https://h/z.apk","sha256":"${"c".repeat(64)}"}}},
{"repo":"x/unsigned","package":"com.z.other","downloads":99,"release":{"tag":"t","asset":{"name":"u.apk","url":"https://h/u.apk"}}}]},
{"id":"sm64","name":"SM64","upstream":"https://github.com/o/sm64","original_platform":"n64","type":"decomp",
"assets":[{"label":"SM64 ROM","accepted":[{"sha1":"9BEF1128717F958171A4AFAC3ED78EE2BB4E86CE"}],"instructions_md":"Pick `sm64.z64`.\n"}],
"forks":[{"repo":"y/sm64","package":"com.y.sm64","signer_sha256":"${"d".repeat(64)}",
"release":{"tag":"r2","asset":{"name":"sm64.apk","url":"https://h/s.apk","sha256":"${"e".repeat(64)}"}}}]},
{"id":"x86only","upstream":"https://github.com/o/x","requirements":{"abi":["x86_64"]},"forks":[]},
{"id":"recompa-app","upstream":"https://github.com/kalasyan/recompa","forks":[{"repo":"kalasyan/recompa","package":"io.github.kalasyan.recompa",
"signer_sha256":"${"f".repeat(64)}","release":{"tag":"v1","asset":{"name":"r.apk","url":"https://h/r.apk","sha256":"${"f".repeat(64)}"}}}]}
]}""")
private val merged by lazy { RecompCatalog.merge(RecompCatalog.fromRecompLauncher(launcherFeed), RecompCatalog.fromRecompa(recompaFeed)) }
private fun entry(id: String) = merged.first { it.id == id }
@Test fun recompLauncherAppsBecomeRunnableBuildsAndTheRestIsLeftOut() {
assertEquals(listOf("zelda64recomp", "ironwail", "otherm", "sm64"), merged.map { it.id })
val z = entry("zelda64recomp")
assertEquals("N64", z.origin)
assertEquals(setOf(RecompCatalog.Platform.LINUX_X64, RecompCatalog.Platform.WINDOWS_X64, RecompCatalog.Platform.ANDROID), z.builds.map { it.platform }.toSet())
val win = z.build(RecompCatalog.Platform.WINDOWS_X64)!!
assertEquals("Zelda64Recompiled.exe", win.entry)
assertEquals("a".repeat(64), win.sha256)
assertTrue(z.build(RecompCatalog.Platform.LINUX_X64)!!.asset.matches("Zelda64Recompiled-v1.2.2-Linux-X64.zip"))
assertNull(z.build(RecompCatalog.Platform.LINUX_X64)!!.file)
assertNull(entry("ironwail").build(RecompCatalog.Platform.WINDOWS_X64))
assertEquals("ironwail", entry("ironwail").build(RecompCatalog.Platform.LINUX_X64)!!.entry)
val m = entry("otherm")
assertEquals(listOf(RecompCatalog.Platform.WINDOWS_X64), m.builds.map { it.platform })
assertEquals("OtherM.zip", m.builds.single().file)
assertEquals("Run setup.bat once. Then play.", m.setup)
assertEquals("Wii", m.origin)
}
@Test fun recompaPortsAddSignedApksAndTheirRomNeeds() {
val z = entry("zelda64recomp")
assertEquals(listOf(RecompCatalog.RECOMP_LAUNCHER.id, RecompCatalog.RECOMPA.id), z.sources)
assertEquals(RecompCatalog.Platform.ANDROID, z.preferred()?.platform)
val apk = z.android!!
assertEquals("com.z.mm", apk.pkg)
assertEquals("b".repeat(64), apk.signer)
val pin = RecompInstaller.pinned(z, apk)!!
assertEquals("https://h/z.apk", pin.url)
assertEquals("a1", pin.tag)
assertEquals("c".repeat(64), pin.sha256)
val s = entry("sm64")
assertEquals(listOf(RecompCatalog.RECOMPA.id), s.sources)
assertEquals(RecompCatalog.DataKind.ROM, s.data.kind)
assertEquals(listOf("9bef1128717f958171a4afac3ed78ee2bb4e86ce"), s.data.sha1)
assertEquals("Pick sm64.z64.", s.data.note)
}
@Test fun aNamedReleaseFileDownloadsWithoutTheApi() {
val m = entry("otherm")
assertEquals("https://github.com/o/otherm/releases/download/1.0/OtherM.zip", RecompInstaller.pinned(m, m.builds.single())!!.url)
assertNull(RecompInstaller.pinned(entry("ironwail"), entry("ironwail").builds.single()))
}
@Test fun theNewestStableReleaseWithAMatchingAssetIsPicked() {
val body = """[
{"tag_name":"v3","draft":true,"assets":[{"name":"Game-Linux-ARM64.zip","browser_download_url":"https://d/3"}]},
{"tag_name":"v2-rc","prerelease":true,"assets":[{"name":"Game-Linux-ARM64.zip","browser_download_url":"https://d/2"}]},
{"tag_name":"v1","published_at":"2026-01-01T00:00:00Z","assets":[
{"name":"Game-Windows.zip","browser_download_url":"https://d/w"},
{"name":"Game-Linux-ARM64.zip","browser_download_url":"https://d/1","digest":"sha256:${"a".repeat(64)}"}]}
]"""
val stable = RecompInstaller.pickRelease(body, RecompCatalog.globRegex("Game-Linux-ARM64.zip"), prerelease = false)!!
assertEquals("v1", stable.tag)
assertEquals("a".repeat(64), stable.sha256)
assertNull(RecompInstaller.pickRelease(body, Regex("macOS"), prerelease = false))
}
@Test fun pcPortsMatchOwnedGamesByTitleAndConsoleRecompsNever() {
val steam = RecompData.Install(Store.STEAM, "2310", "Quake", temporary.newFolder("Quake"), "/root/.local/share/Steam/steamapps/common/Quake")
val found = RecompData.resolve(entry("ironwail"), RecompData.Inputs(listOf(steam), emptyList()))
assertEquals("/root/.local/share/Steam/steamapps/common/Quake", (found as RecompData.State.Found).guest)
val item = CatalogItem(Store.GOG, "1", "Quake", null)
assertTrue(RecompData.resolve(entry("ironwail"), RecompData.Inputs(emptyList(), listOf(RecompData.Owner(Store.GOG, "1", "Quake™ GOTY Edition", item)))) is RecompData.State.Owned)
assertTrue(RecompData.resolve(entry("ironwail"), RecompData.Inputs(emptyList(), listOf(RecompData.Owner(Store.GOG, "2", "Quake II", item)))) is RecompData.State.BringYourOwn)
val majora = RecompData.Install(Store.STEAM, "1", "The Legend of Zelda: Majora's Mask", temporary.root, "/x")
assertTrue(RecompData.resolve(entry("zelda64recomp"), RecompData.Inputs(listOf(majora), emptyList())) is RecompData.State.BringYourOwn)
}
@Test fun titlesFollowDecompBuddysRules() {
assertTrue(RecompData.sameGame("Fallout 2", "Fallout 2: A Post Nuclear Role Playing Game"))
assertTrue(RecompData.sameGame("The Elder Scrolls III: Morrowind", "The Elder Scrolls III: Morrowind® Game of the Year Edition"))
assertTrue(RecompData.sameGame("Civilization II", "Sid Meier's Civilization II"))
assertTrue(RecompData.sameGame("Diablo", "Diablo + Hellfire".replace(" + Hellfire", " Gold")))
assertTrue(!RecompData.sameGame("Fallout", "Fallout 2"))
assertTrue(!RecompData.sameGame("Quake", "Quake II"))
assertTrue(!RecompData.sameGame("", "Quake"))
}
private val decompBuddyFeed = JSONObject("""{"schema":1,"games":[
{"id":"github:diasurgical/devilutionx","slug":"diablo-pc","title":"Diablo","console":"PC (Windows)","repo":"diasurgical/DevilutionX",
"host":"github","repoUrl":"https://github.com/diasurgical/DevilutionX","iconUrl":"https://i/d.png","downloads":50,"updatedAt":"2026-11-01T00:00:00Z",
"platforms":["Windows","Linux","Linux (ARM)","Android"]},
{"id":"github:zelda64recomp/zelda64recomp","slug":"majoras-mask-n64","title":"Majora's Mask","console":"Nintendo 64","repo":"Zelda64Recomp/Zelda64Recomp","host":"github"},
{"id":"github:o/noplan","slug":"no-plan","title":"No Plan","console":"Xbox","repo":"o/noplan","host":"github"},
{"id":"gitlab:o/lab","slug":"lab","title":"Lab","console":"PC (Windows)","repo":"o/lab","host":"gitlab"}
]}""")
private val decompBuddyPlans = """{"updatedAt":"x","plans":{
"github:diasurgical/devilutionx":{"tag":"1.5.5","generatedAt":"g","targets":{
"linux":{"redirect_repo":null,"games":[{"game_title":"Diablo","console":"PC","build":{"method":"release","release_asset":"devilutionx-linux-x86_64.tar.xz",
"release_tag":"1.5.5","executable":"devilutionx","scanned":{"sha256":"${"1".repeat(64)}","size":1}},
"game_files":[{"label":"DIABDAT.MPQ from Diablo","expected_filename":"DIABDAT.MPQ","how_provided":"folder","kind":"game","accepted_formats":[".mpq"],
"expected_hashes":[{"algo":"MD5","value":"5D41402ABC4B2A76B9719D911017C592"},{"algo":"sha1","value":"not-a-hash"}],"expected_size":5}],
"first_run":["a"],"notes":[],"mods":{"supported":false}}]},
"windows":{"games":[{"game_title":"Diablo","build":{"method":"release","release_asset":"devilutionx-windows-x86_64.zip","release_tag":"1.5.5",
"executable":"bin\\devilutionx.exe","scanned":{"sha256":"${"2".repeat(64)}"}},"game_files":[]}]},
"android":{"games":[{"build":{"method":"release","release_asset":"devilutionx-android.apk","release_tag":"1.5.5","package_id":"org.diasurgical.devilutionx",
"scanned":{"sha256":"${"3".repeat(64)}"}},"game_files":[]}]},
"macos-arm64":{"games":[{"build":{"method":"release","release_asset":"d.dmg"}}]}}},
"github:zelda64recomp/zelda64recomp":{"tag":"v1.2.2","targets":{"windows":{"games":[{"build":{"method":"source","release_asset":"x.zip"}}]}}}
}}"""
@Test fun decompBuddyPlansStreamIntoBuildsWithTheirProgramChecksumAndNeededFile() {
val plans = DecompBuddyPlans.read(java.io.StringReader(decompBuddyPlans))
assertEquals(setOf("linux", "windows", "android"), plans.getValue("github:diasurgical/devilutionx").targets.keys)
val list = RecompCatalog.fromDecompBuddy(decompBuddyFeed, plans)
assertEquals(listOf("diablo-pc"), list.map { it.id })
val d = list.single()
assertEquals("PC", d.origin)
assertTrue(d.pc)
val linux = d.build(RecompCatalog.Platform.LINUX_X64)!!
assertEquals("devilutionx", linux.entry)
assertEquals("devilutionx-linux-x86_64.tar.xz", linux.file)
assertTrue(linux.mirrored)
assertEquals("devilutionx.exe", d.build(RecompCatalog.Platform.WINDOWS_X64)!!.entry)
assertEquals("org.diasurgical.devilutionx", d.android!!.pkg)
assertNull(d.android!!.signer)
assertEquals("DIABDAT.MPQ", d.data.file)
assertEquals("https://github.com/diasurgical/DevilutionX/releases/download/1.5.5/devilutionx-linux-x86_64.tar.xz", RecompInstaller.pinned(d, linux)!!.url)
assertEquals("https://files.decompbuddy.com/${"1".repeat(64)}/devilutionx-linux-x86_64.tar.xz", RecompCatalog.mirrorUrl("1".repeat(64), linux.file!!))
}
@Test fun decompBuddyComesFirstAndRecompaAddsItsSignerToTheSameApk() {
val plans = DecompBuddyPlans.read(java.io.StringReader(decompBuddyPlans))
val recompa = JSONObject("""{"ports":[{"id":"devilutionx","upstream":"https://github.com/diasurgical/devilutionX","forks":[{"repo":"diasurgical/devilutionX",
"package":"org.diasurgical.devilutionx","signer_sha256":"${"9".repeat(64)}","downloads":1,
"release":{"tag":"1.5.5","asset":{"name":"devilutionx-android.apk","url":"https://h/d.apk","sha256":"${"3".repeat(64)}"}}}]}]}""")
val all = RecompCatalog.merge(RecompCatalog.fromDecompBuddy(decompBuddyFeed, plans), RecompCatalog.fromRecompLauncher(launcherFeed), RecompCatalog.fromRecompa(recompa))
val d = all.first { it.id == "diablo-pc" }
assertEquals(listOf(RecompCatalog.DECOMP_BUDDY.id, RecompCatalog.RECOMPA.id), d.sources)
assertEquals("9".repeat(64), d.android!!.signer)
assertEquals("Diablo", d.name)
assertEquals(listOf("diablo-pc", "zelda64recomp", "ironwail", "otherm"), all.map { it.id })
}
@Test fun theBulkPassNeverHashesAndLeavesTheCheckOpen() {
val plans = DecompBuddyPlans.read(java.io.StringReader(decompBuddyPlans))
val d = RecompCatalog.fromDecompBuddy(decompBuddyFeed, plans).single()
val gog = temporary.newFolder("Diablo bulk")
File(gog, "diabdat.mpq").writeText("hello")
val install = RecompData.Install(Store.GOG, "1412601690", "Diablo", gog, "/g")
var hashed = 0
val bulk = RecompData.Inputs(listOf(install), emptyList(), hasher = { _, _ -> hashed++; null }, cachedOnly = true)
val found = RecompData.resolve(d, bulk) as RecompData.State.Found
assertTrue(!found.checked)
assertTrue(hashed > 0)
}
@Test fun theNeededFileFindsTheFolderInsideAStoreInstall() {
val plans = DecompBuddyPlans.read(java.io.StringReader(decompBuddyPlans))
val d = RecompCatalog.fromDecompBuddy(decompBuddyFeed, plans).single()
val gog = temporary.newFolder("Diablo GOG")
File(gog, "hellfire").mkdirs()
File(gog, "hellfire/diabdat.mpq").writeText("hello")
val install = RecompData.Install(Store.GOG, "1412601690", "Diablo + Hellfire".substringBefore(" +"), gog, "/root/Games/Stores/GOG/Diablo")
val found = RecompData.resolve(d, RecompData.Inputs(listOf(install), emptyList()))
found as RecompData.State.Found
assertEquals("/root/Games/Stores/GOG/Diablo/hellfire", found.guest)
assertTrue(found.checked)
File(gog, "hellfire/diabdat.mpq").writeText("jello")
val other = RecompData.resolve(d, RecompData.Inputs(listOf(install), emptyList()))
assertTrue((other as RecompData.State.Incomplete).wrongVersion)
File(gog, "hellfire/diabdat.mpq").delete()
val missing = RecompData.resolve(d, RecompData.Inputs(listOf(install), emptyList())) as RecompData.State.Incomplete
assertEquals("DIABDAT.MPQ", missing.file)
assertTrue(!missing.wrongVersion)
}
@Test fun catalogsGiveTheIgdbSlugTheNeededFileAndItsHashes() {
assertEquals("quake", entry("ironwail").igdb)
val plans = DecompBuddyPlans.read(java.io.StringReader(decompBuddyPlans))
val d = RecompCatalog.fromDecompBuddy(decompBuddyFeed, plans).single().data
assertEquals(listOf("md5" to "5d41402abc4b2a76b9719d911017c592"), d.hashes.map { it.algo to it.value })
assertEquals(5L, d.size)
val rl = RecompCatalog.fromRecompLauncher(JSONObject("""{"apps":[{"id":"f117","name":"F-117A","origin":"pc","repo":"o/f117","tag":"1",
"assets":{"windows":"f.zip"},"needs":"Your F-117A","launcher":{"inputs":[{"id":"game","label":"Your F-117A folder","check":{"file":"Data\\VGAME.EXE"}}]}}]}""")).single()
assertEquals("Data/VGAME.EXE", rl.data.file)
assertNull(RecompCatalog.safePath("../etc/passwd"))
assertNull(RecompCatalog.hash("sha1", "abc"))
}
@Test fun wikidataAndGogAnswersParseToStoreIds() {
val ids = RecompStoreIds.parseSparql("""{"results":{"bindings":[
{"igdb":{"value":"the-elder-scrolls-iii-morrowind"},"steam":{"value":"22320"},"gog":{"value":"game/the_elder_scrolls_iii_morrowind_goty_edition"},"epic":{"value":"morrowind-aa49c4"}},
{"igdb":{"value":"the-elder-scrolls-iii-morrowind"},"steam":{"value":"22330"}},
{"igdb":{"value":"diablo"},"gog":{"value":"game/diablo"}}]}}""")
val m = ids.getValue("the-elder-scrolls-iii-morrowind")
assertEquals(setOf("22320", "22330"), m.steam)
assertEquals(setOf("the_elder_scrolls_iii_morrowind_goty_edition"), m.gog)
assertEquals(setOf("morrowind-aa49c4"), m.epic)
assertTrue(ids.getValue("diablo").steam.isEmpty())
assertTrue("\"quake\"" in RecompStoreIds.sparql(listOf("quake", "bad\" } evil")))
assertTrue("evil" !in RecompStoreIds.sparql(listOf("quake", "bad\" } evil")))
assertEquals(mapOf("1440163901" to "the_elder_scrolls_iii_morrowind_goty_edition", "1412601690" to "diablo"),
RecompStoreIds.parseGogProducts("""[{"id":1440163901,"slug":"the_elder_scrolls_iii_morrowind_goty_edition"},{"id":1412601690,"slug":"diablo"}]"""))
}
@Test fun aKnownStoreIdIsMatchedExactlyAndATitleAloneIsNotEnoughThere() {
val quake = entry("ironwail")
val ids = mapOf("quake" to RecompStoreIds.Ids(setOf("2310"), setOf("quake_the_offering"), emptySet()))
fun state(vararg installs: RecompData.Install, owned: List<RecompData.Owner> = emptyList(), slugs: Map<String, String> = emptyMap()) =
RecompData.resolve(quake, RecompData.Inputs(installs.toList(), owned, ids, slugs))
val dir = temporary.newFolder("q")
val right = state(RecompData.Install(Store.STEAM, "2310", "Quake (Original)", dir, "/s/Quake"))
assertTrue((right as RecompData.State.Found).exact)
assertTrue(state(RecompData.Install(Store.STEAM, "9999", "Quake", dir, "/s/QuakeRemake")) is RecompData.State.BringYourOwn)
val gog = state(RecompData.Install(Store.GOG, "1", "Quake The Offering", dir, "/g/Quake"), slugs = mapOf("1" to "quake_the_offering"))
assertTrue((gog as RecompData.State.Found).exact)
val owned = state(owned = listOf(RecompData.Owner(Store.STEAM, "2310", "Something Else", null)))
assertTrue((owned as RecompData.State.Owned).exact)
val epicByName = state(RecompData.Install(Store.EPIC, "Quake", "Quake", dir, "/e/Quake"))
assertTrue(!(epicByName as RecompData.State.Found).exact)
}
@Test fun aNeededFileCanSitInASubfolderPath() {
val e = RecompCatalog.Entry("openmw", "OpenMW", "The Elder Scrolls III: Morrowind", "PC", "port", "o/openmw", "", "", null,
listOf(RecompCatalog.Build(RecompCatalog.Platform.LINUX_X64, Regex("x"))),
RecompCatalog.Data(RecompCatalog.DataKind.DUMP, "Morrowind", file = "Data Files/Morrowind.esm"), listOf("recomp-launcher"))
val root = temporary.newFolder("Morrowind")
File(root, "data files").mkdirs()
File(root, "data files/MORROWIND.ESM").writeText("x")
val install = RecompData.Install(Store.STEAM, "22320", "The Elder Scrolls III: Morrowind GOTY Edition", root, "/s/Morrowind")
val found = RecompData.resolve(e, RecompData.Inputs(listOf(install), emptyList())) as RecompData.State.Found
assertEquals("/s/Morrowind", found.guest)
assertTrue(found.checked && !found.exact)
}
@Test fun otherPortsOfAPcGameShareItsIgdbSlugOnlyWhenTheTitleIsUnambiguous() {
fun e(id: String, game: String, igdb: String?, origin: String = "PC") = RecompCatalog.Entry(id, id, game, origin, "port", "o/$id", "", "", null,
listOf(RecompCatalog.Build(RecompCatalog.Platform.LINUX_X64, Regex("x"))), RecompCatalog.Data(RecompCatalog.DataKind.NONE, ""), listOf("x"), igdb = igdb)
val out = RecompCatalog.shareIgdb(listOf(
e("ironwail", "Quake", "quake"), e("vkquake", "QUAKE", null),
e("doom-a", "Doom", "doom"), e("doom-b", "Doom", "doom--2"), e("doom-c", "Doom", null),
e("n64", "Quake", null, origin = "N64"),
)).associateBy { it.id }
assertEquals("quake", out.getValue("vkquake").igdb)
assertNull(out.getValue("doom-c").igdb)
assertNull(out.getValue("n64").igdb)
}
@Test fun fileHashesUseTheCatalogsAlgorithms() {
val f = temporary.newFile("h").apply { writeText("hello") }
assertEquals("5d41402abc4b2a76b9719d911017c592", RecompData.hashOf(f, "md5"))
assertEquals("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", RecompData.hashOf(f, "sha1"))
assertEquals("3610a686", RecompData.hashOf(f, "crc32"))
assertNull(RecompData.hashOf(f, "whirlpool"))
}
@Test fun decompBuddyIsReadButItsTakenDownCopiesAreNotUsed() {
assertEquals(listOf(RecompCatalog.DECOMP_BUDDY, RecompCatalog.RECOMP_LAUNCHER, RecompCatalog.RECOMPA), RecompCatalog.FEEDS)
assertTrue(!RecompCatalog.mirrorEnabled)
}
@Test fun theArm64TwinOfAnX64FileKeepsItsName() {
assertEquals(listOf("Game-aarch64.tar.gz", "Game-arm64.tar.gz", "Game-ARM64.tar.gz"), RecompInstaller.armNames("Game-x86_64.tar.gz"))
assertEquals(listOf("Zelda64Recompiled-v1.2.2-Linux-aarch64.zip", "Zelda64Recompiled-v1.2.2-Linux-arm64.zip", "Zelda64Recompiled-v1.2.2-Linux-ARM64.zip"),
RecompInstaller.armNames("Zelda64Recompiled-v1.2.2-Linux-X64.zip"))
assertEquals(emptyList<String>(), RecompInstaller.armNames("Game-Linux.zip"))
}
@Test fun theWrapperStartsTheProgramFromItsOwnFolder() {
val files = temporary.newFolder("files")
File(files, "Game-1.0").mkdirs()
File(files, "Game-1.0/game").apply {
writeText("#!/bin/sh\necho \"cwd=\$PWD\"\nfor a in \"\$@\"; do echo \"arg=\$a\"; done\n")
setExecutable(true)
}
val wrapper = File(files, RecompInstaller.WRAPPER).apply { writeText(RecompInstaller.wrapper("Game-1.0/game")) }
val p = ProcessBuilder("/bin/sh", wrapper.name, "it's").directory(files).redirectErrorStream(true).start()
p.waitFor(10, TimeUnit.SECONDS)
val out = p.inputStream.bufferedReader().readLines()
assertEquals(listOf("cwd=${File(files, "Game-1.0").canonicalPath}", "arg=it's"), out.map { it.replace(files.path, files.canonicalPath) })
}
@Test fun theEntryIsFoundInsideAVersionedFolder() {
val root = temporary.newFolder("stage")
File(root, "ironwail-0.8.2-linux-x64").mkdirs()
File(root, "ironwail-0.8.2-linux-x64/ironwail").writeText("x")
assertEquals("ironwail-0.8.2-linux-x64/ironwail", RecompInstaller.findEntry(root, "ironwail")!!.relativeTo(root).path)
assertNull(RecompInstaller.findEntry(root, "missing"))
}
@Test fun anUnnamedProgramIsGuessedFromTheArchive() {
val root = temporary.newFolder("guess")
fun elf(path: String, size: Int, program: Boolean) = File(root, path).apply {
parentFile.mkdirs()
val bytes = ByteArray(size)
byteArrayOf(0x7f, 'E'.code.toByte(), 'L'.code.toByte(), 'F'.code.toByte(), 2, 1).copyInto(bytes)
bytes[16] = 3
if (program) "/lib/ld-linux-x86-64.so.2".toByteArray().copyInto(bytes, 64)
writeBytes(bytes)
}
val e = RecompCatalog.Entry("sonic-recomp", "Sonic Recompiled", "Sonic", "Xbox 360", "recomp", "o/SonicRecomp", "", "", null,
listOf(RecompCatalog.Build(RecompCatalog.Platform.LINUX_X64, Regex("x"))), RecompCatalog.Data(RecompCatalog.DataKind.NONE, ""), listOf("recompa"))
elf("Game/libSDL2.so", 4000, program = false)
elf("Game/lib/helper", 9000, program = false)
elf("Game/crashpad", 5000, program = true)
val main = elf("Game/SonicRecompiled", 3000, program = true)
assertEquals(main, RecompInstaller.guessEntry(root, e))
val image = File(root, "Game/Sonic.AppImage").apply { writeText("x") }
assertEquals(image, RecompInstaller.guessEntry(root, e))
}
@Test fun anInstalledAndroidPortWithoutARecordIsNeverOfferedAnUpdate() {
val unknown = RecompInstaller.Installed("z", "android:com.z.mm", null, null, "android", temporary.root)
assertTrue(!RecompInstaller.isNewer(RecompInstaller.Release("a2", "q", "", "", null), unknown))
val known = RecompInstaller.Installed("z", "android:com.z.mm", "a1", "p", "android", temporary.root)
assertTrue(RecompInstaller.isNewer(RecompInstaller.Release("a2", "q", "", "", null), known))
}
}
@@ -80,24 +80,6 @@ class OrientationTest {
assertFalse(SessionPrefs.portrait(landscape))
}
@Test fun modeOrientationControlsWindowFollowAndPortraitResolution() {
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, SessionPrefs.windowOrientation(context, true, 700, SessionService.MODE_STEAM))
SessionPrefs.setOrientation(context, "steam", ActivityInfo.SCREEN_ORIENTATION_USER)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(context, true, 700, SessionService.MODE_STEAM))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(context, false, 400, SessionService.MODE_RUN))
val config = android.content.res.Configuration(context.resources.configuration)
config.orientation = android.content.res.Configuration.ORIENTATION_PORTRAIT
val portrait = context.createConfigurationContext(config)
config.orientation = android.content.res.Configuration.ORIENTATION_LANDSCAPE
val landscape = context.createConfigurationContext(config)
assertTrue(SessionPrefs.portrait(portrait, SessionService.MODE_STEAM))
assertFalse(SessionPrefs.portrait(landscape, SessionService.MODE_STEAM))
assertTrue(SessionPrefs.portrait(landscape, SessionService.MODE_DESKTOP))
}
@Test fun invalidLauncherOrientationFallsBackAndInvalidChoicePreservesPreference() {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", 999).commit()
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, AppUiPrefs.orientation(context))
@@ -106,20 +88,4 @@ class OrientationTest {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, AppUiPrefs.orientation(context))
}
@Test fun steamAndDesktopOrientationsAreIndependentAndFallBackToLegacyChoice() {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context, "steam"))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context, "desktop"))
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
SessionPrefs.setOrientation(context, "steam", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
SessionPrefs.setOrientation(context, "desktop", ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, "steam"))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_STEAM))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_RUN))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SessionPrefs.orientation(context, "desktop"))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_DESKTOP))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, SessionPrefs.orientation(context))
}
}
@@ -30,16 +30,4 @@ class OutputPacingTest {
@Test fun mirroringKeepsTheGlassesRate() {
assertEquals(60, SessionPrefs.compositorFpsLimit(60))
}
@Test fun gameModeOverrideCapsAPanelThatRunsFaster() {
assertEquals(60, SessionPrefs.hostFrameCap(60.000004f, 120.00001f))
assertEquals(0, SessionPrefs.hostFrameCap(120.00001f, 120.00001f))
assertEquals(0, SessionPrefs.hostFrameCap(0f, 120f))
}
@Test fun hostCapPacesSteamSessionsAndYieldsToLowerLimits() {
assertEquals(60, SessionPrefs.compositorFpsLimit(0, 0, hostCap = 60))
assertEquals(45, SessionPrefs.compositorFpsLimit(0, 45, hostCap = 60))
assertEquals(SessionPrefs.PIP_FPS, SessionPrefs.compositorFpsLimit(0, 0, pip = true, hostCap = 60))
}
}
@@ -1,12 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollTo
/** Session menu groups start folded; a test opens the one whose rows it checks. */
internal fun SemanticsNodeInteractionsProvider.openSection(key: String) {
if (DrawerSectionState.isOpen(key)) return
onNodeWithTag("drawer-section-$key").performScrollTo().performClick()
}
@@ -227,81 +227,6 @@ class InputSurfaceTouchTest {
touch(MotionEvent.ACTION_UP, 1 to (750f to 285f))
}
@Test fun theMiddleOfACrossedDpadPressesTheNearestArmInsteadOfFallingThrough() {
val up = InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f)
val down = InputSurfaceElement(InputControl.DOWN, .45f, .45f, .1f, .15f)
show(up, down, InputSurfaceElement(InputControl.LEFT, .3f, .25f, .15f, .2f),
InputSurfaceElement(InputControl.RIGHT, .55f, .25f, .15f, .2f), a)
val missed = mutableListOf<Int>()
view.onTouchMiss = { missed += it.actionMasked }
touch(MotionEvent.ACTION_DOWN, 1 to (500f to 170f))
assertEquals(-1, state().hatY())
touch(MotionEvent.ACTION_MOVE, 1 to (540f to 215f))
assertEquals(1, state().hatX())
assertEquals(0, state().hatY())
touch(MotionEvent.ACTION_UP, 1 to (540f to 215f))
assertEquals(0, state().hatX())
assertTrue(missed.isEmpty())
assertFalse(view.takesTouchAt(250f, 210f))
assertFalse(view.takesTouchAt(800f, 500f))
assertFalse(view.takesTouchAt(350f, 100f))
show(up, down)
assertFalse(view.takesTouchAt(500f, 210f))
view.onTouchMiss = null
}
@Test fun aHandPlacedDpadWithOffArmsStillTakesItsMiddle() {
show(InputSurfaceElement(InputControl.UP, .42f, .1f, .1f, .15f),
InputSurfaceElement(InputControl.DOWN, .42f, .45f, .1f, .15f),
InputSurfaceElement(InputControl.LEFT, .3f, .27f, .15f, .15f),
InputSurfaceElement(InputControl.RIGHT, .5f, .25f, .15f, .2f))
touch(MotionEvent.ACTION_DOWN, 1 to (475f to 225f))
assertTrue(state().hatX() != 0 || state().hatY() != 0)
touch(MotionEvent.ACTION_UP, 1 to (475f to 225f))
assertFalse(view.takesTouchAt(750f, 225f))
}
@Test fun aTallGapPicksTheNearestArmAndSplitArmsAreNoCross() {
show(InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f),
InputSurfaceElement(InputControl.DOWN, .45f, .65f, .1f, .15f),
InputSurfaceElement(InputControl.LEFT, .3f, .35f, .15f, .2f),
InputSurfaceElement(InputControl.RIGHT, .55f, .35f, .15f, .2f))
touch(MotionEvent.ACTION_DOWN, 1 to (530f to 290f))
assertEquals(1, state().hatX())
assertEquals(0, state().hatY())
touch(MotionEvent.ACTION_UP, 1 to (530f to 290f))
touch(MotionEvent.ACTION_DOWN, 1 to (530f to 180f))
assertEquals(-1, state().hatY())
assertEquals(0, state().hatX())
touch(MotionEvent.ACTION_UP, 1 to (530f to 180f))
show(InputSurfaceElement(InputControl.UP, .2f, .1f, .1f, .15f),
InputSurfaceElement(InputControl.DOWN, .7f, .6f, .1f, .15f),
InputSurfaceElement(InputControl.LEFT, .1f, .35f, .15f, .2f),
InputSurfaceElement(InputControl.RIGHT, .8f, .35f, .15f, .2f))
assertFalse(view.takesTouchAt(500f, 300f))
}
@Test fun aSecondUpButtonDoesNotHideTheCross() {
show(InputSurfaceElement(InputControl.UP, .1f, .7f, .1f, .15f, "extra-up"),
InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f),
InputSurfaceElement(InputControl.DOWN, .45f, .45f, .1f, .15f),
InputSurfaceElement(InputControl.LEFT, .3f, .25f, .15f, .2f),
InputSurfaceElement(InputControl.RIGHT, .55f, .25f, .15f, .2f))
touch(MotionEvent.ACTION_DOWN, 1 to (500f to 170f))
assertEquals(-1, state().hatY())
touch(MotionEvent.ACTION_UP, 1 to (500f to 170f))
assertEquals(0, state().hatY())
show(InputSurfaceElement(InputControl.UP, .45f, 0f, .1f, .05f, "extra-up"),
InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f),
InputSurfaceElement(InputControl.DOWN, .45f, .45f, .1f, .15f),
InputSurfaceElement(InputControl.LEFT, .3f, .25f, .15f, .2f),
InputSurfaceElement(InputControl.RIGHT, .55f, .25f, .15f, .2f))
touch(MotionEvent.ACTION_DOWN, 1 to (490f to 170f))
assertEquals(-1, state().hatY())
assertEquals(0, state().hatX())
touch(MotionEvent.ACTION_UP, 1 to (490f to 170f))
}
@Test fun adaptiveSticksCaptureAroundThemAndTheLeftOneToTheEdge() {
val left = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, hideWhenIdle = true)
val right = InputSurfaceElement(InputControl.RS, .6f, .3f, .2f, .4f, hideWhenIdle = true)
@@ -107,9 +107,9 @@ class LibraryEntriesTest {
}
@Test fun placesRoundTripThroughTheirOrder() {
val order = listOf("epic", "steam", "favorites", LIBRARY_HIDDEN, "gog", "xbox", "added")
val order = listOf("epic", "steam", "favorites", LIBRARY_HIDDEN, "gog", "xbox", "added", "recomp")
assertEquals(order, placeLibraryTabs(listOf("epic", "gog", "xbox"), libraryPlacesOf(order)))
assertEquals(listOf("favorites", "steam", "epic", "gog", "added", LIBRARY_HIDDEN), placeLibraryTabs(listOf("epic", "gog"), emptyList()))
assertEquals(listOf("favorites", "steam", "epic", "gog", "added", "recomp", LIBRARY_HIDDEN), placeLibraryTabs(listOf("epic", "gog"), emptyList()))
}
@Test fun librarySourcesIgnoreUnknownAndDuplicateOrderEntriesAndAppendNewStores() {
@@ -37,7 +37,7 @@ class LibraryHiddenTest {
}
@Test fun theHiddenTabSortsLastUnlessMoved() {
assertEquals(listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, "epic", Library.ADDED, LIBRARY_HIDDEN), placeLibraryTabs(listOf("epic"), DEFAULT_LIBRARY_PLACES))
assertEquals(listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM, "epic", Library.ADDED, "recomp", LIBRARY_HIDDEN), placeLibraryTabs(listOf("epic"), DEFAULT_LIBRARY_PLACES))
val moved = placeLibraryTabs(listOf("epic"), listOf(LIBRARY_HIDDEN to "epic"))
assertEquals(listOf("epic", LIBRARY_HIDDEN), moved.filter { it == "epic" || it == LIBRARY_HIDDEN })
}
@@ -41,7 +41,7 @@ class NavTabsTest {
@Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() {
assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state()))
assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "recomps"), NavTabs.more(state()))
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps"))
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent"))
assertFalse(com.droiddeck.launcher.agent.AgentTab.shown)
@@ -72,22 +72,11 @@ class NavTabsTest {
@Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() {
place("desktop", TabPlace.MORE)
val s = state()
assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "recomps"), NavTabs.more(s))
assertEquals(NavTabs.MORE, navigationKeys(s).last())
assertFalse("desktop" in navigationKeys(s))
}
@Test fun moreStaysOnTheBarWhenNoTabIsShelvedSoTabsCanStillBeEdited() {
NavTabs.more(state()).forEach { place(it, TabPlace.HIDDEN) }
assertTrue(NavTabs.more(state()).isEmpty())
assertEquals(NavTabs.MORE, navigationKeys(state()).last())
NavTabs.reset(ctx)
NavTabs.more(state()).forEach { place(it, TabPlace.BAR) }
assertTrue(NavTabs.more(state()).isEmpty())
assertEquals(NavTabs.MORE, navigationKeys(state()).last())
assertEquals(1, navigationKeys(state()).count { it == NavTabs.MORE })
}
@Test fun appsAndTheDevHarnessCanBeShownWithoutHomeScreenOrDeveloperTools() {
place("android-apps", TabPlace.MORE)
assertTrue("android-apps" in NavTabs.more(state()))
@@ -112,7 +101,7 @@ class NavTabsTest {
NavTabs.load(ctx)
val s = state()
assertEquals(listOf("steam", "games", "desktop", "components", "setup", "updates", NavTabs.MORE), navigationKeys(s))
assertEquals(listOf("storage", "sync", "decky", "boot-movies"), NavTabs.more(s))
assertEquals(listOf("storage", "sync", "decky", "boot-movies", "recomps"), NavTabs.more(s))
listOf("stores", "downloads", "soundtracks", "android-apps", "agent").forEach { assertEquals(it, TabPlace.HIDDEN, NavTabs.place(s, it)) }
val prefs = ctx.getSharedPreferences("session", Context.MODE_PRIVATE)
assertFalse(prefs.contains("gameStoresEnabled"))
@@ -134,7 +123,7 @@ class NavTabsTest {
assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "stores"))
assertEquals(TabPlace.MORE, NavTabs.place(state(), "components"))
assertEquals(TabPlace.BAR, NavTabs.place(state(), "downloads"))
assertEquals(listOf("components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
assertEquals(listOf("components", "storage", "sync", "decky", "boot-movies", "recomps"), NavTabs.more(state()))
}
@Test fun movingSwapsWithTheNextVisibleTabAndPersists() {
@@ -145,9 +134,9 @@ class NavTabsTest {
}
@Test fun tabsMissingFromASavedOrderSlotInAfterTheirDefaultNeighbour() {
assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"),
assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "recomps", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"),
NavTabs.arrange(listOf("updates", "steam")))
assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "updates"),
assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "decky", "boot-movies", "recomps", "android-apps", "agent", "updates"),
NavTabs.arrange(listOf("games", "steam", "setup", "stores", "desktop", "components", "android-apps", "updates", "bogus")))
}
@@ -156,7 +145,7 @@ class NavTabsTest {
.putString("navTabOrder", "steam,games,soundtracks,stores,desktop,agent,components,android-apps,setup,updates")
.putString("navTabShelved", "soundtracks").commit()
NavTabs.load(ctx)
assertEquals(listOf("soundtracks", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state()))
assertEquals(listOf("soundtracks", "storage", "sync", "decky", "boot-movies", "recomps"), NavTabs.more(state()))
place("sync", TabPlace.BAR)
NavTabs.load(ctx)
assertTrue("sync" in navigationKeys(state()))
@@ -31,9 +31,7 @@ class PenSettingsGroupTest {
@Test fun theDrawerHasNoPenGroupUntilAPenIsKnown() {
compose.setContent { DroidDeckTheme { SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(pen = null)) } }
compose.openSection("controller-touch")
compose.onNodeWithTag("setting-touch").assertExists()
compose.onNodeWithTag("drawer-section-controller-pen").assertDoesNotExist()
compose.onNodeWithTag("setting-pen").assertDoesNotExist()
compose.onNodeWithTag("setting-pen-button").assertDoesNotExist()
}
@@ -45,7 +43,6 @@ class PenSettingsGroupTest {
SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(SessionPrefs.Pen()) { k, v -> picks += k to v })
}
}
compose.openSection("controller-pen")
compose.onNodeWithTag("setting-pen-button").performScrollTo().performClick()
compose.onNodeWithText(context.getString(R.string.gesture_middle_click)).performScrollTo().performClick()
compose.onNodeWithTag("setting-pen").performScrollTo().performClick()
@@ -0,0 +1,77 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.runtime.RecompCatalog
import com.droiddeck.launcher.runtime.RecompData
import org.junit.Assert.assertEquals
import org.junit.Test
class RecompFiltersTest {
private fun row(
id: String, origin: String, vararg platforms: RecompCatalog.Platform, popularity: Long = 0, updated: String = "", listed: String = "",
setup: String? = null, data: RecompData.State? = null,
) = RecompRow(
RecompCatalog.Entry(id, id, id, origin, "recomp", "o/$id", "", "", null, platforms.map { RecompCatalog.Build(it, Regex("x")) },
RecompCatalog.Data(RecompCatalog.DataKind.ROM, "rom"), listOf("recomp-launcher"), popularity, setup,
updated = updated, listed = listed),
data ?: RecompData.State.BringYourOwn(RecompCatalog.Data(RecompCatalog.DataKind.ROM, "rom")), null, null,
)
@Test fun nativeMeansTheBuildThatWouldInstallRunsWithoutFexOrProton() {
val rows = listOf(
row("arm", "N64", RecompCatalog.Platform.LINUX_ARM64, RecompCatalog.Platform.WINDOWS_X64),
row("apk", "N64", RecompCatalog.Platform.ANDROID, RecompCatalog.Platform.LINUX_X64),
row("fex", "PC", RecompCatalog.Platform.LINUX_X64),
row("wine", "Xbox 360", RecompCatalog.Platform.WINDOWS_X64),
)
assertEquals(listOf("arm", "apk"), rows.filter { it.matches(RecompFilter.NATIVE) }.map { it.entry.id })
}
@Test fun systemChipsListOriginsByCountAndSkipSingletonsAndBlanks() {
val rows = listOf(row("a", "N64"), row("b", "N64"), row("c", "PS1"), row("d", "PS1"), row("e", "PS1"), row("f", "Wii"), row("g", ""), row("h", ""))
assertEquals(listOf("PS1" to 3, "N64" to 2), recompSystems(rows))
}
@Test fun sortsOrderByWhatTheyNameAndBestPutsWhatYouHaveFirst() {
val owned = RecompData.State.Owned(com.droiddeck.launcher.stores.Store.STEAM, null, exact = true)
val rows = listOf(
row("popular", "N64", RecompCatalog.Platform.WINDOWS_X64, popularity = 900, updated = "2025-01-01", listed = "2025-01-01"),
row("fresh", "N64", RecompCatalog.Platform.WINDOWS_X64, popularity = 10, updated = "2026-11-30", listed = "2026-11-01"),
row("native", "PS1", RecompCatalog.Platform.LINUX_ARM64, popularity = 50, updated = "2026-01-01", listed = "2026-11-20"),
row("mine", "PC", RecompCatalog.Platform.LINUX_X64, popularity = 1, data = owned),
)
fun ids(sort: RecompSort) = visibleRecomps(rows, "", emptySet(), null, sort).map { it.entry.id }
assertEquals(listOf("mine", "native", "popular", "fresh"), ids(RecompSort.BEST))
assertEquals(listOf("popular", "native", "fresh", "mine"), ids(RecompSort.POPULAR))
assertEquals(listOf("fresh", "native", "popular", "mine"), ids(RecompSort.UPDATED))
assertEquals(listOf("native", "fresh", "popular", "mine"), ids(RecompSort.LISTED))
assertEquals(listOf("fresh", "mine", "native", "popular"), ids(RecompSort.TITLE))
}
@Test fun filtersCombineWithEachOtherTheSystemAndTheSearch() {
val rows = listOf(
row("zelda", "N64", RecompCatalog.Platform.LINUX_ARM64),
row("banjo", "N64", RecompCatalog.Platform.LINUX_X64),
row("setup", "N64", RecompCatalog.Platform.LINUX_ARM64, setup = "Run setup.sh"),
row("crash", "PS1", RecompCatalog.Platform.LINUX_ARM64),
)
fun ids(query: String = "", filters: Set<RecompFilter> = emptySet(), system: String? = null) =
visibleRecomps(rows, query, filters, system, RecompSort.TITLE).map { it.entry.id }
assertEquals(listOf("crash", "setup", "zelda"), ids(filters = setOf(RecompFilter.NATIVE)))
assertEquals(listOf("zelda"), ids(filters = setOf(RecompFilter.NATIVE, RecompFilter.NO_SETUP), system = "N64"))
assertEquals(listOf("banjo"), ids(query = "ban", system = "N64"))
assertEquals(emptyList<String>(), ids(filters = setOf(RecompFilter.INSTALLED)))
}
@Test fun buildFiltersKeepOnlyProjectsWithEveryTickedBuild() {
val rows = listOf(
row("all3", "N64", RecompCatalog.Platform.LINUX_ARM64, RecompCatalog.Platform.LINUX_X64, RecompCatalog.Platform.WINDOWS_X64),
row("pc", "PC", RecompCatalog.Platform.LINUX_X64, RecompCatalog.Platform.WINDOWS_X64),
row("apk", "N64", RecompCatalog.Platform.ANDROID, RecompCatalog.Platform.WINDOWS_X64),
)
fun ids(vararg f: RecompFilter) = visibleRecomps(rows, "", f.toSet(), null, RecompSort.TITLE).map { it.entry.id }
assertEquals(listOf("all3"), ids(RecompFilter.HAS_LINUX_ARM64, RecompFilter.HAS_LINUX_X64, RecompFilter.HAS_WINDOWS))
assertEquals(listOf("all3", "pc"), ids(RecompFilter.HAS_LINUX_X64, RecompFilter.HAS_WINDOWS))
assertEquals(listOf("all3", "apk", "pc"), ids(RecompFilter.HAS_WINDOWS))
assertEquals(listOf("apk"), ids(RecompFilter.HAS_ANDROID, RecompFilter.HAS_WINDOWS))
}
}
@@ -4,51 +4,60 @@ import org.junit.Assert.*
import org.junit.Test
class SessionDrawerPageTest {
@Test fun navigationRunsControllerPerformanceDisplayEffectsGameVrSession() {
@Test fun navigationStartsWithControllerAndGoesStraightToDisplay() {
val pages = sessionDrawerPages(hasAgent = false)
assertEquals(
listOf(SessionDrawerPage.CONTROLLER, SessionDrawerPage.HUD, SessionDrawerPage.DISPLAY, SessionDrawerPage.EFFECTS,
SessionDrawerPage.GAMES, SessionDrawerPage.VR, SessionDrawerPage.SESSION, SessionDrawerPage.MORE),
pages.strip(),
)
assertEquals(SessionDrawerPage.MORE, pages.step(SessionDrawerPage.CONTROLLER, -1))
assertEquals(SessionDrawerPage.CONTROLLER, pages.first())
assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1))
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.CONTROLLER, -1))
assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1))
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1))
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.EFFECTS, 1))
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
}
@Test fun achievementsAndTheAgentStartInsideMore() {
val pages = sessionDrawerPages(hasAchievements = true, hasAgent = true)
assertEquals(listOf(SessionDrawerPage.ACHIEVEMENTS, SessionDrawerPage.AGENT), pages.inMore())
assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.ACHIEVEMENTS))
@Test fun moreKeepsSteamVrByDefaultAndStandsInForThePagesInsideIt() {
val pages = sessionDrawerPages(hasAgent = false)
assertEquals(listOf(SessionDrawerPage.VR), pages.inMore())
assertEquals(SessionDrawerPage.MORE, pages.strip().last())
assertFalse(SessionDrawerPage.VR in pages.strip())
assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.VR))
assertEquals(SessionDrawerPage.GAMES, pages.tabFor(SessionDrawerPage.GAMES))
val strip = pages.strip()
assertEquals(SessionDrawerPage.CONTROLLER, strip.step(pages.tabFor(SessionDrawerPage.AGENT), 1))
}
@Test fun achievementsAreOfferedOnlyForAGameThatHasThem() {
assertFalse(SessionDrawerPage.ACHIEVEMENTS in sessionDrawerPages(hasAchievements = false, hasAgent = false))
assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false))
assertTrue(sessionDrawerPages(hasAgent = false).inMore().isEmpty())
assertEquals(SessionDrawerPage.MORE, strip.step(SessionDrawerPage.SESSION, 1))
assertEquals(SessionDrawerPage.CONTROLLER, strip.step(SessionDrawerPage.MORE, 1))
assertEquals(SessionDrawerPage.SESSION, strip.step(pages.tabFor(SessionDrawerPage.VR), -1))
}
@Test fun anOlderSavedOrderKeepsItsPagesAndGetsAMoreTabAfterSession() {
val saved = listOf("CONTROLLER", "GLASSES", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION")
val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION")
val out = DrawerPages.arrange(saved)
assertEquals(SessionDrawerPage.entries.toSet(), out.toSet())
assertEquals(SessionDrawerPage.MORE, out[out.indexOf(SessionDrawerPage.SESSION) + 1])
assertEquals(listOf(SessionDrawerPage.ACHIEVEMENTS), out.inMore())
assertTrue(SessionDrawerPage.AGENT in out.strip())
assertTrue(out.indexOf(SessionDrawerPage.VR) < out.indexOf(SessionDrawerPage.EFFECTS) + 2)
assertTrue(out.inMore().isEmpty())
}
@Test fun sessionCanBeKeptInsideMore() {
val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "GAMES", "AGENT", "MORE", "SESSION", "VR")
val out = DrawerPages.arrange(saved)
assertEquals(listOf(SessionDrawerPage.ACHIEVEMENTS, SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore())
assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore())
assertFalse(SessionDrawerPage.SESSION in out.strip())
}
@Test fun moreAndSessionCannotBeHidden() {
assertFalse(DrawerPages.hideable(SessionDrawerPage.MORE))
assertFalse(DrawerPages.hideable(SessionDrawerPage.SESSION))
assertTrue(DrawerPages.hideable(SessionDrawerPage.HUD))
}
@Test fun glassesAddTheirPageAfterController() {
val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false)
assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1))
assertEquals(sessionDrawerPages(hasAgent = false), pages.filter { it != SessionDrawerPage.GLASSES })
}
@Test fun theAgentPageComesBeforeSessionOnlyWhenTheTabIsShown() {
val with = sessionDrawerPages(hasAgent = true)
assertEquals(SessionDrawerPage.AGENT, with.step(SessionDrawerPage.GAMES, 1))
assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1))
assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false))
}
@Test fun arrangeKeepsSavedOrderAndSlotsNewPagesAfterTheirNeighbour() {
@@ -58,4 +67,9 @@ class SessionDrawerPageTest {
assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD), out.filter { it in setOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD) })
assertTrue(out.indexOf(SessionDrawerPage.HUD) < out.indexOf(SessionDrawerPage.CONTROLLER))
}
@Test fun sessionPageCannotBeHidden() {
assertFalse(DrawerPages.hideable(SessionDrawerPage.SESSION))
assertTrue(DrawerPages.hideable(SessionDrawerPage.HUD))
}
}
@@ -130,8 +130,6 @@ class SessionSecondScreenTest {
actions(true, listOf(SecondScreenDisplay(1, "Bottom screen"), SecondScreenDisplay(2, "Monitor")), gameSwap = true))
}
}
compose.onNodeWithText(context.getString(R.string.swap_game_screen)).assertDoesNotExist()
compose.openSection("display-second")
compose.onNodeWithText(context.getString(R.string.swap_game_screen)).performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Bottom screen").performScrollTo().assertIsDisplayed()
}
@@ -267,7 +265,7 @@ class SessionSecondScreenTest {
state<Boolean>("drawerOpenState").value = true
state<Boolean>("drawerControllerActive").value = true
state<List<SecondScreenDisplay>>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen"))
for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.HUD,
for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.DISPLAY,
KeyEvent.KEYCODE_BUTTON_L1 to SessionDrawerPage.CONTROLLER)) {
assertTrue(activity.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, button, 0, 0,
device.id, 0, 0, InputDevice.SOURCE_GAMEPAD)))
@@ -311,7 +309,6 @@ class SessionSecondScreenTest {
actions(true, emptyList(), micAvailable = true, micEnabled = true, onMic = changes::add))
}
}
compose.openSection("session-behavior")
compose.onNodeWithTag("setting-microphone").assertIsEnabled()
.assert(SemanticsMatcher.expectValue(StateDescription, context.getString(R.string.widgets_on))).performClick()
assertEquals(listOf(false), changes)
@@ -325,7 +322,6 @@ class SessionSecondScreenTest {
actions(true, emptyList(), micAvailable = true, onMic = changes::add))
}
}
compose.openSection("session-behavior")
compose.onNodeWithTag("setting-microphone").assertIsEnabled()
.assert(SemanticsMatcher.expectValue(StateDescription, context.getString(R.string.widgets_off))).performClick()
assertEquals(listOf(true), changes)
@@ -337,7 +333,6 @@ class SessionSecondScreenTest {
SessionDrawer(true, SessionDrawerPage.SESSION, false, {}, actions(false, emptyList()))
}
}
compose.openSection("session-behavior")
compose.onNodeWithTag("setting-microphone").assertDoesNotExist()
compose.onNodeWithText(context.getString(R.string.mode_mic)).assertDoesNotExist()
}
@@ -359,7 +354,6 @@ class SessionSecondScreenTest {
onInputSelection = { panel.refreshControls() }, onClose = { open.value = false }))
}
}
compose.openSection("controller-input")
compose.onNodeWithTag("setting-input-profile").performScrollTo().performClick()
compose.onNodeWithText("Desktop").performScrollTo().performClick()
compose.onNodeWithTag("input-profile-expand").performScrollTo().performClick()
+282
View File
@@ -0,0 +1,282 @@
# Recomps
The Recomps tab (More → Recomps, key `recomps`) lists PC builds of console and PC games made
by static recompilation, decompilation or engine reimplementation. It installs the build that
runs best on the device and links the game files the player already owns from a store
DroidDeck is signed in to. It never downloads ROMs, disc images or game files.
## The ecosystem (researched 2026-11-30)
- **Recomp Launcher** (`elripalda/RecompLauncher`, GPL-3.0; Xarishark is its most active
contributor). A Tauri desktop launcher for Windows, Linux x86-64 and macOS. It has no Android
or arm64 Linux build. Its catalog `https://recomplauncher.com/pc-catalog.json` lists about 2,270
apps, each with fields such as `repo, tag, assets{windows|linux|macos}, files{sha256}, needs,
setup_steps`. It never ships game data: "Easy Setup" asks for the player's disc or folder,
then runs the recomp's own prepare step. Recomps can describe that step in a
`recomplauncher.json` in their release (schema at
`https://recomplauncher.com/schema/recomplauncher.json`). The FAQ says it is free, has no ads
and keeps usage stats opt-in. The catalog data has no stated licence, and many `needs` lines
are machine-written.
- **Recompa** (`kalasyan/recompa`, GPL-3.0). An Android hub for recomps shipped as APKs. Its
`https://recompa.app/index.json` lists about 790 ports with Android package names, signer
hashes, ABIs and game-data requirements (accepted sha1s, conversions such as v64→z64, and
where the file goes). The data has no stated licence.
- **PortMaster** (`PortsMaster/PortMaster-New`, MIT). Its `ports.json` lists about 1,500 arm64
Linux ports. 266 of them link a Steam page and about 64 a GOG page, so they can be matched to
owned games. Ports expect PortMaster's runtime (`control.txt`, gptokeyb, gl4es).
- Most recomps need a console dump: N64 ROMs (Zelda64Recomp, Starfox64Recomp, BanjoRecomp, the
Ship of Harkinian family) or Xbox 360 files (XenonRecomp: UnleashedRecomp, MarathonRecomp).
The ones that fit DroidDeck's stores are source ports and engine reimplementations whose data
is sold on Steam or GOG: OpenMW (Morrowind), DevilutionX (Diablo, GOG), OpenRCT2, Fallout 1/2
CE, Quake ports, Xash3D (Half-Life), Julius/Augustus (Caesar III), VCMI and fheroes2 (Heroes
III and II), CorsixTH and OpenLoco.
- N64Recomp projects (Zelda, Starfox, Banjo), DevilutionX, Xash3D and fheroes2 publish **arm64
Linux** builds, which run natively in DroidDeck's runtime. Most others publish x86-64 Linux,
which runs through FEX, and Windows, which runs through Proton.
## Catalog
DroidDeck keeps no catalog. `RecompCatalog` downloads three community catalogs, caches them in
`files/recomps/`, revalidates each with its ETag after 6 hours, and merges them on the device. An
earlier catalog wins every field it sets; a later one with the same GitHub repo (or id) adds builds the
entry lacks.
> Decomp Buddy also keeps copies of projects taken down by a legal notice. DroidDeck does not use
> those copies (`RecompCatalog.DECOMP_BUDDY_MIRROR = false`) until that is decided. Its catalog and
> plans are read.
1. **Decomp Buddy** (`TanookiStudios/decomp-buddy`, GPL-3.0):
- `https://tanookistudios.com/decomp-buddy/catalog.json`, about 4,900 games.
- `plans.json`, about 32 MB. `DecompBuddyPlans` reads it as a stream and keeps only the `windows`,
`linux`, `linux-arm64` and `android` targets: the release file, its tag, the program, the scanned
sha256, the Android package and the game files needed.
- Games without a `release` plan are left out.
2. **Recomp Launcher** (`https://recomplauncher.com/pc-catalog.json`):
- `assets` globs and `files` pins; `boot.start` / `start_linux` name the program.
- `setup_required` / `setup_steps` become the setup note.
- Archived, `soon`, non-GitHub, `installer` / `not-a-game` / `source` entries and Flatpak bundles are
left out.
3. **Recompa** (`https://recompa.app/index.json`): Android APKs with a package name and signing
certificate. A Recompa signer is added to a Decomp Buddy APK with the same package.
As of 2026-12-01 this gives 4,764 entries, 1,812 of them found in more than one catalog:
| Build | Entries |
|---|---|
| Linux arm64 | 214 |
| Linux x86-64 | 2,349 |
| Windows x86-64 | 4,036 |
| Android | 836 |
The two parses and the merge take about 1.3 s on a desktop JVM. 96% of builds name their release
file, so they download without the GitHub releases API.
The build is chosen in the order linux-arm64 (native), android, linux-x64 (FEX), windows-x64
(Proton).
- **Linux x86-64:** before installing, the release is checked for an arm64 twin, the same file name
with `aarch64`/`arm64` in place of `x86_64`/`amd64`/`x64` (Decomp Buddy's `armSibling` rule). The
check uses a plain request to the download URL. If the twin exists, it is installed natively instead.
- **No program named:** an AppImage, else the executable ELF closest to the project's name (Linux), or
`GameExePicker`'s best exe (Windows).
- **Download fails:** if the project's own download fails and Decomp Buddy scanned that file, it is
fetched from `files.decompbuddy.com/<sha256>/<name>`. That copy is a fallback only, because Decomp
Buddy's hosting runs on donations.
## Installing
`RecompInstaller.install`:
1. Downloads the asset, checking its sha256.
2. **Linux build:** `bsdtar` in the guest unpacks it into the app cache, keeping modes and
symlinks, and unpacks again when the result is a single archive (Zelda's zip holds a tar.gz) or
a Debian package (its `data.tar`), up to three levels. It then finds `entry` up to four folders down. An AppImage, whether downloaded
directly or found inside the archive, goes to `AppImageManager.import`. Anything else becomes
a user app (`UserApps.addPrepared`): the unpacked tree moves to
`/opt/droiddeck-apps/<id>/files`, and a `droiddeck-recomp` wrapper, which starts the program from
its own folder, becomes its entry.
`droiddeck-script-run` launches it, so `droiddeck-fex` decides between native and FEX from
the folder's ELFs, exactly as for any added Linux app. It also shows on the Desktop page.
3. **Windows build:** unpacks into `<first Games folder or the store install root>/Recomps/<id>`
and registers the exe with `AddedGames.addExe`. It then appears in the Library (Custom) and
runs through Proton.
4. **Android build:** checks the APK's package name and signing certificate against the catalog,
then installs it through `PackageInstaller` (`RecompAndroid`). The confirmation prompt comes from
the system. The install shows as Play and Remove on the card, and in the Apps tab. The installed tag
is kept in `files/recomps-android/<package>`.
5. Writes `recomp-id`, `recomp-tag`, `recomp-published`, `recomp-platform` and `recomp-repo` beside the
install. `RecompInstaller.installed` finds installs by those files. An install belongs to the entry
with its id, or else its repo, since a higher-ranked catalog can rename an entry. An update installs the
new release first and then deletes the old folder.
## In Steam and the Library
- **Linux recomps** (script apps and AppImages) are non-Steam games (`RecompShortcuts`):
- Each install gets a `play` script beside it that runs `droiddeck-script-run` or the AppImage
launcher, and the catalog's cover and icon are saved there.
- The shortcut is native (no compatibility tool) and its ID is Steam's CRC of the quoted program and
name.
- It is written to the session's shortcut listing next to the Epic launcher, so the next Steam start
has it. It is also added to a running client at once, and removed when the recomp is.
- **Windows recomps** are added games, so they are already non-Steam games.
- **Android apps** cannot be Steam shortcuts and stay in Apps.
- **Library:** Linux recomps also show in a **Recomps** chip, after Custom; it can be hidden like Custom.
Starting one from the Library always runs it as the Linux app, even when DroidDeck launches without
Steam.
## Android installs
- **CPU check:** before Android's prompt, the APK's `lib/<abi>/` folders are checked against
`Build.SUPPORTED_ABIS`. Many newer handhelds (the Pocket FIT included) run 64-bit code only, so a
port that only ships `armeabi-v7a` can never install there. Such an APK is stopped with a sentence
naming both sets of CPUs.
- **Remembered:** the package is recorded in `files/recomps-android/incompatible` (as is one Android
refuses with `NO_MATCHING_ABIS`). Install then picks another build, "Runs natively" stops counting
it, and its build row says "Not for this device".
- **Failures in words, naming the game:**
- wrong CPU;
- another copy signed by someone else;
- a newer version installed;
- not enough space;
- cancelled, blocked, or a damaged APK.
The last failure stays on the recomp's page until the next attempt.
## Game data
PC ports need the original PC game's files, which a store sells. For these entries (Decomp Buddy's "PC
(Windows)" and "IBM PC (MS-DOS)", Recomp Launcher's `pc` origin), DroidDeck works out whether the player
already has them.
**1. Which store release is the game: `RecompStoreIds`.** None of the catalogs names one.
- **IGDB slug:** Recomp Launcher gives each game's IGDB slug (`about.url`). Other ports of the same PC
game take it when the title leads to one slug (`shareIgdb`). That covers 390 of 1,104 PC entries.
- **Wikidata:** links IGDB slugs (P5794) to Steam app IDs (P1733), GOG slugs (P2725) and Epic store
slugs (P6278). It is asked in batches of 150 over SPARQL and cached in `files/recomps/store-ids.json`
for 14 days. 144 PC games get at least one store ID: 121 Steam, 90 GOG, 18 Epic.
- **GOG:** GOG's public products API (`api.gog.com/products?ids=…`, 50 per call) gives the slug of each
GOG product the player owns or installed. Kept in `gog-slugs.json`, since slugs don't change.
**2. Matching an install or owned game.**
- For a store with known IDs for the game, only the ID counts: a Steam app ID, or a GOG product's slug.
A title match is not used there, so DOOM (2016) never stands in for Doom (1993).
- Epic IDs can't be compared yet: DroidDeck keeps an Epic game's namespace and app name, not its store
slug. So Epic, and any store without IDs for the game, falls back to Decomp Buddy's title rules (from
`src/stores.js`):
- A subtitle after a colon or dash is fine.
- A leading possessive such as "Sid Meier's" is dropped.
- Only store-edition words (GOTY, Gold, Complete, Definitive, ...) may follow the title.
- Installs come from store sidecars and the Steam client libraries, internal or SD card. Owned games
come from the store libraries and the Steam page.
**3. The right files.**
- **The file:** Decomp Buddy's `expected_filename` or Recomp Launcher's `inputs[game].check.file` (112
PC entries) names a file the port needs. It is looked for as a relative path, without case, up to 4
folders into the install. The folder holding it is the one shown.
- **The version:** when Decomp Buddy gives `expected_hashes` (sha1, sha256, md5, crc32) or
`expected_size` (31 PC entries), the file must match. Hashes are kept in `hashes.json` by path, size
and modified time.
| State | Card |
|---|---|
| Found, file checked | green "Installed on Steam · files checked", and the folder |
| Found by ID, no file to check | green "Installed on Steam" |
| Found by title only | grey "Installed on Steam · matched by name" |
| Incomplete | "Installed on GOG, but DIABDAT.MPQ is missing", or "… is a different version" |
| Owned | "You own it on Steam. Install it first", with "Install game" |
| Otherwise | what the catalog says the game needs |
Console recomps are never matched, because no store sells their dumps.
## UI
The page follows the Library.
- **Header:** `ModeHeader` with the title and the count shown, search, and Filter, Sort and Display
buttons. These use the Library's `Steps` popovers, and Display is the Library's own tile size and
title/detail toggles.
- **Filter:** multi-select, each choice with its count: Installed, You own the game, Runs natively
(the build that would install is arm64 Linux or an APK), Android app, Update available, Ready without
setup ("No setup steps"). Filters in use show as removable chips under the header, with "Clear all", and the Filter
button gets a dot.
- **Build filters:** "Has a build for" Linux ARM64, Linux x86-64, Windows or Android, in their own group
of the Filter menu. Like every filter they combine with AND, so all three desktop builds ticked leaves
only projects that publish all three.
- **Sort:** Best for you (installed, then found in a store install, then owned, then native, each by
popularity), Most popular, Recently updated, Newly listed, A–Z.
- **Systems:** a row of the original systems in the current results, most entries first.
- **Grid:** box-art tiles (`ArtCard`, capsule art from the catalogs' covers), sized by `LevelCells` like
the Library. Each tile shows the name, "System · Native/Android/FEX/Proton", and corner badges for
installed, the store you own it on, and an available update.
- **Detail page** (opening a tile):
- Cover, name, game and kind, chips for how it runs and its data state.
- Actions: Install, Play or Open in Games, Update, Install game, Project page, Remove.
- "What it needs": the folder found, or the file it looks for, or the catalog's note.
- "Builds": every build as a choice. The one that would install is selected. Picking another changes
the main button to "Install <build>", or "Install <build> instead" when a different build is
installed. A picked build installs exactly as listed, with no arm64 twin swapped in.
- Switching replaces the old install, except an Android app, which Android asks the player to remove.
The last pick is kept in `files/recomps/choices.json`, so the card shows that build when two are
installed.
- "About": repo, licence, sources.
- Back returns to the grid.
- **Kept in memory** (`RecompsView`): search, filters, sort and system, so leaving the tab keeps your place.
## Tested
These device runs used the earlier hand-made list. Each recomp is still installed and launched by the
same code.
- **Retroid Pocket Duo:**
- Zelda 64: Recompiled v1.2.2 (linux-arm64) installed and reached its own Select ROM screen natively.
- Ironwail v0.8.2 (linux-x64) ran through FEX and asked for its `-basedir` (Quake's folder).
- Ship of Harkinian (Android, Recompa): the APK passed the package and signer checks, Android's
install prompt appeared, and after confirming it the card showed Play, which launched the app.
- Ports already installed were recognised.
- The top screen shows the page; the bottom screen's rail is labelled Recomps.
- **Pocket FIT Elite (portrait 1080×1920):**
- The More tile, the one-column page and installs work.
- A launch of an x86 Linux build stopped with exit 126: FEX needs the Steam Linux Runtime
(sniper), and that device had never opened Steam. This applies to every x86 Linux app in
DroidDeck.
- **Unit tests:** `RecompsTest` parses and merges sample feeds and covers pins, signed APKs, title
matching, release picking, program guessing and the wrapper (run under `/bin/sh`). `NavTabsTest`
covers the tab.
- GZDoom 4.14.2 from Decomp Buddy's `linux-arm64` plan (a `.deb` naming no program), on the Pocket FIT:
installed in about 5 s and started natively to its own "Cannot find a game IWAD" screen. With all
three catalogs the FIT loaded 4,764 entries in 6 s.
- AYN Thor:
- With all three catalogs: 4,764 entries in 11 s, 1,003 running natively.
- Sonic Mania, installed on Steam on the SD card, was matched to the Sonic Mania decomp, showing
`/mnt/droiddeck-sd/steamapps/common/Sonic Mania`.
- Zelda 64: Recompiled v1.2.2 installed from Decomp Buddy's `linux-arm64` plan in about 5 s and
reached its Select ROM screen natively.
- AYN Thor, with store IDs: both Sonic Mania ports matched the Steam install on the SD card by app ID
(via IGDB and Wikidata), not by title.
## Not done yet
- **Recompa delivery rules.** Hand a chosen ROM to an Android port the way Recompa's `delivery`
says: an in-app picker, a shared folder or an intent.
- **Recomp Launcher setup.** Run its `recomplauncher.json` `inputs` / `prepare` steps, so recomps that
build from the player's dump (Unleashed, Marathon, the `setup` entries) can be set up from DroidDeck.
Xarishark offered help on the DroidDeck Discord (2026-11-12).
- **Choosing a build.** Let the player choose another build when an entry has several (for example
the Android port instead of the FEX one).
- **Linking your own folder.** For data copied from a PC: a folder picker the card remembers.
- **Native builds the catalogs miss.** Recomp Launcher lists one Linux build per app, usually x86-64.
Several projects (Zelda64Recomp, Starfox64Recomp, BanjoRecomp, DevilutionX) also publish arm64
builds. Trying the arm64 sibling of a Linux asset first would run those natively instead of
through FEX.
- **ROM checks.** Hash a chosen ROM against `sha1` and say whether it is the right one.
- **x86 runtime hint.** A linux-x64 build needs Steam opened once so the FEX runtime (sniper) is
installed. Show that on the card, or fall back to the Windows build.
- **Epic IDs.** Epic store slugs from Wikidata could be compared once DroidDeck keeps each owned Epic
game's product slug (Epic's catalog has it as `productSlug` / page mappings).
- **Store IDs upstream.** A `stores` field on Recomp Launcher inputs (Steam app IDs, GOG product IDs)
would make Wikidata a fallback. It has been proposed but not filed yet.
- **Recomp setup steps.** Some recomps build themselves from the player's data with bundled
Python (Recompia). They need executable storage, so they must stay inside the Linux root, never
under `/media`; see the Discord thread on Recompia from 2026-11-15.
-1
View File
@@ -32,7 +32,6 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc
| Run without proot (experimental) | Settings › Performance (`droiddeck://settings/performance`) | proot |
| Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor |
| Host name | Settings › Performance (`droiddeck://settings/performance`) | name |
| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot |
| Controller | Settings › Controller (`droiddeck://settings/controller`) | gamepad, buttons, mapping, profile, remap |
| Smart glasses | Settings › Smart glasses (`droiddeck://settings/glasses`) | xreal, viture, vr, ar |
| Theme | Settings › Launcher (`droiddeck://settings/launcher`) | color, dark |
+1 -2
View File
@@ -86,8 +86,7 @@ RTD=$APP/.wayland-rt
export VK_ICD_FILENAMES=$PACK/adapter/icd.json ADRENOTOOLS_DRIVER_PATH=$DRVDIR/ ADRENOTOOLS_HOOKS_PATH=$PACK/lib
export ADRENOTOOLS_DRIVER_NAME=$(drvlib "$DRVDIR")
export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0}
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=0
echo "WSI forced XWayland bypass disabled (GAMESCOPE_WSI_FORCE_BYPASS=$GAMESCOPE_WSI_FORCE_BYPASS)"
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=1
[ -e "$RTD/droiddeck-gamescope-limiter" ] && export GAMESCOPE_LIMITER_FILE=$RTD/droiddeck-gamescope-limiter
# Wine: DXVK/VKD3D over the builtins, X11 inside gamescope (winewayland would pick DroidDeck's compositor),
+1 -11
View File
@@ -494,15 +494,5 @@ gamescope returned the buffer to the client on that release, and a client whose
fences attached to a dma-buf then drew into it while the display was still scanning it out, which showed as black
tiles in compressed buffers. A forwarded client buffer now stays held until `poll(POLLOUT)` on its dma-buf reports
that the display has finished with it, on a waiter thread so nothing else blocks. A release that arrives after the
buffer was shown again is dropped, so the later release decides. A pending wait holds its own reference on the
buffer, since that later release can drop the host's reference before the wait ends. Composite output images keep the 0146 path, and a
buffer was shown again is dropped, so the later release decides. Composite output images keep the 0146 path, and a
host that waits for the fence itself releases buffers that are already idle, so nothing changes there.
## 0148 Wayland backend: composite every frame when the host releases buffers before scanout
With 0147 a forwarded client buffer stays held until the display has finished scanning it out, about one refresh after
the host releases it. Steam's web helper cycles three buffers of its own, so forwarding them held the Steam UI at 80 fps
on a 120 Hz screen (frames alternately one and two refreshes apart). The first time a forwarded buffer comes back while
it is still being scanned out, the backend now composites every frame into its own output images. Those are reused at
latch under 0146, and the client's buffers return as soon as the composite has read them: the Steam UI then runs at
the full 120 fps. Hosts that release a buffer only after scanout never take this path and keep forwarding.
@@ -1,5 +1,5 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 12f0f50..d9db2e6 100644
index 12f0f50..a0fedd4 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -3,24 +3,28 @@
@@ -31,7 +31,7 @@ index 12f0f50..d9db2e6 100644
#include <libdecor.h>
#include "wlr_begin.hpp"
@@ -485,44 +489,86 @@ namespace gamescope
@@ -485,44 +489,82 @@ namespace gamescope
// One backing plane plus every layer steamcompmgr can hand us.
CWaylandPlane m_Planes[k_nMaxLayers + 1];
@@ -78,12 +78,8 @@ index 12f0f50..d9db2e6 100644
+ , m_nFd{ nFd }
+ , m_ulAcquireSerial{ ulAcquireSerial }
+ {
+ // A later acquire and release can drop the compositor's reference before this wait ends.
+ m_pFb->IncRef();
+ }
+
+ ~CWaylandScanoutRelease() { m_pFb->DecRef(); }
+
+ int GetFD() override { return m_nFd; }
+ void OnPollOut() override { Finish(); }
+ void OnPollHangUp() override { Finish(); }
@@ -119,7 +115,7 @@ index 12f0f50..d9db2e6 100644
~CWaylandInputThread();
bool Init( CWaylandBackend *pBackend );
@@ -969,73 +1015,108 @@ namespace gamescope
@@ -969,73 +1011,108 @@ namespace gamescope
.action = WAYLAND_NULL(),
};
const zwp_primary_selection_source_v1_listener CWaylandBackend::s_PrimarySelectionSourceListener =
@@ -239,7 +235,7 @@ index 12f0f50..d9db2e6 100644
, m_pBackend( pBackend )
, m_Planes{ this, this, this, this, this, this, this, this, this }
{
@@ -2349,25 +2430,26 @@ namespace gamescope
@@ -2349,25 +2426,26 @@ namespace gamescope
pDmaBuf->format,
0u );
@@ -1,116 +0,0 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index d9db2e6..5c4cd86 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -804,24 +804,31 @@ namespace gamescope
{
auto iter = m_pOutputs.find( pOutput );
if ( iter == m_pOutputs.end() )
return nullptr;
return &iter->second;
}
wl_region *GetEmptyRegion() const { return m_pEmptyRegion; }
wl_region *GetFullRegion() const { return m_pFullRegion; }
CWaylandFb *GetBlackFb() const { return m_BlackFb.get(); }
+ bool HostReleasesBeforeScanout() const { return m_bHostReleasesBeforeScanout; }
+ void OnHostReleasedBeforeScanout()
+ {
+ if ( !m_bHostReleasesBeforeScanout.exchange( true ) )
+ xdg_log.infof( "Host releases buffers before scanout ends: compositing every frame into our own images" );
+ }
+
void OnConnectorDestroyed( CWaylandConnector *pConnector )
{
m_pFocusConnector.compare_exchange_strong( pConnector, nullptr );
}
private:
void Wayland_Registry_Global( wl_registry *pRegistry, uint32_t uName, const char *pInterface, uint32_t uVersion );
static const wl_registry_listener s_RegistryListener;
void Wayland_Modifier( zwp_linux_dmabuf_v1 *pDmabuf, uint32_t uFormat, uint32_t uModifierHi, uint32_t uModifierLo );
@@ -871,24 +878,25 @@ namespace gamescope
wl_display *m_pDisplay = nullptr;
wl_shm *m_pShm = nullptr;
wl_compositor *m_pCompositor = nullptr;
wp_single_pixel_buffer_manager_v1 *m_pSinglePixelBufferManager = nullptr;
wl_subcompositor *m_pSubcompositor = nullptr;
zwp_linux_dmabuf_v1 *m_pLinuxDmabuf = nullptr;
xdg_wm_base *m_pXdgWmBase = nullptr;
wp_viewporter *m_pViewporter = nullptr;
wl_region *m_pEmptyRegion = nullptr;
wl_region *m_pFullRegion = nullptr;
Rc<CWaylandFb> m_BlackFb;
+ std::atomic<bool> m_bHostReleasesBeforeScanout = { false };
OwningRc<CWaylandFb> m_pOwnedBlackFb;
OwningRc<CVulkanTexture> m_pBlackTexture;
wp_presentation *m_pPresentation = nullptr;
droiddeck_refresh_v1 *m_pHostRefresh = nullptr;
std::array<uint32_t, 16> m_HostRefreshRates{};
std::atomic<uint32_t> m_uHostRefreshRateCount = { 0 };
std::vector<uint32_t> m_PendingHostRefreshRates;
int m_nSentHostRefresh = 0;
int m_nSentHostFrameRate = 0;
frog_color_management_factory_v1 *m_pFrogColorMgmtFactory = nullptr;
wp_color_manager_v1 *m_pWPColorManager = nullptr;
wp_image_description_v1 *m_pWPImageDescriptions[ GamescopeAppTextureColorspace_Count ]{};
@@ -1083,24 +1091,25 @@ namespace gamescope
xdg_log.errorf( "Compositor released us but we were not acquired. Oh no." );
}
void CWaylandFb::Wayland_Buffer_Release( wl_buffer *pBuffer )
{
assert( m_pHostBuffer );
assert( m_pHostBuffer == pBuffer );
xdg_log.debugf( "buffer_release: %p", pBuffer );
if ( ShowsClientBuffer() && gamescope::DmabufScanoutPending( m_nDmabufFd ) )
{
+ m_pBackend->OnHostReleasedBeforeScanout();
int nFd = fcntl( m_nDmabufFd, F_DUPFD_CLOEXEC, 0 );
if ( nFd >= 0 )
{
uint64_t ulSerial;
{
std::scoped_lock lock( m_AcquireMutex );
ulSerial = m_ulAcquireSerial;
}
auto *pWait = new CWaylandScanoutRelease( this, nFd, ulSerial );
if ( CWaylandScanoutRelease::Waiter().AddWaitable( pWait, EPOLLOUT | EPOLLHUP | EPOLLONESHOT ) )
return;
delete pWait;
@@ -1194,24 +1203,27 @@ namespace gamescope
plane.Present( nullptr );
}
else
{
// TODO: Dedupe some of this composite check code between us and drm.cpp
bool bLayer0ScreenSize = close_enough(pFrameInfo->layers.get( 0 ).scale.x, 1.0f) && close_enough(pFrameInfo->layers.get( 0 ).scale.y, 1.0f);
GamescopeUpscaleFilter eLayer0Filter = pFrameInfo->layers.get( 0 ).filter;
bool bNeedsCompositeFromFilter = ( eLayer0Filter == GamescopeUpscaleFilter::NEAREST ||
eLayer0Filter == GamescopeUpscaleFilter::PIXEL ) && !bLayer0ScreenSize;
bNeedsFullComposite |= cv_composite_force;
+ // A forwarded buffer would stay out of its client's hands until scanout ends, which caps a
+ // three-image client at two thirds of the refresh rate. Our own output images are reused at latch.
+ bNeedsFullComposite |= m_pBackend->HostReleasesBeforeScanout();
bNeedsFullComposite |= cv_wayland_overlay_planes >= 0 && pFrameInfo->layers.count() > 1 + cv_wayland_overlay_planes;
bNeedsFullComposite |= pFrameInfo->useFSRLayer0;
bNeedsFullComposite |= pFrameInfo->useNISLayer0;
bNeedsFullComposite |= pFrameInfo->useSGSRLayer0;
bNeedsFullComposite |= pFrameInfo->blurLayer0;
bNeedsFullComposite |= bNeedsCompositeFromFilter;
bNeedsFullComposite |= g_bColorSliderInUse;
bNeedsFullComposite |= pFrameInfo->bFadingOut;
bNeedsFullComposite |= !g_reshade_effect.empty();
if ( g_bOutputHDREnabled )
bNeedsFullComposite |= g_bHDRItmEnable;
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more