mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10a66b2298 | ||
|
|
509c0482bf | ||
|
|
05d1795a51 | ||
|
|
87e6556993 | ||
|
|
8ff1f5dd20 | ||
|
|
93cd54c93b | ||
|
|
c8a49e853a | ||
|
|
78b3f27816 | ||
|
|
eaa095925c | ||
|
|
82b8cf1230 | ||
|
|
4163b31b02 | ||
|
|
02888834d4 | ||
|
|
ec537421ac | ||
|
|
5e23c668f3 | ||
|
|
a12ac8134a | ||
|
|
4562d61139 | ||
|
|
cc5ae4ff0b | ||
|
|
f0c52c273b | ||
|
|
975c76e3e8 | ||
|
|
a394dfd31b | ||
|
|
a2e555f4cc | ||
|
|
31d12a9f6c | ||
|
|
3820445561 | ||
|
|
75d7edd2c3 | ||
|
|
da8fe068d9 |
No files matched your search
@@ -186,7 +186,7 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/linuxfs/debian-image.env') }}
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/linuxfs/debian-image.env', 'tools/vr/**') }}
|
||||
|
||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
@@ -218,6 +218,9 @@ jobs:
|
||||
mkdir -p "$D/usr/local/bin"
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$D/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-clipboard"
|
||||
# Cardboard mode's SteamVR driver and Vulkan layer (tools/vr), Vulkan headers from the runner's NDK.
|
||||
VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \
|
||||
tools/vr/build.sh --native "$D/usr/local/lib/droiddeck-vr"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
|
||||
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
@@ -625,10 +628,11 @@ jobs:
|
||||
|
||||
# Each signed main build as a prerelease of the public Droid-Deck/DroidDeck-CI (main-<sha>, the
|
||||
# last KEEP kept), where anyone can download it without a GitHub account, then a post in the
|
||||
# Discord's builds channel linking to it. The release is made with a token of the org's
|
||||
# Discord's #preview-builds channel linking to it. The release is made with a token of the org's
|
||||
# "DroidDeck CI Publisher" app (installed on DroidDeck-CI only, Contents: write): its ID in the
|
||||
# DROIDDECK_CI_APP_ID variable, its private key in the DROIDDECK_CI_APP_KEY secret.
|
||||
# DISCORD_BUILDS_WEBHOOK is the channel's webhook URL.
|
||||
# DISCORD_BUILDS_WEBHOOK is the channel's webhook URL. Keep this secret name when renaming
|
||||
# the channel: Discord routes the existing webhook by channel ID, not its display name.
|
||||
announce:
|
||||
needs: [build, sign]
|
||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||
@@ -730,7 +734,7 @@ jobs:
|
||||
echo "apk=$GITHUB_SERVER_URL/$CI_REPO/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
|
||||
echo "Published $url"
|
||||
|
||||
- name: Post to Discord
|
||||
- name: Post the Preview build to Discord
|
||||
env:
|
||||
WEBHOOK: ${{ secrets.DISCORD_BUILDS_WEBHOOK }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
@@ -754,7 +758,7 @@ jobs:
|
||||
what="[\`${GITHUB_SHA::7}\`]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA): $subject"
|
||||
fi
|
||||
get=$(printf 'Download: [standard APK](<%s>) · [all variants](<%s>)' "$APK" "$RELEASE")
|
||||
content=$(printf '**New signed build** `main-%s`\n%s\n%s' "${GITHUB_SHA::7}" "$what" "$get")
|
||||
content=$(printf '**New signed Preview build** `main-%s`\n%s\nIn the app: **Updates → Preview**\n%s' "${GITHUB_SHA::7}" "$what" "$get")
|
||||
jq -n --arg content "$content" '{content: $content, allowed_mentions: {parse: []}}' |
|
||||
curl -fsS -H 'Content-Type: application/json' -d @- "$WEBHOOK" -o /dev/null
|
||||
echo "Posted: $content"
|
||||
|
||||
@@ -40,3 +40,4 @@ __pycache__/
|
||||
# Local signing with the release key (tools/build_local.sh); holds a password.
|
||||
.signing.env
|
||||
app/src/main/assets/directaudio/
|
||||
/tools/vr/out/
|
||||
@@ -8,6 +8,7 @@ add_library(droiddeckwayland SHARED
|
||||
src/compositor.c
|
||||
src/vk_present.c
|
||||
src/effects_chain.c
|
||||
src/cardboard.c
|
||||
src/vk_loader.c
|
||||
src/sc_layer.c
|
||||
src/ahb_swapchain.c
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
/* Cardboard pass - see cardboard.h. Compositor thread unless noted.
|
||||
*
|
||||
* The shader is cardboard.frag, pre-compiled like the rest of the compositor's SPIR-V:
|
||||
* glslangValidator -V --vn cardboard_frag_code -o cardboard_frag.h cardboard.frag
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "cardboard.h"
|
||||
#include <math.h>
|
||||
#include <pthread.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef CARDBOARD_HOST_TEST
|
||||
#include <fcntl.h>
|
||||
#include <stdatomic.h>
|
||||
#include <sys/mman.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include "headpose_shm.h"
|
||||
#endif
|
||||
|
||||
#ifndef CARDBOARD_HOST_TEST
|
||||
#include "vk_loader.h"
|
||||
#include "vk_present.h" /* droiddeck_log */
|
||||
/* upscale_vert.h defines its array non-static, and effects_chain.c includes it too: a private name here. */
|
||||
#define upscale_vert_code cardboard_upscale_vert_code
|
||||
#include "upscale_vert.h"
|
||||
#undef upscale_vert_code
|
||||
#include "cardboard_frag.h"
|
||||
#endif
|
||||
|
||||
/* ------------------------------------------------------------------ pure helpers */
|
||||
|
||||
static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; }
|
||||
|
||||
void cardboard_clamp(struct cardboard_params *p) {
|
||||
p->enabled = p->enabled ? 1 : 0;
|
||||
p->source = p->source == CARDBOARD_SOURCE_SBS ? CARDBOARD_SOURCE_SBS : CARDBOARD_SOURCE_SCREEN;
|
||||
p->ipd_m = clampf(p->ipd_m, 0.0f, 0.1f);
|
||||
p->screen_dist_m = clampf(p->screen_dist_m, 0.5f, 50.0f);
|
||||
p->screen_width_m = clampf(p->screen_width_m, 0.2f, 60.0f);
|
||||
p->k1 = clampf(p->k1, -1.0f, 2.0f);
|
||||
p->k2 = clampf(p->k2, -1.0f, 2.0f);
|
||||
p->fov_deg = clampf(p->fov_deg, 30.0f, 140.0f);
|
||||
p->lens_inset = clampf(p->lens_inset, -0.25f, 0.25f);
|
||||
p->chroma = clampf(p->chroma, 0.0f, 0.05f);
|
||||
}
|
||||
|
||||
void cardboard_push_constants(const struct cardboard_params *p, const float pose[9],
|
||||
int src_w, int src_h, int out_w, int out_h, float out[24]) {
|
||||
/* rot0..rot2: the pose's rows, each with one scalar riding in w. */
|
||||
for (int r = 0; r < 3; r++)
|
||||
for (int c = 0; c < 3; c++) out[r * 4 + c] = pose[r * 3 + c];
|
||||
out[3] = p->ipd_m * 0.5f;
|
||||
out[7] = p->screen_dist_m;
|
||||
out[11] = p->screen_width_m * 0.5f;
|
||||
/* lens */
|
||||
out[12] = p->k1;
|
||||
out[13] = p->k2;
|
||||
out[14] = tanf(p->fov_deg * 0.5f * (float)M_PI / 180.0f);
|
||||
out[15] = p->chroma;
|
||||
/* view */
|
||||
out[16] = p->lens_inset;
|
||||
out[17] = (src_w > 0 && src_h > 0) ? (float)src_w / (float)src_h : 16.0f / 9.0f;
|
||||
if (p->source == CARDBOARD_SOURCE_SBS) out[17] *= 0.5f; /* one eye's half */
|
||||
out[18] = (float)p->source;
|
||||
out[19] = (out_w > 0 && out_h > 0) ? ((float)out_w * 0.5f) / (float)out_h : 1.0f;
|
||||
out[20] = out[21] = out[22] = out[23] = 0.0f; /* reserved */
|
||||
}
|
||||
|
||||
#ifndef CARDBOARD_HOST_TEST
|
||||
|
||||
/* ------------------------------------------------------------------ settings + pose */
|
||||
|
||||
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct cardboard_params g_set = {
|
||||
.enabled = 0, .source = CARDBOARD_SOURCE_SCREEN, .ipd_m = 0.064f, .screen_dist_m = 3.0f,
|
||||
.screen_width_m = 4.0f, .k1 = 0.22f, .k2 = 0.24f, .fov_deg = 90.0f, .lens_inset = 0.0f, .chroma = 0.0f};
|
||||
static float g_pose[9] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
|
||||
static volatile int g_changed = 1;
|
||||
|
||||
static int g_live; /* the last pose came from a sensor */
|
||||
static void shm_publish(int live); /* below: the guest's copy of the pose */
|
||||
|
||||
void vkp_cardboard_set(const struct cardboard_params *p) {
|
||||
struct cardboard_params c = *p;
|
||||
cardboard_clamp(&c);
|
||||
pthread_mutex_lock(&g_lock);
|
||||
int was = g_set.enabled;
|
||||
g_set = c;
|
||||
g_changed = 1;
|
||||
shm_publish(g_live);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
if (was != c.enabled || c.enabled)
|
||||
droiddeck_log("cardboard", "%s: %s, ipd %.0f mm, screen %.1f m wide at %.1f m, lens k1 %.2f k2 %.2f, fov %.0f, inset %.3f, chroma %.3f",
|
||||
c.enabled ? "on" : "off", c.source == CARDBOARD_SOURCE_SBS ? "side-by-side source" : "virtual screen",
|
||||
c.ipd_m * 1000.0f, c.screen_width_m, c.screen_dist_m, c.k1, c.k2, c.fov_deg, c.lens_inset, c.chroma);
|
||||
}
|
||||
|
||||
/* The guest's copy of the pose (headpose_shm.h), mapped once a path is known. */
|
||||
static struct droiddeck_headpose *g_shm;
|
||||
static int g_eye_w, g_eye_h; /* the last eye viewport drawn, for the guest */
|
||||
|
||||
void vkp_cardboard_set_pose_file(const char *path) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
if (!g_shm && path && *path) {
|
||||
int fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0600);
|
||||
if (fd >= 0 && ftruncate(fd, sizeof(struct droiddeck_headpose)) == 0) {
|
||||
void *p = mmap(NULL, sizeof(struct droiddeck_headpose), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
if (p != MAP_FAILED) {
|
||||
g_shm = p;
|
||||
memset(g_shm, 0, sizeof(*g_shm));
|
||||
g_shm->magic = DROIDDECK_HEADPOSE_MAGIC;
|
||||
g_shm->version = DROIDDECK_HEADPOSE_VERSION;
|
||||
memcpy(g_shm->rot, g_pose, sizeof(g_shm->rot));
|
||||
}
|
||||
}
|
||||
if (fd >= 0) close(fd);
|
||||
droiddeck_log("cardboard", g_shm ? "head pose shared with the guest at %s" : "could not share the head pose at %s", path);
|
||||
}
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
|
||||
/* Under g_lock. */
|
||||
static void shm_publish(int live) {
|
||||
if (!g_shm) return;
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
atomic_uint *seq = (atomic_uint *)&g_shm->seq;
|
||||
unsigned s = atomic_load_explicit(seq, memory_order_relaxed);
|
||||
atomic_store_explicit(seq, s | 1u, memory_order_relaxed);
|
||||
atomic_thread_fence(memory_order_release);
|
||||
memcpy(g_shm->rot, g_pose, sizeof(g_shm->rot));
|
||||
g_shm->ipd_m = g_set.ipd_m;
|
||||
g_shm->flags = (live ? DROIDDECK_HEADPOSE_LIVE : 0u) | (g_set.enabled ? DROIDDECK_HEADPOSE_ENABLED : 0u);
|
||||
g_shm->time_ns = (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
|
||||
g_shm->tan_half_fov = tanf(g_set.fov_deg * 0.5f * (float)M_PI / 180.0f);
|
||||
g_shm->eye_w = (uint32_t)(g_eye_w > 0 ? g_eye_w : 0);
|
||||
g_shm->eye_h = (uint32_t)(g_eye_h > 0 ? g_eye_h : 0);
|
||||
g_shm->eye_aspect = g_eye_h > 0 ? (float)g_eye_w / (float)g_eye_h : 1.0f;
|
||||
atomic_thread_fence(memory_order_release);
|
||||
atomic_store_explicit(seq, (s | 1u) + 1u, memory_order_relaxed);
|
||||
}
|
||||
|
||||
|
||||
void vkp_cardboard_set_pose(const float m[9], int live) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
memcpy(g_pose, m, sizeof(g_pose));
|
||||
g_live = live;
|
||||
if (g_set.enabled && g_set.source == CARDBOARD_SOURCE_SCREEN) g_changed = 1;
|
||||
shm_publish(live);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
|
||||
static struct cardboard_params g_cur;
|
||||
static float g_cur_pose[9];
|
||||
|
||||
static void snapshot(void) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
g_cur = g_set;
|
||||
memcpy(g_cur_pose, g_pose, sizeof(g_cur_pose));
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
|
||||
int vkp_cardboard_active(void) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
int on = g_set.enabled;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
return on;
|
||||
}
|
||||
|
||||
int vkp_cardboard_pose_changed(void) {
|
||||
if (!g_changed) return 0;
|
||||
g_changed = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Vulkan objects */
|
||||
|
||||
#define CB_FORMAT VK_FORMAT_R8G8B8A8_UNORM
|
||||
#define CB_PC_SIZE (4 * 4 + 24 * 4) /* ndc + the 24 floats: 112 bytes, under the 128 guaranteed */
|
||||
#define CB_MAX_SOURCES 8 /* source views per frame: the real frame + generated ones */
|
||||
|
||||
static VkDevice g_dev;
|
||||
static VkPhysicalDeviceMemoryProperties g_mp;
|
||||
static int g_ready; /* 0 = not built, 1 = ok, -1 = failed (said once) */
|
||||
static VkRenderPass g_rp;
|
||||
static VkDescriptorSetLayout g_dsl;
|
||||
static VkPipelineLayout g_pl;
|
||||
static VkDescriptorPool g_dpool;
|
||||
static VkSampler g_sampler;
|
||||
static VkPipeline g_pipe;
|
||||
static struct { VkImage img; VkDeviceMemory mem; VkImageView view; VkFramebuffer fb; int w, h; } g_t;
|
||||
static struct { VkImageView view; VkDescriptorSet ds; } g_src[CB_MAX_SOURCES];
|
||||
static int g_nsrc;
|
||||
|
||||
void vkp_cardboard_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops) {
|
||||
g_dev = dev;
|
||||
g_mp = *memprops;
|
||||
}
|
||||
|
||||
static int memtype(uint32_t bits, VkMemoryPropertyFlags want) {
|
||||
for (uint32_t i = 0; i < g_mp.memoryTypeCount; i++)
|
||||
if ((bits & (1u << i)) && (g_mp.memoryTypes[i].propertyFlags & want) == want) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static void sources_release(void) {
|
||||
for (int i = 0; i < g_nsrc; i++) {
|
||||
if (g_src[i].ds) g_vk.FreeDescriptorSets(g_dev, g_dpool, 1, &g_src[i].ds);
|
||||
if (g_src[i].view) g_vk.DestroyImageView(g_dev, g_src[i].view, NULL);
|
||||
}
|
||||
memset(g_src, 0, sizeof(g_src));
|
||||
g_nsrc = 0;
|
||||
}
|
||||
|
||||
void vkp_cardboard_begin_frame(void) {
|
||||
if (g_ready == 1) sources_release();
|
||||
}
|
||||
|
||||
static void target_destroy(void) {
|
||||
if (g_t.fb) g_vk.DestroyFramebuffer(g_dev, g_t.fb, NULL);
|
||||
if (g_t.view) g_vk.DestroyImageView(g_dev, g_t.view, NULL);
|
||||
if (g_t.img) g_vk.DestroyImage(g_dev, g_t.img, NULL);
|
||||
if (g_t.mem) g_vk.FreeMemory(g_dev, g_t.mem, NULL);
|
||||
memset(&g_t, 0, sizeof(g_t));
|
||||
}
|
||||
|
||||
static VkImageView make_view(VkImage img) {
|
||||
VkImageView v = VK_NULL_HANDLE;
|
||||
VkImageViewCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = img,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D, .format = CB_FORMAT,
|
||||
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
|
||||
if (g_vk.CreateImageView(g_dev, &ci, NULL, &v) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The panel-sized output: rendered into, then blitted 1:1 to the swapchain. Kept uncompressed
|
||||
* (mutable format) like the effect chain's targets: UBWC render-then-blit targets corrupt on
|
||||
* Adreno 740. */
|
||||
static int target_ensure(int w, int h) {
|
||||
if (g_t.img && g_t.w == w && g_t.h == h) return 0;
|
||||
target_destroy();
|
||||
VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,
|
||||
.imageType = VK_IMAGE_TYPE_2D, .format = CB_FORMAT, .extent = {(uint32_t)w, (uint32_t)h, 1},
|
||||
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
if (g_vk.CreateImage(g_dev, &ii, NULL, &g_t.img) != VK_SUCCESS) goto fail;
|
||||
VkMemoryRequirements req;
|
||||
g_vk.GetImageMemoryRequirements(g_dev, g_t.img, &req);
|
||||
int idx = memtype(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
if (idx < 0) idx = memtype(req.memoryTypeBits, 0);
|
||||
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = req.size,
|
||||
.memoryTypeIndex = (uint32_t)(idx < 0 ? 0 : idx)};
|
||||
if (g_vk.AllocateMemory(g_dev, &mai, NULL, &g_t.mem) != VK_SUCCESS) goto fail;
|
||||
g_vk.BindImageMemory(g_dev, g_t.img, g_t.mem, 0);
|
||||
if (!(g_t.view = make_view(g_t.img))) goto fail;
|
||||
VkFramebufferCreateInfo fi = {.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, .renderPass = g_rp,
|
||||
.attachmentCount = 1, .pAttachments = &g_t.view, .width = (uint32_t)w,
|
||||
.height = (uint32_t)h, .layers = 1};
|
||||
if (g_vk.CreateFramebuffer(g_dev, &fi, NULL, &g_t.fb) != VK_SUCCESS) goto fail;
|
||||
g_t.w = w;
|
||||
g_t.h = h;
|
||||
droiddeck_log("cardboard", "eye target %dx%d (two %dx%d eyes)", w, h, w / 2, h);
|
||||
return 0;
|
||||
fail:
|
||||
droiddeck_log("error", "cardboard: could not create the %dx%d eye target", w, h);
|
||||
target_destroy();
|
||||
return -1;
|
||||
}
|
||||
|
||||
static VkShaderModule shader(const uint32_t *code, size_t size) {
|
||||
VkShaderModule m = VK_NULL_HANDLE;
|
||||
VkShaderModuleCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = size, .pCode = code};
|
||||
if (g_vk.CreateShaderModule(g_dev, &ci, NULL, &m) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
return m;
|
||||
}
|
||||
|
||||
static void objects_destroy(void) {
|
||||
if (!g_dev) return;
|
||||
sources_release();
|
||||
target_destroy();
|
||||
if (g_pipe) g_vk.DestroyPipeline(g_dev, g_pipe, NULL);
|
||||
if (g_dpool) g_vk.DestroyDescriptorPool(g_dev, g_dpool, NULL);
|
||||
if (g_pl) g_vk.DestroyPipelineLayout(g_dev, g_pl, NULL);
|
||||
if (g_dsl) g_vk.DestroyDescriptorSetLayout(g_dev, g_dsl, NULL);
|
||||
if (g_sampler) g_vk.DestroySampler(g_dev, g_sampler, NULL);
|
||||
if (g_rp) g_vk.DestroyRenderPass(g_dev, g_rp, NULL);
|
||||
g_pipe = VK_NULL_HANDLE; g_dpool = VK_NULL_HANDLE; g_pl = VK_NULL_HANDLE;
|
||||
g_dsl = VK_NULL_HANDLE; g_sampler = VK_NULL_HANDLE; g_rp = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
static int objects_ensure(void) {
|
||||
if (g_ready) return g_ready == 1 ? 0 : -1;
|
||||
if (!g_dev || !g_vk.CreateGraphicsPipelines) goto fail;
|
||||
{
|
||||
/* One colour target, overwritten whole, left GENERAL for the 1:1 blit that follows. */
|
||||
VkAttachmentDescription att = {.format = CB_FORMAT, .samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
|
||||
.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
|
||||
.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, .finalLayout = VK_IMAGE_LAYOUT_GENERAL};
|
||||
VkAttachmentReference ref = {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
|
||||
VkSubpassDescription sub = {.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, .colorAttachmentCount = 1,
|
||||
.pColorAttachments = &ref};
|
||||
VkSubpassDependency deps[2] = {
|
||||
{.srcSubpass = VK_SUBPASS_EXTERNAL, .dstSubpass = 0,
|
||||
.srcStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
|
||||
.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT,
|
||||
.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT},
|
||||
{.srcSubpass = 0, .dstSubpass = VK_SUBPASS_EXTERNAL,
|
||||
.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
|
||||
.dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
|
||||
VkRenderPassCreateInfo rci = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, .attachmentCount = 1,
|
||||
.pAttachments = &att, .subpassCount = 1, .pSubpasses = &sub,
|
||||
.dependencyCount = 2, .pDependencies = deps};
|
||||
if (g_vk.CreateRenderPass(g_dev, &rci, NULL, &g_rp) != VK_SUCCESS) goto fail;
|
||||
|
||||
VkSamplerCreateInfo sci = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_LINEAR,
|
||||
.minFilter = VK_FILTER_LINEAR, .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
|
||||
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE};
|
||||
if (g_vk.CreateSampler(g_dev, &sci, NULL, &g_sampler) != VK_SUCCESS) goto fail;
|
||||
|
||||
VkDescriptorSetLayoutBinding b = {.binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT};
|
||||
VkDescriptorSetLayoutCreateInfo dli = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
|
||||
.bindingCount = 1, .pBindings = &b};
|
||||
if (g_vk.CreateDescriptorSetLayout(g_dev, &dli, NULL, &g_dsl) != VK_SUCCESS) goto fail;
|
||||
VkPushConstantRange pcr = {.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
|
||||
.offset = 0, .size = CB_PC_SIZE};
|
||||
VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1,
|
||||
.pSetLayouts = &g_dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pcr};
|
||||
if (g_vk.CreatePipelineLayout(g_dev, &pli, NULL, &g_pl) != VK_SUCCESS) goto fail;
|
||||
VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, CB_MAX_SOURCES};
|
||||
VkDescriptorPoolCreateInfo dpi = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
|
||||
.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
|
||||
.maxSets = CB_MAX_SOURCES, .poolSizeCount = 1, .pPoolSizes = &ps};
|
||||
if (g_vk.CreateDescriptorPool(g_dev, &dpi, NULL, &g_dpool) != VK_SUCCESS) goto fail;
|
||||
|
||||
VkShaderModule vert = shader(cardboard_upscale_vert_code, sizeof(cardboard_upscale_vert_code));
|
||||
VkShaderModule frag = shader(cardboard_frag_code, sizeof(cardboard_frag_code));
|
||||
if (!vert || !frag) {
|
||||
if (vert) g_vk.DestroyShaderModule(g_dev, vert, NULL);
|
||||
if (frag) g_vk.DestroyShaderModule(g_dev, frag, NULL);
|
||||
goto fail;
|
||||
}
|
||||
VkPipelineShaderStageCreateInfo st[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vert, .pName = "main"},
|
||||
{.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = frag, .pName = "main"}};
|
||||
VkPipelineVertexInputStateCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
|
||||
VkPipelineInputAssemblyStateCreateInfo ia = {.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
|
||||
.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP};
|
||||
VkDynamicState dyn[2] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
|
||||
VkPipelineDynamicStateCreateInfo ds = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
|
||||
.dynamicStateCount = 2, .pDynamicStates = dyn};
|
||||
VkPipelineViewportStateCreateInfo vp = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
|
||||
.viewportCount = 1, .scissorCount = 1};
|
||||
VkPipelineRasterizationStateCreateInfo rs = {.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
|
||||
.polygonMode = VK_POLYGON_MODE_FILL, .cullMode = VK_CULL_MODE_NONE,
|
||||
.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE, .lineWidth = 1.0f};
|
||||
VkPipelineMultisampleStateCreateInfo ms = {.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
|
||||
.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT};
|
||||
VkPipelineColorBlendAttachmentState ba = {.blendEnable = VK_FALSE, .colorWriteMask = 0xF};
|
||||
VkPipelineColorBlendStateCreateInfo cb = {.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
|
||||
.attachmentCount = 1, .pAttachments = &ba};
|
||||
VkGraphicsPipelineCreateInfo pi = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 2,
|
||||
.pStages = st, .pVertexInputState = &vi, .pInputAssemblyState = &ia,
|
||||
.pViewportState = &vp, .pRasterizationState = &rs, .pMultisampleState = &ms,
|
||||
.pColorBlendState = &cb, .pDynamicState = &ds, .layout = g_pl,
|
||||
.renderPass = g_rp, .subpass = 0};
|
||||
VkResult r = g_vk.CreateGraphicsPipelines(g_dev, VK_NULL_HANDLE, 1, &pi, NULL, &g_pipe);
|
||||
g_vk.DestroyShaderModule(g_dev, vert, NULL);
|
||||
g_vk.DestroyShaderModule(g_dev, frag, NULL);
|
||||
if (r != VK_SUCCESS) goto fail;
|
||||
}
|
||||
g_ready = 1;
|
||||
droiddeck_log("cardboard", "pass ready on %s", vkp_gpu_name());
|
||||
return 0;
|
||||
fail:
|
||||
objects_destroy();
|
||||
g_ready = -1;
|
||||
droiddeck_log("error", "cardboard: the pass could not be built on this driver; frames are shown flat");
|
||||
return -1;
|
||||
}
|
||||
|
||||
static VkDescriptorSet source_ds(VkImage src) {
|
||||
if (g_nsrc >= CB_MAX_SOURCES) return VK_NULL_HANDLE;
|
||||
VkImageView view = make_view(src);
|
||||
if (!view) return VK_NULL_HANDLE;
|
||||
VkDescriptorSet ds = VK_NULL_HANDLE;
|
||||
VkDescriptorSetAllocateInfo ai = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
|
||||
.descriptorPool = g_dpool, .descriptorSetCount = 1, .pSetLayouts = &g_dsl};
|
||||
if (g_vk.AllocateDescriptorSets(g_dev, &ai, &ds) != VK_SUCCESS) {
|
||||
g_vk.DestroyImageView(g_dev, view, NULL);
|
||||
return VK_NULL_HANDLE;
|
||||
}
|
||||
VkDescriptorImageInfo ii = {.sampler = g_sampler, .imageView = view, .imageLayout = VK_IMAGE_LAYOUT_GENERAL};
|
||||
VkWriteDescriptorSet wr = {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = ds, .dstBinding = 0,
|
||||
.descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.pImageInfo = &ii};
|
||||
g_vk.UpdateDescriptorSets(g_dev, 1, &wr, 0, NULL);
|
||||
g_src[g_nsrc].view = view;
|
||||
g_src[g_nsrc].ds = ds;
|
||||
g_nsrc++;
|
||||
return ds;
|
||||
}
|
||||
|
||||
VkImage vkp_cardboard_run(VkCommandBuffer cmd, VkImage src, int src_w, int src_h, int out_w, int out_h) {
|
||||
if (out_w < 2 || out_h < 1 || objects_ensure() != 0 || target_ensure(out_w, out_h) != 0) return VK_NULL_HANDLE;
|
||||
VkDescriptorSet ds = source_ds(src);
|
||||
if (!ds) {
|
||||
static int said;
|
||||
if (!said) { said = 1; droiddeck_log("error", "cardboard: no descriptor for the frame; shown flat"); }
|
||||
return VK_NULL_HANDLE;
|
||||
}
|
||||
if (g_eye_w != out_w / 2 || g_eye_h != out_h) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
g_eye_w = out_w / 2;
|
||||
g_eye_h = out_h;
|
||||
shm_publish(g_live);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
snapshot();
|
||||
struct { float ndc[4]; float rest[24]; } pc = {{-1.0f, -1.0f, 1.0f, 1.0f}, {0}};
|
||||
cardboard_push_constants(&g_cur, g_cur_pose, src_w, src_h, out_w, out_h, pc.rest);
|
||||
|
||||
VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_rp,
|
||||
.framebuffer = g_t.fb, .renderArea = {{0, 0}, {(uint32_t)out_w, (uint32_t)out_h}}};
|
||||
VkViewport vp = {0, 0, (float)out_w, (float)out_h, 0, 1};
|
||||
VkRect2D sc = {{0, 0}, {(uint32_t)out_w, (uint32_t)out_h}};
|
||||
g_vk.CmdBeginRenderPass(cmd, &rpi, VK_SUBPASS_CONTENTS_INLINE);
|
||||
g_vk.CmdSetViewport(cmd, 0, 1, &vp);
|
||||
g_vk.CmdSetScissor(cmd, 0, 1, &sc);
|
||||
g_vk.CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pipe);
|
||||
g_vk.CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pl, 0, 1, &ds, 0, NULL);
|
||||
g_vk.CmdPushConstants(cmd, g_pl, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(pc), &pc);
|
||||
g_vk.CmdDraw(cmd, 4, 1, 0, 0);
|
||||
g_vk.CmdEndRenderPass(cmd);
|
||||
return g_t.img;
|
||||
}
|
||||
|
||||
#endif /* CARDBOARD_HOST_TEST */
|
||||
@@ -0,0 +1,83 @@
|
||||
#version 450
|
||||
// Cardboard pass (cardboard.c): the finished frame -> two eye viewports, side by side, each
|
||||
// barrel-distorted for a phone-in-a-viewer lens. Runs on upscale.vert's full quad, so uv covers
|
||||
// the whole panel with (0,0) at the top left.
|
||||
//
|
||||
// Source modes:
|
||||
// 0 = virtual screen: the frame is a flat screen hanging in front of the viewer. Each eye casts
|
||||
// a ray through its lens, rotated by the head pose, from its own position (half the IPD to
|
||||
// either side), so the screen has real stereo depth and stays put while the head turns.
|
||||
// 1 = side by side: the frame already holds a left and a right eye image (SteamVR, an SBS 3D
|
||||
// game or video); each eye samples its own half. The head pose belongs to whoever rendered
|
||||
// it, so none is applied here.
|
||||
//
|
||||
// Regenerate cardboard_frag.h after editing (glslangValidator, see cardboard.c).
|
||||
layout(binding = 0) uniform sampler2D Source;
|
||||
layout(location = 0) in vec2 uv;
|
||||
layout(location = 0) out vec4 outColor;
|
||||
|
||||
layout(push_constant) uniform PC {
|
||||
vec4 ndc; // upscale.vert's quad
|
||||
vec4 rot0; // xyz: head -> world rotation, row 0; w: half the IPD (m)
|
||||
vec4 rot1; // xyz: row 1; w: distance to the virtual screen (m)
|
||||
vec4 rot2; // xyz: row 2; w: half the virtual screen's width (m)
|
||||
vec4 lens; // x: k1, y: k2, z: tan of half the eye's vertical field of view, w: chromatic spread
|
||||
vec4 view; // x: lens centre inset (fraction of an eye viewport), y: source aspect w/h,
|
||||
// z: source mode, w: eye viewport aspect w/h
|
||||
} pc;
|
||||
|
||||
const vec3 BACKDROP = vec3(0.015, 0.015, 0.02);
|
||||
|
||||
// Lens: a point on the panel at tangent-space offset t (from the lens centre) shows the ray that
|
||||
// leaves the eye at t * (1 + k1 r^2 + k2 r^4). Sampling outwards like this draws the picture
|
||||
// barrel-shaped; the viewer's lens pincushions it back.
|
||||
vec2 undistort(vec2 t, float scale) {
|
||||
float r2 = dot(t, t);
|
||||
return t * scale * (1.0 + pc.lens.x * r2 + pc.lens.y * r2 * r2);
|
||||
}
|
||||
|
||||
// What one eye sees along tangent direction tan (x right, y down): colour, or the backdrop.
|
||||
vec3 eyeSample(vec2 tan, float eye) {
|
||||
if (pc.view.z > 0.5) {
|
||||
// Side by side: this eye's half of the source covers the eye's field of view.
|
||||
float tanH = pc.lens.z;
|
||||
vec2 s = vec2(tan.x / (tanH * pc.view.w), tan.y / tanH) * 0.5 + 0.5;
|
||||
if (any(lessThan(s, vec2(0.0))) || any(greaterThan(s, vec2(1.0)))) return vec3(0.0);
|
||||
return texture(Source, vec2((s.x + eye) * 0.5, s.y)).rgb;
|
||||
}
|
||||
// mat3() takes columns; the push constants carry rows.
|
||||
mat3 R = transpose(mat3(pc.rot0.xyz, pc.rot1.xyz, pc.rot2.xyz));
|
||||
vec3 d = R * normalize(vec3(tan.x, -tan.y, -1.0));
|
||||
vec3 o = R * vec3((eye < 0.5 ? -1.0 : 1.0) * pc.rot0.w, 0.0, 0.0);
|
||||
if (d.z > -1e-4) return BACKDROP; // looking away from the screen
|
||||
float t = (-pc.rot1.w - o.z) / d.z;
|
||||
vec3 hit = o + d * t;
|
||||
float halfW = pc.rot2.w, halfH = halfW / pc.view.y;
|
||||
vec2 s = vec2(hit.x / halfW, -hit.y / halfH) * 0.5 + 0.5;
|
||||
if (any(lessThan(s, vec2(0.0))) || any(greaterThan(s, vec2(1.0)))) return BACKDROP;
|
||||
return texture(Source, s).rgb;
|
||||
}
|
||||
|
||||
void main() {
|
||||
float eye = uv.x < 0.5 ? 0.0 : 1.0;
|
||||
vec2 local = vec2(uv.x * 2.0 - eye, uv.y);
|
||||
// Lens centres sit inset towards the nose by view.x of a viewport.
|
||||
float cx = 0.5 + (eye < 0.5 ? pc.view.x : -pc.view.x);
|
||||
vec2 p = local - vec2(cx, 0.5);
|
||||
float tanH = pc.lens.z;
|
||||
vec2 t = vec2(p.x * pc.view.w, p.y) * 2.0 * tanH;
|
||||
|
||||
vec3 c;
|
||||
if (pc.lens.w > 0.0) {
|
||||
// Chromatic aberration: the lens bends red least and blue most; pre-spread to match.
|
||||
c.r = eyeSample(undistort(t, 1.0 - pc.lens.w), eye).r;
|
||||
c.g = eyeSample(undistort(t, 1.0), eye).g;
|
||||
c.b = eyeSample(undistort(t, 1.0 + pc.lens.w), eye).b;
|
||||
} else {
|
||||
c = eyeSample(undistort(t, 1.0), eye);
|
||||
}
|
||||
// Fade out towards each viewport's edge so the lens rim never shows a hard cut.
|
||||
vec2 e = min(local, 1.0 - local);
|
||||
float fade = smoothstep(0.0, 0.03, min(e.x * pc.view.w, e.y));
|
||||
outColor = vec4(c * fade, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#ifndef CARDBOARD_H
|
||||
#define CARDBOARD_H
|
||||
/*
|
||||
* Cardboard mode: the last stage of the compositor pass. The finished frame (after the effects and
|
||||
* frame generation) is drawn twice, once per eye, side by side on the panel, barrel-distorted for a
|
||||
* phone-in-a-viewer lens (cardboard.frag). The frame either hangs as a flat virtual screen in front
|
||||
* of the viewer, world-locked by the phone's rotation sensor (3DoF), or is already a side-by-side
|
||||
* stereo pair (SteamVR, SBS 3D content) that only gets the lens treatment.
|
||||
*
|
||||
* Present-pass order with Cardboard on (vk_present.c, render_impl):
|
||||
* scene -> effects -> frame generation -> vkp_cardboard_run (whole panel) -> 1:1 blit -> present
|
||||
* The Fullscreen Mode mapping does not apply: the pass fills the output itself.
|
||||
*
|
||||
* Settings and the head pose come from any thread (JNI, the sensor thread); the compositor thread
|
||||
* snapshots them per frame. A new pose redraws even a static scene (vkp_cardboard_pose_changed), so
|
||||
* the virtual screen stays put while the head turns.
|
||||
*/
|
||||
#define VK_USE_PLATFORM_ANDROID_KHR
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
enum { CARDBOARD_SOURCE_SCREEN = 0, CARDBOARD_SOURCE_SBS = 1 };
|
||||
|
||||
struct cardboard_params {
|
||||
int enabled;
|
||||
int source; /* CARDBOARD_SOURCE_* */
|
||||
float ipd_m; /* distance between the eyes, metres */
|
||||
float screen_dist_m; /* virtual screen distance, metres */
|
||||
float screen_width_m;/* virtual screen width, metres */
|
||||
float k1, k2; /* lens distortion coefficients */
|
||||
float fov_deg; /* vertical field of view of one eye before distortion */
|
||||
float lens_inset; /* lens centre inset towards the nose, fraction of an eye viewport */
|
||||
float chroma; /* chromatic aberration pre-correction (0 = off) */
|
||||
};
|
||||
|
||||
/* Any thread. Values are clamped to sane ranges. */
|
||||
void vkp_cardboard_set(const struct cardboard_params *p);
|
||||
/* Any thread: the head -> world rotation, row-major 3x3. Identity = looking straight at the screen.
|
||||
* live = a sensor produced it. Also published to the guest (headpose_shm.h) once a file is set. */
|
||||
void vkp_cardboard_set_pose(const float m[9], int live);
|
||||
/* Any thread, once: where the guest's copy of the pose lives (<files>/.wayland-rt/droiddeck-headpose). */
|
||||
void vkp_cardboard_set_pose_file(const char *path);
|
||||
|
||||
/* Compositor thread. */
|
||||
void vkp_cardboard_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops);
|
||||
/* 1 while Cardboard mode is on (the frame must take the compositor pass). */
|
||||
int vkp_cardboard_active(void);
|
||||
/* 1 when the settings or the pose changed since the last call: the caller redraws. */
|
||||
int vkp_cardboard_pose_changed(void);
|
||||
/* Called once per frame before any vkp_cardboard_run: releases the previous frame's source views
|
||||
* (that frame is fenced by now). */
|
||||
void vkp_cardboard_begin_frame(void);
|
||||
/* Records the pass into cmd: src (src_w x src_h, R8G8B8A8, in GENERAL) -> a panel-sized image
|
||||
* (out_w x out_h), returned in GENERAL. VK_NULL_HANDLE when the pass is unavailable (the caller
|
||||
* presents the frame the usual way). */
|
||||
VkImage vkp_cardboard_run(VkCommandBuffer cmd, VkImage src, int src_w, int src_h, int out_w, int out_h);
|
||||
|
||||
/* Pure helpers, shared with the host test (tools/tests). */
|
||||
void cardboard_clamp(struct cardboard_params *p);
|
||||
/* The 24 floats after the quad's ndc in the shader's push constants. */
|
||||
void cardboard_push_constants(const struct cardboard_params *p, const float pose[9],
|
||||
int src_w, int src_h, int out_w, int out_h, float out[24]);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,266 @@
|
||||
// 1116.2.0
|
||||
#pragma once
|
||||
const uint32_t cardboard_frag_code[] = {
|
||||
0x07230203,0x00010000,0x0008000b,0x0000016d,0x00000000,0x00020011,0x00000001,0x0006000b,
|
||||
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
|
||||
0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x000000ee,0x00000165,0x00030010,
|
||||
0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
|
||||
0x00000000,0x00070005,0x0000000d,0x69646e75,0x726f7473,0x66762874,0x31663b32,0x0000003b,
|
||||
0x00030005,0x0000000b,0x00000074,0x00040005,0x0000000c,0x6c616373,0x00000065,0x00070005,
|
||||
0x00000013,0x53657965,0x6c706d61,0x66762865,0x31663b32,0x0000003b,0x00030005,0x00000011,
|
||||
0x006e6174,0x00030005,0x00000012,0x00657965,0x00030005,0x00000015,0x00003272,0x00030005,
|
||||
0x0000001e,0x00004350,0x00040006,0x0000001e,0x00000000,0x0063646e,0x00050006,0x0000001e,
|
||||
0x00000001,0x30746f72,0x00000000,0x00050006,0x0000001e,0x00000002,0x31746f72,0x00000000,
|
||||
0x00050006,0x0000001e,0x00000003,0x32746f72,0x00000000,0x00050006,0x0000001e,0x00000004,
|
||||
0x736e656c,0x00000000,0x00050006,0x0000001e,0x00000005,0x77656976,0x00000000,0x00030005,
|
||||
0x00000020,0x00006370,0x00040005,0x0000003f,0x486e6174,0x00000000,0x00030005,0x00000042,
|
||||
0x00000073,0x00040005,0x00000068,0x72756f53,0x00006563,0x00030005,0x00000077,0x00000052,
|
||||
0x00030005,0x00000094,0x00000064,0x00030005,0x0000009f,0x0000006f,0x00030005,0x000000b3,
|
||||
0x00000074,0x00030005,0x000000bd,0x00746968,0x00040005,0x000000c3,0x666c6168,0x00000057,
|
||||
0x00040005,0x000000c6,0x666c6168,0x00000048,0x00030005,0x000000cb,0x00000073,0x00030005,
|
||||
0x000000ec,0x00657965,0x00030005,0x000000ee,0x00007675,0x00040005,0x000000f4,0x61636f6c,
|
||||
0x0000006c,0x00030005,0x000000fe,0x00007863,0x00030005,0x0000010c,0x00000070,0x00040005,
|
||||
0x00000111,0x486e6174,0x00000000,0x00030005,0x00000114,0x00000074,0x00030005,0x00000125,
|
||||
0x00000063,0x00040005,0x00000129,0x61726170,0x0000006d,0x00040005,0x0000012b,0x61726170,
|
||||
0x0000006d,0x00040005,0x0000012d,0x61726170,0x0000006d,0x00040005,0x0000012e,0x61726170,
|
||||
0x0000006d,0x00040005,0x00000133,0x61726170,0x0000006d,0x00040005,0x00000135,0x61726170,
|
||||
0x0000006d,0x00040005,0x00000137,0x61726170,0x0000006d,0x00040005,0x00000138,0x61726170,
|
||||
0x0000006d,0x00040005,0x00000140,0x61726170,0x0000006d,0x00040005,0x00000142,0x61726170,
|
||||
0x0000006d,0x00040005,0x00000144,0x61726170,0x0000006d,0x00040005,0x00000145,0x61726170,
|
||||
0x0000006d,0x00040005,0x0000014b,0x61726170,0x0000006d,0x00040005,0x0000014d,0x61726170,
|
||||
0x0000006d,0x00040005,0x0000014f,0x61726170,0x0000006d,0x00040005,0x00000150,0x61726170,
|
||||
0x0000006d,0x00030005,0x00000153,0x00000065,0x00040005,0x00000159,0x65646166,0x00000000,
|
||||
0x00050005,0x00000165,0x4374756f,0x726f6c6f,0x00000000,0x00030047,0x0000001e,0x00000002,
|
||||
0x00050048,0x0000001e,0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,0x00000001,
|
||||
0x00000023,0x00000010,0x00050048,0x0000001e,0x00000002,0x00000023,0x00000020,0x00050048,
|
||||
0x0000001e,0x00000003,0x00000023,0x00000030,0x00050048,0x0000001e,0x00000004,0x00000023,
|
||||
0x00000040,0x00050048,0x0000001e,0x00000005,0x00000023,0x00000050,0x00040047,0x00000068,
|
||||
0x00000021,0x00000000,0x00040047,0x00000068,0x00000022,0x00000000,0x00040047,0x000000ee,
|
||||
0x0000001e,0x00000000,0x00040047,0x00000165,0x0000001e,0x00000000,0x00020013,0x00000002,
|
||||
0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,
|
||||
0x00000006,0x00000002,0x00040020,0x00000008,0x00000007,0x00000007,0x00040020,0x00000009,
|
||||
0x00000007,0x00000006,0x00050021,0x0000000a,0x00000007,0x00000008,0x00000009,0x00040017,
|
||||
0x0000000f,0x00000006,0x00000003,0x00050021,0x00000010,0x0000000f,0x00000008,0x00000009,
|
||||
0x0004002b,0x00000006,0x0000001c,0x3f800000,0x00040017,0x0000001d,0x00000006,0x00000004,
|
||||
0x0008001e,0x0000001e,0x0000001d,0x0000001d,0x0000001d,0x0000001d,0x0000001d,0x0000001d,
|
||||
0x00040020,0x0000001f,0x00000009,0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,
|
||||
0x00040015,0x00000021,0x00000020,0x00000001,0x0004002b,0x00000021,0x00000022,0x00000004,
|
||||
0x00040015,0x00000023,0x00000020,0x00000000,0x0004002b,0x00000023,0x00000024,0x00000000,
|
||||
0x00040020,0x00000025,0x00000009,0x00000006,0x0004002b,0x00000023,0x0000002b,0x00000001,
|
||||
0x0004002b,0x00000021,0x00000036,0x00000005,0x0004002b,0x00000023,0x00000037,0x00000002,
|
||||
0x0004002b,0x00000006,0x0000003a,0x3f000000,0x00020014,0x0000003b,0x0004002b,0x00000023,
|
||||
0x00000046,0x00000003,0x0004002b,0x00000006,0x00000054,0x00000000,0x0005002c,0x00000007,
|
||||
0x00000055,0x00000054,0x00000054,0x00040017,0x00000056,0x0000003b,0x00000002,0x0005002c,
|
||||
0x00000007,0x0000005d,0x0000001c,0x0000001c,0x0006002c,0x0000000f,0x00000063,0x00000054,
|
||||
0x00000054,0x00000054,0x00090019,0x00000065,0x00000006,0x00000001,0x00000000,0x00000000,
|
||||
0x00000000,0x00000001,0x00000000,0x0003001b,0x00000066,0x00000065,0x00040020,0x00000067,
|
||||
0x00000000,0x00000066,0x0004003b,0x00000067,0x00000068,0x00000000,0x00040018,0x00000075,
|
||||
0x0000000f,0x00000003,0x00040020,0x00000076,0x00000007,0x00000075,0x0004002b,0x00000021,
|
||||
0x00000078,0x00000001,0x00040020,0x00000079,0x00000009,0x0000001d,0x0004002b,0x00000021,
|
||||
0x0000007d,0x00000002,0x0004002b,0x00000021,0x00000081,0x00000003,0x00040020,0x00000093,
|
||||
0x00000007,0x0000000f,0x0004002b,0x00000006,0x0000009b,0xbf800000,0x0004002b,0x00000006,
|
||||
0x000000ab,0xb8d1b717,0x0004002b,0x00000006,0x000000af,0x3c75c28f,0x0004002b,0x00000006,
|
||||
0x000000b0,0x3ca3d70a,0x0006002c,0x0000000f,0x000000b1,0x000000af,0x000000af,0x000000b0,
|
||||
0x00040020,0x000000ed,0x00000001,0x00000007,0x0004003b,0x000000ed,0x000000ee,0x00000001,
|
||||
0x00040020,0x000000ef,0x00000001,0x00000006,0x0004002b,0x00000006,0x000000f7,0x40000000,
|
||||
0x0004002b,0x00000006,0x0000015a,0x3cf5c28f,0x00040020,0x00000164,0x00000003,0x0000001d,
|
||||
0x0004003b,0x00000164,0x00000165,0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,
|
||||
0x00000003,0x000200f8,0x00000005,0x0004003b,0x00000009,0x000000ec,0x00000007,0x0004003b,
|
||||
0x00000008,0x000000f4,0x00000007,0x0004003b,0x00000009,0x000000fe,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000101,0x00000007,0x0004003b,0x00000008,0x0000010c,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000111,0x00000007,0x0004003b,0x00000008,0x00000114,0x00000007,0x0004003b,
|
||||
0x00000093,0x00000125,0x00000007,0x0004003b,0x00000008,0x00000129,0x00000007,0x0004003b,
|
||||
0x00000009,0x0000012b,0x00000007,0x0004003b,0x00000008,0x0000012d,0x00000007,0x0004003b,
|
||||
0x00000009,0x0000012e,0x00000007,0x0004003b,0x00000008,0x00000133,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000135,0x00000007,0x0004003b,0x00000008,0x00000137,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000138,0x00000007,0x0004003b,0x00000008,0x00000140,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000142,0x00000007,0x0004003b,0x00000008,0x00000144,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000145,0x00000007,0x0004003b,0x00000008,0x0000014b,0x00000007,0x0004003b,
|
||||
0x00000009,0x0000014d,0x00000007,0x0004003b,0x00000008,0x0000014f,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000150,0x00000007,0x0004003b,0x00000008,0x00000153,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000159,0x00000007,0x00050041,0x000000ef,0x000000f0,0x000000ee,0x00000024,
|
||||
0x0004003d,0x00000006,0x000000f1,0x000000f0,0x000500b8,0x0000003b,0x000000f2,0x000000f1,
|
||||
0x0000003a,0x000600a9,0x00000006,0x000000f3,0x000000f2,0x00000054,0x0000001c,0x0003003e,
|
||||
0x000000ec,0x000000f3,0x00050041,0x000000ef,0x000000f5,0x000000ee,0x00000024,0x0004003d,
|
||||
0x00000006,0x000000f6,0x000000f5,0x00050085,0x00000006,0x000000f8,0x000000f6,0x000000f7,
|
||||
0x0004003d,0x00000006,0x000000f9,0x000000ec,0x00050083,0x00000006,0x000000fa,0x000000f8,
|
||||
0x000000f9,0x00050041,0x000000ef,0x000000fb,0x000000ee,0x0000002b,0x0004003d,0x00000006,
|
||||
0x000000fc,0x000000fb,0x00050050,0x00000007,0x000000fd,0x000000fa,0x000000fc,0x0003003e,
|
||||
0x000000f4,0x000000fd,0x0004003d,0x00000006,0x000000ff,0x000000ec,0x000500b8,0x0000003b,
|
||||
0x00000100,0x000000ff,0x0000003a,0x000300f7,0x00000103,0x00000000,0x000400fa,0x00000100,
|
||||
0x00000102,0x00000106,0x000200f8,0x00000102,0x00060041,0x00000025,0x00000104,0x00000020,
|
||||
0x00000036,0x00000024,0x0004003d,0x00000006,0x00000105,0x00000104,0x0003003e,0x00000101,
|
||||
0x00000105,0x000200f9,0x00000103,0x000200f8,0x00000106,0x00060041,0x00000025,0x00000107,
|
||||
0x00000020,0x00000036,0x00000024,0x0004003d,0x00000006,0x00000108,0x00000107,0x0004007f,
|
||||
0x00000006,0x00000109,0x00000108,0x0003003e,0x00000101,0x00000109,0x000200f9,0x00000103,
|
||||
0x000200f8,0x00000103,0x0004003d,0x00000006,0x0000010a,0x00000101,0x00050081,0x00000006,
|
||||
0x0000010b,0x0000003a,0x0000010a,0x0003003e,0x000000fe,0x0000010b,0x0004003d,0x00000007,
|
||||
0x0000010d,0x000000f4,0x0004003d,0x00000006,0x0000010e,0x000000fe,0x00050050,0x00000007,
|
||||
0x0000010f,0x0000010e,0x0000003a,0x00050083,0x00000007,0x00000110,0x0000010d,0x0000010f,
|
||||
0x0003003e,0x0000010c,0x00000110,0x00060041,0x00000025,0x00000112,0x00000020,0x00000022,
|
||||
0x00000037,0x0004003d,0x00000006,0x00000113,0x00000112,0x0003003e,0x00000111,0x00000113,
|
||||
0x00050041,0x00000009,0x00000115,0x0000010c,0x00000024,0x0004003d,0x00000006,0x00000116,
|
||||
0x00000115,0x00060041,0x00000025,0x00000117,0x00000020,0x00000036,0x00000046,0x0004003d,
|
||||
0x00000006,0x00000118,0x00000117,0x00050085,0x00000006,0x00000119,0x00000116,0x00000118,
|
||||
0x00050041,0x00000009,0x0000011a,0x0000010c,0x0000002b,0x0004003d,0x00000006,0x0000011b,
|
||||
0x0000011a,0x00050050,0x00000007,0x0000011c,0x00000119,0x0000011b,0x0005008e,0x00000007,
|
||||
0x0000011d,0x0000011c,0x000000f7,0x0004003d,0x00000006,0x0000011e,0x00000111,0x0005008e,
|
||||
0x00000007,0x0000011f,0x0000011d,0x0000011e,0x0003003e,0x00000114,0x0000011f,0x00060041,
|
||||
0x00000025,0x00000120,0x00000020,0x00000022,0x00000046,0x0004003d,0x00000006,0x00000121,
|
||||
0x00000120,0x000500ba,0x0000003b,0x00000122,0x00000121,0x00000054,0x000300f7,0x00000124,
|
||||
0x00000000,0x000400fa,0x00000122,0x00000123,0x0000014a,0x000200f8,0x00000123,0x00060041,
|
||||
0x00000025,0x00000126,0x00000020,0x00000022,0x00000046,0x0004003d,0x00000006,0x00000127,
|
||||
0x00000126,0x00050083,0x00000006,0x00000128,0x0000001c,0x00000127,0x0004003d,0x00000007,
|
||||
0x0000012a,0x00000114,0x0003003e,0x00000129,0x0000012a,0x0003003e,0x0000012b,0x00000128,
|
||||
0x00060039,0x00000007,0x0000012c,0x0000000d,0x00000129,0x0000012b,0x0003003e,0x0000012d,
|
||||
0x0000012c,0x0004003d,0x00000006,0x0000012f,0x000000ec,0x0003003e,0x0000012e,0x0000012f,
|
||||
0x00060039,0x0000000f,0x00000130,0x00000013,0x0000012d,0x0000012e,0x00050051,0x00000006,
|
||||
0x00000131,0x00000130,0x00000000,0x00050041,0x00000009,0x00000132,0x00000125,0x00000024,
|
||||
0x0003003e,0x00000132,0x00000131,0x0004003d,0x00000007,0x00000134,0x00000114,0x0003003e,
|
||||
0x00000133,0x00000134,0x0003003e,0x00000135,0x0000001c,0x00060039,0x00000007,0x00000136,
|
||||
0x0000000d,0x00000133,0x00000135,0x0003003e,0x00000137,0x00000136,0x0004003d,0x00000006,
|
||||
0x00000139,0x000000ec,0x0003003e,0x00000138,0x00000139,0x00060039,0x0000000f,0x0000013a,
|
||||
0x00000013,0x00000137,0x00000138,0x00050051,0x00000006,0x0000013b,0x0000013a,0x00000001,
|
||||
0x00050041,0x00000009,0x0000013c,0x00000125,0x0000002b,0x0003003e,0x0000013c,0x0000013b,
|
||||
0x00060041,0x00000025,0x0000013d,0x00000020,0x00000022,0x00000046,0x0004003d,0x00000006,
|
||||
0x0000013e,0x0000013d,0x00050081,0x00000006,0x0000013f,0x0000001c,0x0000013e,0x0004003d,
|
||||
0x00000007,0x00000141,0x00000114,0x0003003e,0x00000140,0x00000141,0x0003003e,0x00000142,
|
||||
0x0000013f,0x00060039,0x00000007,0x00000143,0x0000000d,0x00000140,0x00000142,0x0003003e,
|
||||
0x00000144,0x00000143,0x0004003d,0x00000006,0x00000146,0x000000ec,0x0003003e,0x00000145,
|
||||
0x00000146,0x00060039,0x0000000f,0x00000147,0x00000013,0x00000144,0x00000145,0x00050051,
|
||||
0x00000006,0x00000148,0x00000147,0x00000002,0x00050041,0x00000009,0x00000149,0x00000125,
|
||||
0x00000037,0x0003003e,0x00000149,0x00000148,0x000200f9,0x00000124,0x000200f8,0x0000014a,
|
||||
0x0004003d,0x00000007,0x0000014c,0x00000114,0x0003003e,0x0000014b,0x0000014c,0x0003003e,
|
||||
0x0000014d,0x0000001c,0x00060039,0x00000007,0x0000014e,0x0000000d,0x0000014b,0x0000014d,
|
||||
0x0003003e,0x0000014f,0x0000014e,0x0004003d,0x00000006,0x00000151,0x000000ec,0x0003003e,
|
||||
0x00000150,0x00000151,0x00060039,0x0000000f,0x00000152,0x00000013,0x0000014f,0x00000150,
|
||||
0x0003003e,0x00000125,0x00000152,0x000200f9,0x00000124,0x000200f8,0x00000124,0x0004003d,
|
||||
0x00000007,0x00000154,0x000000f4,0x0004003d,0x00000007,0x00000155,0x000000f4,0x00050050,
|
||||
0x00000007,0x00000156,0x0000001c,0x0000001c,0x00050083,0x00000007,0x00000157,0x00000156,
|
||||
0x00000155,0x0007000c,0x00000007,0x00000158,0x00000001,0x00000025,0x00000154,0x00000157,
|
||||
0x0003003e,0x00000153,0x00000158,0x00050041,0x00000009,0x0000015b,0x00000153,0x00000024,
|
||||
0x0004003d,0x00000006,0x0000015c,0x0000015b,0x00060041,0x00000025,0x0000015d,0x00000020,
|
||||
0x00000036,0x00000046,0x0004003d,0x00000006,0x0000015e,0x0000015d,0x00050085,0x00000006,
|
||||
0x0000015f,0x0000015c,0x0000015e,0x00050041,0x00000009,0x00000160,0x00000153,0x0000002b,
|
||||
0x0004003d,0x00000006,0x00000161,0x00000160,0x0007000c,0x00000006,0x00000162,0x00000001,
|
||||
0x00000025,0x0000015f,0x00000161,0x0008000c,0x00000006,0x00000163,0x00000001,0x00000031,
|
||||
0x00000054,0x0000015a,0x00000162,0x0003003e,0x00000159,0x00000163,0x0004003d,0x0000000f,
|
||||
0x00000166,0x00000125,0x0004003d,0x00000006,0x00000167,0x00000159,0x0005008e,0x0000000f,
|
||||
0x00000168,0x00000166,0x00000167,0x00050051,0x00000006,0x00000169,0x00000168,0x00000000,
|
||||
0x00050051,0x00000006,0x0000016a,0x00000168,0x00000001,0x00050051,0x00000006,0x0000016b,
|
||||
0x00000168,0x00000002,0x00070050,0x0000001d,0x0000016c,0x00000169,0x0000016a,0x0000016b,
|
||||
0x0000001c,0x0003003e,0x00000165,0x0000016c,0x000100fd,0x00010038,0x00050036,0x00000007,
|
||||
0x0000000d,0x00000000,0x0000000a,0x00030037,0x00000008,0x0000000b,0x00030037,0x00000009,
|
||||
0x0000000c,0x000200f8,0x0000000e,0x0004003b,0x00000009,0x00000015,0x00000007,0x0004003d,
|
||||
0x00000007,0x00000016,0x0000000b,0x0004003d,0x00000007,0x00000017,0x0000000b,0x00050094,
|
||||
0x00000006,0x00000018,0x00000016,0x00000017,0x0003003e,0x00000015,0x00000018,0x0004003d,
|
||||
0x00000007,0x00000019,0x0000000b,0x0004003d,0x00000006,0x0000001a,0x0000000c,0x0005008e,
|
||||
0x00000007,0x0000001b,0x00000019,0x0000001a,0x00060041,0x00000025,0x00000026,0x00000020,
|
||||
0x00000022,0x00000024,0x0004003d,0x00000006,0x00000027,0x00000026,0x0004003d,0x00000006,
|
||||
0x00000028,0x00000015,0x00050085,0x00000006,0x00000029,0x00000027,0x00000028,0x00050081,
|
||||
0x00000006,0x0000002a,0x0000001c,0x00000029,0x00060041,0x00000025,0x0000002c,0x00000020,
|
||||
0x00000022,0x0000002b,0x0004003d,0x00000006,0x0000002d,0x0000002c,0x0004003d,0x00000006,
|
||||
0x0000002e,0x00000015,0x00050085,0x00000006,0x0000002f,0x0000002d,0x0000002e,0x0004003d,
|
||||
0x00000006,0x00000030,0x00000015,0x00050085,0x00000006,0x00000031,0x0000002f,0x00000030,
|
||||
0x00050081,0x00000006,0x00000032,0x0000002a,0x00000031,0x0005008e,0x00000007,0x00000033,
|
||||
0x0000001b,0x00000032,0x000200fe,0x00000033,0x00010038,0x00050036,0x0000000f,0x00000013,
|
||||
0x00000000,0x00000010,0x00030037,0x00000008,0x00000011,0x00030037,0x00000009,0x00000012,
|
||||
0x000200f8,0x00000014,0x0004003b,0x00000009,0x0000003f,0x00000007,0x0004003b,0x00000008,
|
||||
0x00000042,0x00000007,0x0004003b,0x00000076,0x00000077,0x00000007,0x0004003b,0x00000093,
|
||||
0x00000094,0x00000007,0x0004003b,0x00000093,0x0000009f,0x00000007,0x0004003b,0x00000009,
|
||||
0x000000b3,0x00000007,0x0004003b,0x00000093,0x000000bd,0x00000007,0x0004003b,0x00000009,
|
||||
0x000000c3,0x00000007,0x0004003b,0x00000009,0x000000c6,0x00000007,0x0004003b,0x00000008,
|
||||
0x000000cb,0x00000007,0x00060041,0x00000025,0x00000038,0x00000020,0x00000036,0x00000037,
|
||||
0x0004003d,0x00000006,0x00000039,0x00000038,0x000500ba,0x0000003b,0x0000003c,0x00000039,
|
||||
0x0000003a,0x000300f7,0x0000003e,0x00000000,0x000400fa,0x0000003c,0x0000003d,0x0000003e,
|
||||
0x000200f8,0x0000003d,0x00060041,0x00000025,0x00000040,0x00000020,0x00000022,0x00000037,
|
||||
0x0004003d,0x00000006,0x00000041,0x00000040,0x0003003e,0x0000003f,0x00000041,0x00050041,
|
||||
0x00000009,0x00000043,0x00000011,0x00000024,0x0004003d,0x00000006,0x00000044,0x00000043,
|
||||
0x0004003d,0x00000006,0x00000045,0x0000003f,0x00060041,0x00000025,0x00000047,0x00000020,
|
||||
0x00000036,0x00000046,0x0004003d,0x00000006,0x00000048,0x00000047,0x00050085,0x00000006,
|
||||
0x00000049,0x00000045,0x00000048,0x00050088,0x00000006,0x0000004a,0x00000044,0x00000049,
|
||||
0x00050041,0x00000009,0x0000004b,0x00000011,0x0000002b,0x0004003d,0x00000006,0x0000004c,
|
||||
0x0000004b,0x0004003d,0x00000006,0x0000004d,0x0000003f,0x00050088,0x00000006,0x0000004e,
|
||||
0x0000004c,0x0000004d,0x00050050,0x00000007,0x0000004f,0x0000004a,0x0000004e,0x0005008e,
|
||||
0x00000007,0x00000050,0x0000004f,0x0000003a,0x00050050,0x00000007,0x00000051,0x0000003a,
|
||||
0x0000003a,0x00050081,0x00000007,0x00000052,0x00000050,0x00000051,0x0003003e,0x00000042,
|
||||
0x00000052,0x0004003d,0x00000007,0x00000053,0x00000042,0x000500b8,0x00000056,0x00000057,
|
||||
0x00000053,0x00000055,0x0004009a,0x0000003b,0x00000058,0x00000057,0x000400a8,0x0000003b,
|
||||
0x00000059,0x00000058,0x000300f7,0x0000005b,0x00000000,0x000400fa,0x00000059,0x0000005a,
|
||||
0x0000005b,0x000200f8,0x0000005a,0x0004003d,0x00000007,0x0000005c,0x00000042,0x000500ba,
|
||||
0x00000056,0x0000005e,0x0000005c,0x0000005d,0x0004009a,0x0000003b,0x0000005f,0x0000005e,
|
||||
0x000200f9,0x0000005b,0x000200f8,0x0000005b,0x000700f5,0x0000003b,0x00000060,0x00000058,
|
||||
0x0000003d,0x0000005f,0x0000005a,0x000300f7,0x00000062,0x00000000,0x000400fa,0x00000060,
|
||||
0x00000061,0x00000062,0x000200f8,0x00000061,0x000200fe,0x00000063,0x000200f8,0x00000062,
|
||||
0x0004003d,0x00000066,0x00000069,0x00000068,0x00050041,0x00000009,0x0000006a,0x00000042,
|
||||
0x00000024,0x0004003d,0x00000006,0x0000006b,0x0000006a,0x0004003d,0x00000006,0x0000006c,
|
||||
0x00000012,0x00050081,0x00000006,0x0000006d,0x0000006b,0x0000006c,0x00050085,0x00000006,
|
||||
0x0000006e,0x0000006d,0x0000003a,0x00050041,0x00000009,0x0000006f,0x00000042,0x0000002b,
|
||||
0x0004003d,0x00000006,0x00000070,0x0000006f,0x00050050,0x00000007,0x00000071,0x0000006e,
|
||||
0x00000070,0x00050057,0x0000001d,0x00000072,0x00000069,0x00000071,0x0008004f,0x0000000f,
|
||||
0x00000073,0x00000072,0x00000072,0x00000000,0x00000001,0x00000002,0x000200fe,0x00000073,
|
||||
0x000200f8,0x0000003e,0x00050041,0x00000079,0x0000007a,0x00000020,0x00000078,0x0004003d,
|
||||
0x0000001d,0x0000007b,0x0000007a,0x0008004f,0x0000000f,0x0000007c,0x0000007b,0x0000007b,
|
||||
0x00000000,0x00000001,0x00000002,0x00050041,0x00000079,0x0000007e,0x00000020,0x0000007d,
|
||||
0x0004003d,0x0000001d,0x0000007f,0x0000007e,0x0008004f,0x0000000f,0x00000080,0x0000007f,
|
||||
0x0000007f,0x00000000,0x00000001,0x00000002,0x00050041,0x00000079,0x00000082,0x00000020,
|
||||
0x00000081,0x0004003d,0x0000001d,0x00000083,0x00000082,0x0008004f,0x0000000f,0x00000084,
|
||||
0x00000083,0x00000083,0x00000000,0x00000001,0x00000002,0x00050051,0x00000006,0x00000085,
|
||||
0x0000007c,0x00000000,0x00050051,0x00000006,0x00000086,0x0000007c,0x00000001,0x00050051,
|
||||
0x00000006,0x00000087,0x0000007c,0x00000002,0x00050051,0x00000006,0x00000088,0x00000080,
|
||||
0x00000000,0x00050051,0x00000006,0x00000089,0x00000080,0x00000001,0x00050051,0x00000006,
|
||||
0x0000008a,0x00000080,0x00000002,0x00050051,0x00000006,0x0000008b,0x00000084,0x00000000,
|
||||
0x00050051,0x00000006,0x0000008c,0x00000084,0x00000001,0x00050051,0x00000006,0x0000008d,
|
||||
0x00000084,0x00000002,0x00060050,0x0000000f,0x0000008e,0x00000085,0x00000086,0x00000087,
|
||||
0x00060050,0x0000000f,0x0000008f,0x00000088,0x00000089,0x0000008a,0x00060050,0x0000000f,
|
||||
0x00000090,0x0000008b,0x0000008c,0x0000008d,0x00060050,0x00000075,0x00000091,0x0000008e,
|
||||
0x0000008f,0x00000090,0x00040054,0x00000075,0x00000092,0x00000091,0x0003003e,0x00000077,
|
||||
0x00000092,0x0004003d,0x00000075,0x00000095,0x00000077,0x00050041,0x00000009,0x00000096,
|
||||
0x00000011,0x00000024,0x0004003d,0x00000006,0x00000097,0x00000096,0x00050041,0x00000009,
|
||||
0x00000098,0x00000011,0x0000002b,0x0004003d,0x00000006,0x00000099,0x00000098,0x0004007f,
|
||||
0x00000006,0x0000009a,0x00000099,0x00060050,0x0000000f,0x0000009c,0x00000097,0x0000009a,
|
||||
0x0000009b,0x0006000c,0x0000000f,0x0000009d,0x00000001,0x00000045,0x0000009c,0x00050091,
|
||||
0x0000000f,0x0000009e,0x00000095,0x0000009d,0x0003003e,0x00000094,0x0000009e,0x0004003d,
|
||||
0x00000075,0x000000a0,0x00000077,0x0004003d,0x00000006,0x000000a1,0x00000012,0x000500b8,
|
||||
0x0000003b,0x000000a2,0x000000a1,0x0000003a,0x000600a9,0x00000006,0x000000a3,0x000000a2,
|
||||
0x0000009b,0x0000001c,0x00060041,0x00000025,0x000000a4,0x00000020,0x00000078,0x00000046,
|
||||
0x0004003d,0x00000006,0x000000a5,0x000000a4,0x00050085,0x00000006,0x000000a6,0x000000a3,
|
||||
0x000000a5,0x00060050,0x0000000f,0x000000a7,0x000000a6,0x00000054,0x00000054,0x00050091,
|
||||
0x0000000f,0x000000a8,0x000000a0,0x000000a7,0x0003003e,0x0000009f,0x000000a8,0x00050041,
|
||||
0x00000009,0x000000a9,0x00000094,0x00000037,0x0004003d,0x00000006,0x000000aa,0x000000a9,
|
||||
0x000500ba,0x0000003b,0x000000ac,0x000000aa,0x000000ab,0x000300f7,0x000000ae,0x00000000,
|
||||
0x000400fa,0x000000ac,0x000000ad,0x000000ae,0x000200f8,0x000000ad,0x000200fe,0x000000b1,
|
||||
0x000200f8,0x000000ae,0x00060041,0x00000025,0x000000b4,0x00000020,0x0000007d,0x00000046,
|
||||
0x0004003d,0x00000006,0x000000b5,0x000000b4,0x0004007f,0x00000006,0x000000b6,0x000000b5,
|
||||
0x00050041,0x00000009,0x000000b7,0x0000009f,0x00000037,0x0004003d,0x00000006,0x000000b8,
|
||||
0x000000b7,0x00050083,0x00000006,0x000000b9,0x000000b6,0x000000b8,0x00050041,0x00000009,
|
||||
0x000000ba,0x00000094,0x00000037,0x0004003d,0x00000006,0x000000bb,0x000000ba,0x00050088,
|
||||
0x00000006,0x000000bc,0x000000b9,0x000000bb,0x0003003e,0x000000b3,0x000000bc,0x0004003d,
|
||||
0x0000000f,0x000000be,0x0000009f,0x0004003d,0x0000000f,0x000000bf,0x00000094,0x0004003d,
|
||||
0x00000006,0x000000c0,0x000000b3,0x0005008e,0x0000000f,0x000000c1,0x000000bf,0x000000c0,
|
||||
0x00050081,0x0000000f,0x000000c2,0x000000be,0x000000c1,0x0003003e,0x000000bd,0x000000c2,
|
||||
0x00060041,0x00000025,0x000000c4,0x00000020,0x00000081,0x00000046,0x0004003d,0x00000006,
|
||||
0x000000c5,0x000000c4,0x0003003e,0x000000c3,0x000000c5,0x0004003d,0x00000006,0x000000c7,
|
||||
0x000000c3,0x00060041,0x00000025,0x000000c8,0x00000020,0x00000036,0x0000002b,0x0004003d,
|
||||
0x00000006,0x000000c9,0x000000c8,0x00050088,0x00000006,0x000000ca,0x000000c7,0x000000c9,
|
||||
0x0003003e,0x000000c6,0x000000ca,0x00050041,0x00000009,0x000000cc,0x000000bd,0x00000024,
|
||||
0x0004003d,0x00000006,0x000000cd,0x000000cc,0x0004003d,0x00000006,0x000000ce,0x000000c3,
|
||||
0x00050088,0x00000006,0x000000cf,0x000000cd,0x000000ce,0x00050041,0x00000009,0x000000d0,
|
||||
0x000000bd,0x0000002b,0x0004003d,0x00000006,0x000000d1,0x000000d0,0x0004007f,0x00000006,
|
||||
0x000000d2,0x000000d1,0x0004003d,0x00000006,0x000000d3,0x000000c6,0x00050088,0x00000006,
|
||||
0x000000d4,0x000000d2,0x000000d3,0x00050050,0x00000007,0x000000d5,0x000000cf,0x000000d4,
|
||||
0x0005008e,0x00000007,0x000000d6,0x000000d5,0x0000003a,0x00050050,0x00000007,0x000000d7,
|
||||
0x0000003a,0x0000003a,0x00050081,0x00000007,0x000000d8,0x000000d6,0x000000d7,0x0003003e,
|
||||
0x000000cb,0x000000d8,0x0004003d,0x00000007,0x000000d9,0x000000cb,0x000500b8,0x00000056,
|
||||
0x000000da,0x000000d9,0x00000055,0x0004009a,0x0000003b,0x000000db,0x000000da,0x000400a8,
|
||||
0x0000003b,0x000000dc,0x000000db,0x000300f7,0x000000de,0x00000000,0x000400fa,0x000000dc,
|
||||
0x000000dd,0x000000de,0x000200f8,0x000000dd,0x0004003d,0x00000007,0x000000df,0x000000cb,
|
||||
0x000500ba,0x00000056,0x000000e0,0x000000df,0x0000005d,0x0004009a,0x0000003b,0x000000e1,
|
||||
0x000000e0,0x000200f9,0x000000de,0x000200f8,0x000000de,0x000700f5,0x0000003b,0x000000e2,
|
||||
0x000000db,0x000000ae,0x000000e1,0x000000dd,0x000300f7,0x000000e4,0x00000000,0x000400fa,
|
||||
0x000000e2,0x000000e3,0x000000e4,0x000200f8,0x000000e3,0x000200fe,0x000000b1,0x000200f8,
|
||||
0x000000e4,0x0004003d,0x00000066,0x000000e6,0x00000068,0x0004003d,0x00000007,0x000000e7,
|
||||
0x000000cb,0x00050057,0x0000001d,0x000000e8,0x000000e6,0x000000e7,0x0008004f,0x0000000f,
|
||||
0x000000e9,0x000000e8,0x000000e8,0x00000000,0x00000001,0x00000002,0x000200fe,0x000000e9,
|
||||
0x00010038
|
||||
};
|
||||
@@ -50,6 +50,7 @@
|
||||
#include "framegen_bridge.h"
|
||||
#include <pthread.h>
|
||||
#include "effects_chain.h"
|
||||
#include "cardboard.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "droiddeck_color.h"
|
||||
#include "compositor_internal.h"
|
||||
@@ -260,6 +261,7 @@ struct surface {
|
||||
/* Toplevel placement on the scene. */
|
||||
int mapped; /* in g_toplevels */
|
||||
struct wl_list toplevel_link;
|
||||
int keep_on_top; /* Cardboard mode's SteamVR window: above every other toplevel (raise_kept_on_top) */
|
||||
int x, y, placed;
|
||||
uint32_t hwnd;
|
||||
|
||||
@@ -291,6 +293,7 @@ static struct wl_event_source *g_render_idle, *g_frame_timer;
|
||||
* window) a fallback timer renders instead. */
|
||||
static int g_dirty; /* something changed since the last render */
|
||||
static int64_t g_last_vsync_ns; /* last tick, 0 = none yet */
|
||||
static int64_t g_tick_vsync_ns; /* the vsync that tick is for (Choreographer's frame time) */
|
||||
static int64_t g_refresh_ns = 16666667; /* measured tick interval (pacing only, never reported) */
|
||||
static struct wl_event_source *g_fallback_timer;
|
||||
static int g_fallback_armed;
|
||||
@@ -631,6 +634,8 @@ static struct surface *toplevel_by_hwnd(uint32_t hwnd) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void raise_kept_on_top(void);
|
||||
|
||||
/* Reorder the mapped toplevels to match the last reported Windows z-order. Windows the
|
||||
* report doesn't mention keep their relative order below the ones it does. */
|
||||
static void apply_zorder(void) {
|
||||
@@ -640,6 +645,17 @@ static void apply_zorder(void) {
|
||||
wl_list_remove(&s->toplevel_link);
|
||||
wl_list_insert(g_toplevels.prev, &s->toplevel_link);
|
||||
}
|
||||
raise_kept_on_top();
|
||||
}
|
||||
|
||||
/* Windows marked keep_on_top go back to the top of the stack (the end of g_toplevels). */
|
||||
static void raise_kept_on_top(void) {
|
||||
struct surface *s, *tmp, *kept[4];
|
||||
int n = 0;
|
||||
wl_list_for_each_safe(s, tmp, &g_toplevels, toplevel_link) {
|
||||
if (s->keep_on_top && n < 4) { wl_list_remove(&s->toplevel_link); kept[n++] = s; }
|
||||
}
|
||||
for (int i = 0; i < n; i++) wl_list_insert(g_toplevels.prev, &kept[i]->toplevel_link);
|
||||
}
|
||||
|
||||
static void map_toplevel(struct surface *s) {
|
||||
@@ -654,6 +670,7 @@ static void map_toplevel(struct surface *s) {
|
||||
s->placed ? "" : " (no desktop position yet)");
|
||||
}
|
||||
wl_list_insert(g_toplevels.prev, &s->toplevel_link); /* new windows start on top */
|
||||
raise_kept_on_top();
|
||||
/* Without a Wine desktop the clients are whole programs (the Linux desktop, a gamescope a
|
||||
* program on it started over it): a window that opens on top takes the keys too, as it would
|
||||
* on any desktop, rather than the one clicked last that is now underneath it. */
|
||||
@@ -763,8 +780,11 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
|
||||
/* The window the app's performance HUD follows: the latest one at least as big as the last to
|
||||
* start presenting GPU frames (take_dmabuf) (X11 binds the HUD to the _MESA_DRV window and counts X presents instead). JNI upcalls. */
|
||||
static struct surface *g_hud_surface;
|
||||
/* When the HUD's window last presented a frame (now_ns), to let a replacement take over. */
|
||||
static int64_t g_hud_last_ns;
|
||||
/* When the HUD's window last presented a new frame (now_ns), and when it last committed at all,
|
||||
* a repeat of the frame it shows included. A replacement may take over only once it has gone
|
||||
* quiet in the second sense: gamescope repeats a paused game's frame under a busy overlay, and
|
||||
* that overlay must not become the game. */
|
||||
static int64_t g_hud_last_ns, g_hud_alive_ns;
|
||||
/* That window committed a frame the screen has not drawn yet. */
|
||||
static int g_hud_fresh;
|
||||
extern void droiddeck_on_game_surface(const char *window, const char *gpu); /* window NULL = gone */
|
||||
@@ -774,7 +794,14 @@ extern void droiddeck_on_game_frame(void);
|
||||
extern void droiddeck_on_game_program(int pid, const char *program);
|
||||
|
||||
static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) {
|
||||
if (s->dmabuf != buffer || s->dmabuf_buf != b) {
|
||||
/* The buffer this surface already shows, committed again. Gamescope's Wayland backend attaches
|
||||
* every plane on every frame it outputs, so its game plane comes back unchanged whenever only
|
||||
* something above it moved (MangoHud's graph, Steam's overlay). The surface still holds it and
|
||||
* never released it, so the client cannot have drawn into it: it is no new frame. Counted as
|
||||
* one, a game capped at 30 read 50-60 fps in the HUD, and frame generation took those repeats
|
||||
* as source frames ("LSFG 2x 59 -> 54" instead of 30 -> 60). */
|
||||
const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b;
|
||||
if (!repeat) {
|
||||
drop_dmabuf(s, 1);
|
||||
s->dmabuf = buffer;
|
||||
s->dmabuf_buf = b;
|
||||
@@ -809,7 +836,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
s->buf_h = b->height;
|
||||
s->buf_alpha = (b->format & 0xff) == 'A';
|
||||
s->has_content = b->img != NULL;
|
||||
g_stat_dmabuf++;
|
||||
if (!repeat) g_stat_dmabuf++;
|
||||
const int announced_now = !s->announced_vulkan;
|
||||
if (!s->announced_vulkan) {
|
||||
char name[160];
|
||||
@@ -840,7 +867,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
* full-screen gamescope over the desktop still does), and a window gone quiet for a second
|
||||
* gives way to whatever draws next. */
|
||||
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
|
||||
(!g_hud_surface || now_ns() - g_hud_last_ns > 1000000000LL ||
|
||||
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL ||
|
||||
(announced_now && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||
char name[160];
|
||||
describe(s, name, sizeof(name));
|
||||
@@ -869,7 +896,10 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
* Asking whether the compositor could import it, as this used to, is a question about the
|
||||
* copy path and not about whether a frame happened: a game whose buffers go straight to
|
||||
* the display layer draws on screen while the counter sat at 0.0 fps and 1000.0 ms. */
|
||||
if (s == g_hud_surface) { g_hud_last_ns = now_ns(); g_hud_fresh = 1; droiddeck_on_game_frame(); }
|
||||
if (s == g_hud_surface) {
|
||||
g_hud_alive_ns = now_ns();
|
||||
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; droiddeck_on_game_frame(); }
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- hooks for ahb_swapchain.c (zero-copy layers) */
|
||||
@@ -933,6 +963,20 @@ static uint32_t nominal_refresh_ns(void) {
|
||||
return (uint32_t)(1000000000000LL / (int64_t)mhz);
|
||||
}
|
||||
|
||||
/* The vblank a scene drawn at render_ns belongs to, for wp_presentation: the vsync of the tick that
|
||||
* drew it (Choreographer's frame time). Gamescope's Wayland backend anchors its vblank clock to this
|
||||
* and wakes a red zone before the next refresh. Reporting the end of the render instead (a few ms
|
||||
* past the tick) put its wakeups on top of the next tick: some frames missed it and showed twice,
|
||||
* others were replaced before they were shown (a 60 Hz Thor got ~50 distinct frames a second from
|
||||
* gamescope). Not the refresh after it either: gamescope then wakes a whole refresh late and runs
|
||||
* at half rate. Without a fresh tick (the fallback timer) it is the render time. */
|
||||
static int64_t presented_ns(int64_t render_ns) {
|
||||
if (!g_tick_vsync_ns || render_ns - g_last_vsync_ns > (int64_t)nominal_refresh_ns() ||
|
||||
render_ns < g_tick_vsync_ns)
|
||||
return render_ns;
|
||||
return g_tick_vsync_ns;
|
||||
}
|
||||
|
||||
static void feedback_present_all(struct wl_list *list, int64_t t) {
|
||||
struct wl_resource *fb, *tmp;
|
||||
uint64_t sec = (uint64_t)(t / 1000000000LL);
|
||||
@@ -1458,7 +1502,13 @@ static void xdg_toplevel_set_title(struct wl_client *c, struct wl_resource *r, c
|
||||
droiddeck_log("window", "renamed %s -> %s", before, after);
|
||||
}
|
||||
}
|
||||
static void xdg_toplevel_set_app_id(struct wl_client *c, struct wl_resource *r, const char *id) {}
|
||||
static void xdg_toplevel_set_app_id(struct wl_client *c, struct wl_resource *r, const char *id) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
/* Cardboard mode's SteamVR window (tools/vr/src/presenter.cpp) stays above every other window,
|
||||
* gamescope's included: gamescope reopens its window when Steam notices VR, and a reopened window
|
||||
* would otherwise come up over it (new windows start on top). */
|
||||
if (s && id && !strcmp(id, "droiddeck-cardboard-vr")) s->keep_on_top = 1;
|
||||
}
|
||||
static void xdg_toplevel_show_menu(struct wl_client *c, struct wl_resource *r, struct wl_resource *seat,
|
||||
uint32_t serial, int32_t x, int32_t y) {}
|
||||
static void xdg_toplevel_move(struct wl_client *c, struct wl_resource *r, struct wl_resource *seat,
|
||||
@@ -2071,6 +2121,8 @@ static void render_scene(void) {
|
||||
int rendered = 0;
|
||||
int fx_on = vkp_effects_active();
|
||||
int framegen = vkp_framegen_active();
|
||||
/* Cardboard mode draws the whole panel itself, so the game never gets a display layer of its own. */
|
||||
const int cardboard = vkp_cardboard_active();
|
||||
/* HDR (see hdr_plan): route 0 = the old paths below; 1 / 2 = composed; 3 = layer only, effects and
|
||||
* frame generation skipped. Always 0 while the HDR gate is closed: nothing changes for that session. */
|
||||
struct hdr_scene hs;
|
||||
@@ -2117,7 +2169,7 @@ static void render_scene(void) {
|
||||
* - screen effects DO when a window is drawn above the game: the chain has to see the whole
|
||||
* scene to look the way it does on the copy path, and here the game is only part of it. */
|
||||
const int pass_on = fx_on || framegen;
|
||||
int li = (g_zero_copy && !framegen) ? layer_candidate(&dl, w, h) : -1;
|
||||
int li = (g_zero_copy && !framegen && !cardboard) ? layer_candidate(&dl, w, h) : -1;
|
||||
int over = li >= 0 ? dl.n - 1 - li : 0; /* draws above the fullscreen game (0 or 1) */
|
||||
const int fx_blocks = (li >= 0 && fx_on && over > 0);
|
||||
if (fx_blocks) { li = -1; over = 0; }
|
||||
@@ -2147,6 +2199,7 @@ static void render_scene(void) {
|
||||
/* HDR: the same, for a game's SUBSURFACE swapchain whose 10-bit frame the compositor could not
|
||||
* import (NULL whenever the HDR gate is closed - nothing is ever noted then). */
|
||||
if (li < 0 && !ls) ls = hdr_unimported_fullscreen(&dl, w, h);
|
||||
if (cardboard) ls = NULL;
|
||||
if (ls && pass_on && li < 0 && !g_zero_copy_fx_skip_said) {
|
||||
g_zero_copy_fx_skip_said = 1;
|
||||
droiddeck_log(framegen ? "framegen" : "effects",
|
||||
@@ -2218,7 +2271,7 @@ static void render_scene(void) {
|
||||
free(hs.is_hdr);
|
||||
if (hdr_copy && rendered && droiddeck_color_hdr_open()) hdr_count_copied(&dl, hdr_copy);
|
||||
if (rendered) {
|
||||
int64_t t = now_ns();
|
||||
int64_t t = presented_ns(t_scene);
|
||||
g_stat_frames++;
|
||||
/* A surface outside the scene (role-less, not placed yet, a hidden helper window such
|
||||
* as wined3d's device window) was not shown, so its feedback is discarded rather than
|
||||
@@ -2283,12 +2336,14 @@ static void on_vsync(int64_t frame_time_ns) {
|
||||
if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8;
|
||||
}
|
||||
g_last_vsync_ns = now;
|
||||
(void)frame_time_ns;
|
||||
g_tick_vsync_ns = frame_time_ns;
|
||||
/* The app's surface may have been replaced or taken away since the last frame: apply that now
|
||||
* (the app never waits for us), and redraw the scene onto a new one. */
|
||||
if (vkp_apply_window_request()) g_dirty = 1;
|
||||
/* A screen-effect setting changed (JNI, any thread): redraw so it shows on a static scene too. */
|
||||
if (vkp_effects_sync()) g_dirty = 1;
|
||||
/* Cardboard mode: a new head pose (or setting) moves the virtual screen, static scene or not. */
|
||||
if (vkp_cardboard_pose_changed()) g_dirty = 1;
|
||||
if (g_dirty && !scene_waits_for_game(now)) render_scene();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef HEADPOSE_SHM_H
|
||||
#define HEADPOSE_SHM_H
|
||||
/*
|
||||
* The head pose Cardboard mode tracks, shared with the guest: a 128-byte file the compositor maps
|
||||
* at <files>/.wayland-rt/droiddeck-headpose, which the guest sees as /run/droiddeck/droiddeck-headpose.
|
||||
* Written by the app (cardboard.c) at the sensor's rate; read by guest VR code (the SteamVR driver in
|
||||
* tools/vr) without any call into the app.
|
||||
*
|
||||
* Seqlock: the writer makes seq odd, writes the rest, then makes it even again. A reader copies the
|
||||
* struct and keeps the copy only if seq was even and unchanged across the copy.
|
||||
*
|
||||
* Axes are OpenVR's (and the cardboard shader's): x right, y up, z back (-z is straight ahead).
|
||||
* rot maps head directions to the recentred world, row-major. time_ns is CLOCK_MONOTONIC, the same
|
||||
* clock inside the guest (one kernel).
|
||||
*/
|
||||
#include <stdint.h>
|
||||
|
||||
#define DROIDDECK_HEADPOSE_MAGIC 0x50484444u /* "DDHP" */
|
||||
#define DROIDDECK_HEADPOSE_VERSION 1u
|
||||
#define DROIDDECK_HEADPOSE_FILE "droiddeck-headpose"
|
||||
|
||||
enum {
|
||||
DROIDDECK_HEADPOSE_LIVE = 1u << 0, /* a rotation sensor is feeding it (else identity) */
|
||||
DROIDDECK_HEADPOSE_ENABLED = 1u << 1, /* Cardboard mode is on */
|
||||
};
|
||||
|
||||
struct droiddeck_headpose {
|
||||
uint32_t magic;
|
||||
uint32_t version;
|
||||
uint32_t seq;
|
||||
uint32_t flags;
|
||||
float rot[9];
|
||||
float ipd_m;
|
||||
int64_t time_ns;
|
||||
/* What the lens pass expects of a side-by-side source, so a VR renderer can match it: one eye's
|
||||
* half of the frame covers tan_half_fov up and down and eye_aspect times that left and right. */
|
||||
float tan_half_fov;
|
||||
float eye_aspect;
|
||||
uint32_t eye_w, eye_h; /* one eye's viewport on the panel, pixels (0 = not drawn yet) */
|
||||
uint32_t reserved[12];
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
static_assert(sizeof(struct droiddeck_headpose) == 128, "headpose layout");
|
||||
#else
|
||||
_Static_assert(sizeof(struct droiddeck_headpose) == 128, "headpose layout");
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "vk_loader.h"
|
||||
#include "sc_layer.h"
|
||||
#include "effects_chain.h"
|
||||
#include "cardboard.h"
|
||||
#include "framegen_bridge.h"
|
||||
#include "hdr_compose.h"
|
||||
#include "blend_pass.h"
|
||||
@@ -541,6 +542,7 @@ static int dev_init(void) {
|
||||
g_vk.CreateFence(g_dev, &fci, NULL, &g_fence);
|
||||
|
||||
vkp_effects_bind_device(g_dev, g_pd, &g_memprops);
|
||||
vkp_cardboard_bind_device(g_dev, &g_memprops);
|
||||
hdrc_bind_device(g_dev, &g_memprops);
|
||||
blendp_bind_device(g_dev);
|
||||
g_dev_state = 1;
|
||||
@@ -1342,8 +1344,28 @@ static const char *vk_result_name(VkResult r) {
|
||||
* standing for the whole scene) through the scene -> output mapping, and leave the image ready
|
||||
* to present. */
|
||||
static void record_screen_blit(VkCommandBuffer cmd, VkImage src, int src_w, int src_h,
|
||||
int scene_w, int scene_h, uint32_t img, VkFilter filter) {
|
||||
int scene_w, int scene_h, uint32_t img, VkFilter filter, int cardboard) {
|
||||
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||
/* Cardboard mode (cardboard.h): the pass turns src into the two eye views over the whole panel,
|
||||
* and that image is blitted 1:1 instead of src going through the scene mapping. */
|
||||
int direct = 0;
|
||||
if (cardboard) {
|
||||
VkImageMemoryBarrier rd = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src, .subresourceRange = range,
|
||||
.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT, .dstAccessMask = VK_ACCESS_SHADER_READ_BIT};
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
|
||||
0, 0, NULL, 0, NULL, 1, &rd);
|
||||
VkImage eyes = vkp_cardboard_run(cmd, src, src_w, src_h, (int)g_extent.width, (int)g_extent.height);
|
||||
if (eyes) {
|
||||
src = eyes;
|
||||
src_w = (int)g_extent.width;
|
||||
src_h = (int)g_extent.height;
|
||||
direct = 1;
|
||||
}
|
||||
}
|
||||
VkImageMemoryBarrier pre[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
@@ -1361,7 +1383,12 @@ static void record_screen_blit(VkCommandBuffer cmd, VkImage src, int src_w, int
|
||||
struct vkp_image tmp = {.w = src_w, .h = src_h}; /* only its size is looked at */
|
||||
struct vkp_draw d = {&tmp, 0, 0, (float)src_w, (float)src_h, 0, 0, scene_w, scene_h};
|
||||
VkImageBlit blit;
|
||||
const int have_blit = draw_to_blit(&d, &blit);
|
||||
const int have_blit = direct ? 1 : draw_to_blit(&d, &blit);
|
||||
if (direct)
|
||||
blit = (VkImageBlit){.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.srcOffsets = {{0, 0, 0}, {src_w, src_h, 1}},
|
||||
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.dstOffsets = {{0, 0, 0}, {src_w, src_h, 1}}};
|
||||
/* The result fills its whole mapped rectangle, so only the letterbox bars around it need black. */
|
||||
if (!have_blit || !record_bars_clear(cmd, g_images[img], &blit)) {
|
||||
VkClearColorValue black = {.float32 = {0.0f, 0.0f, 0.0f, 1.0f}};
|
||||
@@ -1571,6 +1598,15 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
* blit filter follows the scaling mode. */
|
||||
const int fx = !g_plain_frame && vkp_effects_active();
|
||||
const int fg = !g_plain_frame && vkp_framegen_active();
|
||||
/* Cardboard mode needs the whole frame too; it works on the 8-bit picture only (an HDR frame
|
||||
* is shown flat, said once). */
|
||||
int cb = !g_plain_frame && vkp_cardboard_active();
|
||||
if (cb && hf) {
|
||||
static int said;
|
||||
if (!said) { said = 1; droiddeck_log("cardboard", "HDR frames are shown flat: the cardboard pass is 8-bit only"); }
|
||||
cb = 0;
|
||||
}
|
||||
vkp_cardboard_begin_frame();
|
||||
/* HDR frames with frame generation through an HDR10 swapchain: the scene, the effects and the
|
||||
* engine's frames in FP16 (FG_HDR_FMT) where the engine can take that format - more than 8 bits of
|
||||
* PQ through interpolation - else the 8-bit scene, as before. */
|
||||
@@ -1594,7 +1630,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
}
|
||||
}
|
||||
/* An HDR scene always takes the pass: its draws are composed into one encoding first. */
|
||||
const int pass = deep || ((fx || fg || (hf && n > 0)) && ensure_scene_image(scene_w, scene_h) == 0);
|
||||
const int pass = deep || ((fx || fg || cb || (hf && n > 0)) && ensure_scene_image(scene_w, scene_h) == 0);
|
||||
VkImage scene_img = deep ? g_fgscene.img : g_scene.img;
|
||||
const VkFormat scene_fmt = deep ? FG_HDR_FMT : SCENE_FMT;
|
||||
const VkFilter blit_filter = vkp_effects_blit_filter();
|
||||
@@ -1746,7 +1782,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
}
|
||||
|
||||
/* 4. Mapping/blit: the first present carries generated frame 0, or the result itself. */
|
||||
record_screen_blit(cmd, ngen ? gens[0] : result, rw, rh, scene_w, scene_h, img, blit_filter);
|
||||
record_screen_blit(cmd, ngen ? gens[0] : result, rw, rh, scene_w, scene_h, img, blit_filter, cb);
|
||||
}
|
||||
g_vk.EndCommandBuffer(cmd);
|
||||
|
||||
@@ -1770,7 +1806,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
VkCommandBuffer ck = g_cmds[k];
|
||||
g_vk.ResetCommandBuffer(ck, 0);
|
||||
g_vk.BeginCommandBuffer(ck, &bi);
|
||||
record_screen_blit(ck, k < ngen ? gens[k] : result, rw, rh, scene_w, scene_h, img, blit_filter);
|
||||
record_screen_blit(ck, k < ngen ? gens[k] : result, rw, rh, scene_w, scene_h, img, blit_filter, cb);
|
||||
g_vk.EndCommandBuffer(ck);
|
||||
}
|
||||
const int last = (k + 1 == presents);
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#include "ahb_swapchain.h"
|
||||
#include "sc_layer.h"
|
||||
#include "effects_chain.h"
|
||||
#include "cardboard.h"
|
||||
#include "droiddeck_color.h"
|
||||
|
||||
extern int droiddeck_wayland_run(void);
|
||||
@@ -463,6 +464,36 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetScreenEffects(JNI
|
||||
vkp_effects_set_screen(brightness, contrast, gamma, saturation, fxaa ? 1 : 0, toon ? 1 : 0, crt ? 1 : 0, ntsc ? 1 : 0);
|
||||
}
|
||||
|
||||
/* Cardboard mode - WaylandCompositor.nativeSetCardboard. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboard(JNIEnv *env, jclass clazz, jboolean enabled,
|
||||
jint source, jfloat ipd, jfloat dist, jfloat width, jfloat k1, jfloat k2, jfloat fov, jfloat inset, jfloat chroma) {
|
||||
struct cardboard_params p = {.enabled = enabled ? 1 : 0, .source = source, .ipd_m = ipd, .screen_dist_m = dist,
|
||||
.screen_width_m = width, .k1 = k1, .k2 = k2, .fov_deg = fov, .lens_inset = inset,
|
||||
.chroma = chroma};
|
||||
vkp_cardboard_set(&p);
|
||||
}
|
||||
|
||||
/* The head pose (row-major 3x3, head -> world), from the sensor thread. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardPose(JNIEnv *env, jclass clazz, jfloatArray rot,
|
||||
jboolean live) {
|
||||
float m[9];
|
||||
if (!rot || (*env)->GetArrayLength(env, rot) < 9) return;
|
||||
(*env)->GetFloatArrayRegion(env, rot, 0, 9, m);
|
||||
vkp_cardboard_set_pose(m, live ? 1 : 0);
|
||||
}
|
||||
|
||||
/* Where the head pose is shared with the guest - WaylandCompositor.nativeSetCardboardPoseFile. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardPoseFile(JNIEnv *env, jclass clazz, jstring path) {
|
||||
if (!path) return;
|
||||
const char *p = (*env)->GetStringUTFChars(env, path, NULL);
|
||||
if (!p) return;
|
||||
vkp_cardboard_set_pose_file(p);
|
||||
(*env)->ReleaseStringUTFChars(env, path, p);
|
||||
}
|
||||
|
||||
/* One "display" line in the session log, written from Java: facts that live in the Android
|
||||
* framework (the panel's HDR capability) rather than in the compositor. droiddeck_log() mirrors to
|
||||
* logcat and appends to the session file when one is open, so this is safe at any point. */
|
||||
|
||||
@@ -116,6 +116,7 @@ class MainActivity : ComponentActivity() {
|
||||
private var frameGenLabel by mutableStateOf("")
|
||||
private var lossless by mutableStateOf(Lossless.State.NONE)
|
||||
private var showRemove by mutableStateOf(false)
|
||||
private var showResetSettings by mutableStateOf(false)
|
||||
private var showNonAdreno by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
|
||||
private var glThread by mutableStateOf(true)
|
||||
private var noGlError by mutableStateOf(true)
|
||||
@@ -350,6 +351,8 @@ class MainActivity : ComponentActivity() {
|
||||
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var steamDownloadsInBackground by mutableStateOf(false)
|
||||
private var zramCompression by mutableStateOf(false)
|
||||
private var zramSupported by mutableStateOf<Boolean?>(null)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var gameStorage by mutableStateOf("")
|
||||
@@ -725,6 +728,10 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}, "clear-logs").start()
|
||||
},
|
||||
onResetSettings = {
|
||||
if (SessionState.running) android.widget.Toast.makeText(this, R.string.setup_reset_settings_session_running, android.widget.Toast.LENGTH_LONG).show()
|
||||
else showResetSettings = true
|
||||
},
|
||||
onOffline = {
|
||||
OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
|
||||
offline = OfflineMode.enabled(this)
|
||||
@@ -870,6 +877,10 @@ class MainActivity : ComponentActivity() {
|
||||
onConfirm = { showRemove = false; removeRuntime() },
|
||||
onDismiss = { showRemove = false },
|
||||
)
|
||||
if (showResetSettings) com.droiddeck.launcher.ui.ResetSettingsDialog(
|
||||
onConfirm = { gameProfiles -> resetSettings(gameProfiles) },
|
||||
onDismiss = { showResetSettings = false },
|
||||
)
|
||||
flood?.let { f -> com.droiddeck.launcher.ui.LaunchFlood(f.from, onProgress = { floodProgress = it }) { launchFlooded(f) } }
|
||||
returning?.let { r ->
|
||||
com.droiddeck.launcher.ui.FloodReturn(androidx.compose.ui.graphics.Color(r.color), r.to, onProgress = { floodProgress = it }) {
|
||||
@@ -1293,6 +1304,8 @@ class MainActivity : ComponentActivity() {
|
||||
touchMode = touchMode,
|
||||
suspendPolicy = suspendPolicy,
|
||||
steamDownloadsInBackground = steamDownloadsInBackground,
|
||||
zramCompression = if (mode == SessionService.MODE_STEAM) zramCompression else null,
|
||||
zramSupported = zramSupported,
|
||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
|
||||
pipAutoEnter = pipAutoEnter,
|
||||
unfoldedControls = if (mode == SessionService.MODE_STEAM &&
|
||||
@@ -1351,6 +1364,7 @@ class MainActivity : ComponentActivity() {
|
||||
SessionPrefs.setSteamDownloadsInBackground(this, enabled)
|
||||
steamDownloadsInBackground = enabled
|
||||
},
|
||||
onZramCompression = { on -> SessionPrefs.setZramCompression(this, on); zramCompression = on },
|
||||
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
|
||||
onUnfoldedControls = { on -> SessionPrefs.setUnfoldedControls(this, on); unfoldedControls = on },
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
@@ -1539,6 +1553,9 @@ class MainActivity : ComponentActivity() {
|
||||
// The sheet lifts at once, on what was last read; the slow part (driver files, a walk of the
|
||||
// added-games folders, the storage volumes) lands while it rises.
|
||||
Thread({
|
||||
val zram = com.droiddeck.launcher.core.ZramSupport.supported()
|
||||
val zramOn = SessionPrefs.zramCompression(this)
|
||||
ui.post { zramSupported = zram; zramCompression = zramOn }
|
||||
drivers.refreshDrivers()
|
||||
val storage = GameStorage.options(this)
|
||||
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
|
||||
@@ -1742,6 +1759,22 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Setup's Reset all settings; the activity is recreated so every screen reads the defaults (and the language) again. */
|
||||
private fun resetSettings(gameProfiles: Boolean) {
|
||||
if (SessionState.running) return
|
||||
val scopes = steamGames.map { it.profileKey }
|
||||
Thread({
|
||||
val ok = com.droiddeck.launcher.session.SettingsReset.resetAll(this, gameProfiles, scopes)
|
||||
ui.post {
|
||||
if (isDestroyed) return@post
|
||||
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
|
||||
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
recreate()
|
||||
}
|
||||
}, "reset-settings").start()
|
||||
}
|
||||
|
||||
private fun removeRuntime() {
|
||||
if (runtimeChangesBlocked()) return
|
||||
val removal = LinuxRuntimeInstaller.beginUninstall(this) ?: return
|
||||
|
||||
@@ -49,7 +49,10 @@ import com.droiddeck.launcher.stores.StoreAchievements
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreLaunchRequests
|
||||
import com.droiddeck.launcher.ui.SessionAchievements
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.HeadTracker
|
||||
import com.droiddeck.launcher.gpu.SteamVr
|
||||
import com.droiddeck.launcher.gpu.ScreenEffectLooks
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import com.droiddeck.launcher.gpu.Lossless
|
||||
@@ -297,6 +300,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var upscaler by mutableStateOf(0)
|
||||
private var upscaleSharpness by mutableStateOf(75)
|
||||
private var effects by mutableStateOf(ScreenEffects.OFF)
|
||||
/** Cardboard mode (gpu/Cardboard) and the sensor that turns the virtual screen with the head. */
|
||||
private var cardboard by mutableStateOf(Cardboard.OFF)
|
||||
private var headTracker: HeadTracker? = null
|
||||
private var steamVrStatus by mutableStateOf<SteamVr.Status?>(null)
|
||||
/** The picture was switched to side-by-side for SteamVR and goes back when it stops. */
|
||||
private var steamVrSwitchedPicture by mutableStateOf(false)
|
||||
/** SteamVR has been seen running since the switch: only then does "not running" mean it stopped. */
|
||||
private var steamVrSeenRunning = false
|
||||
private val hasRotationSensor by lazy {
|
||||
(getSystemService(SENSOR_SERVICE) as android.hardware.SensorManager).let {
|
||||
it.getDefaultSensor(android.hardware.Sensor.TYPE_GAME_ROTATION_VECTOR)
|
||||
?: it.getDefaultSensor(android.hardware.Sensor.TYPE_ROTATION_VECTOR)
|
||||
} != null
|
||||
}
|
||||
// Held in a field: SharedPreferences keeps its listeners weakly. A change from anywhere (the
|
||||
// drawer, tools/droiddeckctl prefs set) applies live.
|
||||
private val cardboardPrefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
||||
if (key == SessionPrefs.CARDBOARD_KEY) uiHandler.post { applyCardboard(SessionPrefs.cardboard(this)) }
|
||||
}
|
||||
private var textureAnisotropy by mutableStateOf(0)
|
||||
private var textureLodBias by mutableStateOf(TextureFiltering.LOD_BIAS_OFF)
|
||||
private var drawerTextureAnisotropy by mutableStateOf<Int?>(null)
|
||||
@@ -571,6 +593,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
}
|
||||
// SteamVR's state for the Cardboard group, refreshed while the drawer shows it.
|
||||
// Watched for as long as Cardboard mode is on (or the picture is switched for it), drawer open or
|
||||
// not: however SteamVR is started or quit, the picture follows it.
|
||||
LaunchedEffect(cardboard.enabled, steamVrSwitchedPicture) {
|
||||
while (cardboard.enabled || steamVrSwitchedPicture) {
|
||||
val now = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
SteamVr.status(this@SessionActivity)
|
||||
}
|
||||
onSteamVrStatus(now)
|
||||
kotlinx.coroutines.delay(3000)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(drawerOpen, achievementsOpen, AgentGuest.focusRevision, StoreAchievements.revision) {
|
||||
if (!drawerOpen && !achievementsOpen) return@LaunchedEffect
|
||||
val found = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
@@ -596,6 +630,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
hudOn = hudOn,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
effects = effects,
|
||||
cardboard = cardboard,
|
||||
cardboardSensor = hasRotationSensor,
|
||||
onCardboard = { c -> SessionPrefs.setCardboard(this@SessionActivity, c); applyCardboard(c) },
|
||||
onCardboardRecenter = { headTracker?.recenter() },
|
||||
steamVr = steamVrStatus,
|
||||
onSteamVr = { action -> steamVrAction(action) },
|
||||
textureAnisotropy = if (drawerGameProfileId == null) textureAnisotropy else drawerTextureAnisotropy,
|
||||
textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias,
|
||||
frameGen = frameGen,
|
||||
@@ -1126,6 +1166,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||
effects = SessionPrefs.screenEffects(this)
|
||||
applyCardboard(SessionPrefs.cardboard(this))
|
||||
// A switch left from before this activity (or this resume): SteamVR was running then, so the next
|
||||
// "not running" hands the picture back.
|
||||
if (SessionPrefs.cardboardSourceBeforeSteamVr(this) >= 0 && !steamVrSwitchedPicture) {
|
||||
steamVrSwitchedPicture = true
|
||||
steamVrSeenRunning = true
|
||||
}
|
||||
textureAnisotropy = SessionPrefs.textureAnisotropy(this)
|
||||
textureLodBias = SessionPrefs.textureLodBias(this)
|
||||
val nextTouchMode = SessionPrefs.touchMode(this)
|
||||
@@ -1302,6 +1349,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// Turnip, not the system Adreno driver: importing the dma-bufs gamescope commits needs
|
||||
// VK_EXT_image_drm_format_modifier, which the system driver does not implement.
|
||||
val turnip = TurnipDriver(this)
|
||||
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup")
|
||||
val driverId = if (CompositorHost.isStarted) null else turnip.install()
|
||||
|
||||
// The output size belongs to the session, not to the Surface: gamescope's display is
|
||||
@@ -1331,6 +1379,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
WaylandCompositor.nativeSetUpscaler(SessionPrefs.upscaler(this))
|
||||
WaylandCompositor.nativeSetUpscaleSharpness(SessionPrefs.upscaleSharpness(this))
|
||||
SessionPrefs.screenEffects(this).push(SessionPrefs.upscaler(this))
|
||||
panelSizeMm().let { (w, h) -> SessionPrefs.cardboard(this).push(w, h) }
|
||||
WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path)
|
||||
// The session's folder, claimed here because the compositor starts before the service and
|
||||
// opens its log once. The compositor reads the path from its environment; setting it after
|
||||
// it has started changes nothing, which is why the service copies the file in at teardown.
|
||||
@@ -1368,6 +1418,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
)
|
||||
Log.i(TAG, "hdr: " + (if (on) "on" else if (wanted) "wanted but ${probe.reason}" else "off") + " · display ${probe.formats.ifEmpty { "SDR" }}")
|
||||
}
|
||||
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId")
|
||||
CompositorHost.startOrAttach(
|
||||
holder.surface, runtimeDir.path,
|
||||
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
|
||||
@@ -1489,13 +1540,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
* The rate of the mode PerfMode asked for, not the one the panel is still in: the switch lands
|
||||
* some frames after onCreate, and read too early it gave gamescope `-r 60` on a 120 Hz panel -
|
||||
* the client and every game then paced themselves to 60. (WinNative's requestedPanelRefreshRate.)
|
||||
* Never above the user's peak refresh rate, which Android holds the panel to whatever mode is
|
||||
* active; it is the rate gamescope gives Steam, and the QAM's Frame Limit divides it.
|
||||
*/
|
||||
private fun refreshHz(): Float {
|
||||
val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay
|
||||
val wanted = window.attributes.preferredDisplayModeId
|
||||
val hz = display?.supportedModes?.firstOrNull { wanted != 0 && it.modeId == wanted }?.refreshRate
|
||||
?: display?.refreshRate ?: 60f
|
||||
return if (hz > 1f) hz else 60f
|
||||
val capped = minOf(hz, PerfMode.peakRefreshCap(this))
|
||||
return if (capped > 1f) capped else 60f
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2512,6 +2566,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
readPrefs()
|
||||
if (::pip.isInitialized) pip.resumed()
|
||||
if (CompositorHost.isStarted) applyFrameGen()
|
||||
SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(cardboardPrefListener)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
@@ -2530,9 +2585,103 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
updatePointerCapture()
|
||||
updatePadMotion()
|
||||
keyboard?.takeIf { it.shown }?.hide()
|
||||
SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(cardboardPrefListener)
|
||||
updateHeadTracker()
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
/** SteamVR for Cardboard mode: install, start or stop it in the guest. Starting switches the
|
||||
* picture to side-by-side, which is what SteamVR draws. */
|
||||
private fun steamVrAction(action: String) {
|
||||
if (action == "start") {
|
||||
switchPictureForSteamVr()
|
||||
steamVrSeenRunning = false
|
||||
}
|
||||
if (action == "stop") restoreSteamVrPicture()
|
||||
if (action == "install") steamVrStatus = SteamVr.Status.INSTALLING
|
||||
Thread({
|
||||
val ok = SteamVr.run(this, action)
|
||||
val now = SteamVr.status(this)
|
||||
uiHandler.post {
|
||||
// A start that failed leaves nothing side-by-side to show: the picture goes back.
|
||||
if (!ok && action == "start" && now != SteamVr.Status.RUNNING) restoreSteamVrPicture()
|
||||
onSteamVrStatus(now)
|
||||
if (!ok) Toast.makeText(this, getString(R.string.cardboard_steamvr_failed), Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}, "steamvr-$action").start()
|
||||
}
|
||||
|
||||
/** SteamVR draws a side-by-side pair: the picture switches to that, remembering what it was. */
|
||||
private fun switchPictureForSteamVr() {
|
||||
if (cardboard.source != Cardboard.SOURCE_SBS) {
|
||||
SessionPrefs.setCardboardSourceBeforeSteamVr(this, cardboard.source)
|
||||
val c = cardboard.copy(source = Cardboard.SOURCE_SBS)
|
||||
SessionPrefs.setCardboard(this, c)
|
||||
applyCardboard(c)
|
||||
}
|
||||
steamVrSwitchedPicture = SessionPrefs.cardboardSourceBeforeSteamVr(this) >= 0
|
||||
}
|
||||
|
||||
private fun onSteamVrStatus(now: SteamVr.Status) {
|
||||
steamVrStatus = now
|
||||
// Started some other way than the drawer (a script, a VR game): the picture follows it all the same.
|
||||
if (now == SteamVr.Status.RUNNING && cardboard.enabled && !steamVrSwitchedPicture &&
|
||||
cardboard.source != Cardboard.SOURCE_SBS) {
|
||||
switchPictureForSteamVr()
|
||||
steamVrSeenRunning = true
|
||||
}
|
||||
if (!steamVrSwitchedPicture) return
|
||||
if (now == SteamVr.Status.RUNNING) steamVrSeenRunning = true
|
||||
else if (steamVrSeenRunning && now != SteamVr.Status.UNAVAILABLE) restoreSteamVrPicture()
|
||||
}
|
||||
|
||||
/** SteamVR stopped: the Cardboard picture goes back to what it was before Start. */
|
||||
private fun restoreSteamVrPicture() {
|
||||
val before = SessionPrefs.cardboardSourceBeforeSteamVr(this)
|
||||
SessionPrefs.setCardboardSourceBeforeSteamVr(this, -1)
|
||||
steamVrSwitchedPicture = false
|
||||
steamVrSeenRunning = false
|
||||
if (before < 0 || cardboard.source == before) return
|
||||
val c = cardboard.copy(source = before)
|
||||
SessionPrefs.setCardboard(this, c)
|
||||
applyCardboard(c)
|
||||
}
|
||||
|
||||
/** Cardboard mode: hand the settings to the compositor and run the head tracker while it needs one. */
|
||||
private fun applyCardboard(c: Cardboard) {
|
||||
val was = cardboard
|
||||
cardboard = c
|
||||
if (CompositorHost.isStarted) panelSizeMm().let { (w, h) -> c.push(w, h) }
|
||||
if (c.enabled && !was.enabled) headTracker?.recenter()
|
||||
updateHeadTracker()
|
||||
}
|
||||
|
||||
private fun updateHeadTracker() {
|
||||
// Side-by-side sources track too: the compositor leaves their picture alone, but whoever renders
|
||||
// it (the SteamVR driver, tools/vr) reads the pose from the shared file.
|
||||
val want = resumed && cardboard.enabled && cardboard.headTracking
|
||||
if (want) {
|
||||
val t = headTracker ?: HeadTracker(this) {
|
||||
@Suppress("DEPRECATION")
|
||||
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
|
||||
}.also { headTracker = it }
|
||||
t.start()
|
||||
} else {
|
||||
headTracker?.stop()
|
||||
}
|
||||
}
|
||||
|
||||
/** The panel's physical size in millimetres, long side first, for lining the eyes up with the lenses. */
|
||||
private fun panelSizeMm(): Pair<Float, Float> {
|
||||
val dm = resources.displayMetrics
|
||||
val landscape = dm.widthPixels >= dm.heightPixels
|
||||
val longPx = maxOf(dm.widthPixels, dm.heightPixels).toFloat()
|
||||
val shortPx = minOf(dm.widthPixels, dm.heightPixels).toFloat()
|
||||
val longDpi = if (landscape) dm.xdpi else dm.ydpi
|
||||
val shortDpi = if (landscape) dm.ydpi else dm.xdpi
|
||||
return (if (longDpi > 0f) longPx / longDpi * 25.4f else 0f) to (if (shortDpi > 0f) shortPx / shortDpi * 25.4f else 0f)
|
||||
}
|
||||
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return
|
||||
|
||||
@@ -8,7 +8,7 @@ import android.content.Context
|
||||
* permission). Running commands in the guest, evaluating JavaScript in the Steam client, session
|
||||
* environment, binary overrides and preference writes reach inside the app's sandbox - the guest
|
||||
* holds the Steam login - which the shell of a stock device otherwise cannot. They require
|
||||
* Setup > Session > Debugging tools to be on, in every build. The bridge itself cannot turn it on.
|
||||
* Setup > Diagnostics > Debugging tools to be on, in every build. The bridge itself cannot turn it on.
|
||||
*/
|
||||
object AgentAccess {
|
||||
const val MAX_REQUEST_CHARS = 256 * 1024
|
||||
@@ -33,7 +33,7 @@ object AgentAccess {
|
||||
fun requireCommands(context: Context) {
|
||||
if (!commandsAllowed(context)) throw AgentException(
|
||||
"AGENT_COMMANDS_DISABLED",
|
||||
"Debugging tools are off: turn on Setup > Session > Debugging tools on the device",
|
||||
"Debugging tools are off: turn on Setup > Diagnostics > Debugging tools on the device",
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,11 @@ object AppLanguage {
|
||||
const val SYSTEM = ""
|
||||
|
||||
/** The languages the app ships, as BCP 47 tags, in the order the picker lists them. */
|
||||
val supported: List<String> = listOf("en", "es", "fr", "ru", "ja", "ko", "zh-CN", "zh-TW", "zh-HK")
|
||||
val supported: List<String> = listOf(
|
||||
"en", "id", "ms", "cs", "da", "de", "es", "es-419", "fr", "it", "hu", "nl", "nb", "pl",
|
||||
"pt-BR", "pt-PT", "ro", "fi", "sv", "vi", "tr", "el", "bg", "ru", "uk", "ar", "hi", "th",
|
||||
"ja", "ko", "zh-CN", "zh-TW", "zh-HK",
|
||||
)
|
||||
|
||||
private const val PREFS = "language"
|
||||
private const val KEY = "app_language"
|
||||
@@ -97,9 +101,18 @@ object AppLanguage {
|
||||
// 0 leaves it undefined, so only the locale is changed.
|
||||
private fun override(locale: Locale) = Configuration().apply { fontScale = 0f; setLocales(LocaleList(locale)) }
|
||||
|
||||
private val latinAmerica = setOf(
|
||||
"419", "AR", "BO", "BR", "BZ", "CL", "CO", "CR", "CU", "DO", "EC", "GT", "HN", "MX", "NI", "PA",
|
||||
"PE", "PR", "PY", "SV", "US", "UY", "VE",
|
||||
)
|
||||
|
||||
/** Which of the app's languages [locale] reads as, or null when the app does not ship it. */
|
||||
fun supportedTag(locale: Locale): String? = when (locale.language) {
|
||||
"en", "es", "fr", "ru", "ja", "ko" -> locale.language
|
||||
"en", "fr", "ru", "ja", "ko", "ms", "cs", "da", "de", "it", "hu", "nl", "nb", "pl", "ro", "fi",
|
||||
"sv", "vi", "tr", "el", "bg", "uk", "ar", "hi", "th" -> locale.language
|
||||
"in", "id" -> "id"
|
||||
"es" -> if (locale.country in latinAmerica) "es-419" else "es"
|
||||
"pt" -> if (locale.country.isEmpty() || locale.country == "BR") "pt-BR" else "pt-PT"
|
||||
"zh" -> when {
|
||||
locale.script == "Hans" -> "zh-CN"
|
||||
locale.country == "HK" || locale.country == "MO" -> "zh-HK"
|
||||
@@ -116,9 +129,33 @@ object AppLanguage {
|
||||
/** A language's name in that language, for the picker: what a reader of it looks for. */
|
||||
fun nativeName(tag: String): String = when (tag) {
|
||||
"en" -> "English"
|
||||
"es" -> "Español"
|
||||
"id" -> "Bahasa Indonesia"
|
||||
"ms" -> "Bahasa Melayu"
|
||||
"cs" -> "Čeština"
|
||||
"da" -> "Dansk"
|
||||
"de" -> "Deutsch"
|
||||
"es" -> "Español (España)"
|
||||
"es-419" -> "Español (Latinoamérica)"
|
||||
"fr" -> "Français"
|
||||
"it" -> "Italiano"
|
||||
"hu" -> "Magyar"
|
||||
"nl" -> "Nederlands"
|
||||
"nb" -> "Norsk bokmål"
|
||||
"pl" -> "Polski"
|
||||
"pt-BR" -> "Português (Brasil)"
|
||||
"pt-PT" -> "Português (Portugal)"
|
||||
"ro" -> "Română"
|
||||
"fi" -> "Suomi"
|
||||
"sv" -> "Svenska"
|
||||
"vi" -> "Tiếng Việt"
|
||||
"tr" -> "Türkçe"
|
||||
"el" -> "Ελληνικά"
|
||||
"bg" -> "Български"
|
||||
"ru" -> "Русский"
|
||||
"uk" -> "Українська"
|
||||
"ar" -> "العربية"
|
||||
"hi" -> "हिन्दी"
|
||||
"th" -> "ไทย"
|
||||
"ja" -> "日本語"
|
||||
"ko" -> "한국어"
|
||||
"zh-CN" -> "简体中文"
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import java.io.File
|
||||
|
||||
/** Whether the client's memory can be paged out to compressed swap: MADV_PAGEOUT (Linux 5.4) and a zram or other swap device. */
|
||||
object ZramSupport {
|
||||
private const val GIB = 1L shl 30
|
||||
|
||||
fun supported(): Boolean = kernelAtLeast(System.getProperty("os.version").orEmpty(), 5, 4) && swapTotalKb() > 0
|
||||
|
||||
fun recommended(context: Context): Boolean {
|
||||
if (!supported()) return false
|
||||
val memory = ActivityManager.MemoryInfo()
|
||||
context.getSystemService(ActivityManager::class.java).getMemoryInfo(memory)
|
||||
val advertised = if (Build.VERSION.SDK_INT >= 34) memory.advertisedMem else 0L
|
||||
return belowTwelveGb(advertised, memory.totalMem)
|
||||
}
|
||||
|
||||
fun belowTwelveGb(advertisedBytes: Long, totalBytes: Long): Boolean =
|
||||
if (advertisedBytes > 0) advertisedBytes < 11 * GIB else totalBytes < 10 * GIB
|
||||
|
||||
fun kernelAtLeast(release: String, major: Int, minor: Int): Boolean {
|
||||
val parts = Regex("^(\\d+)\\.(\\d+)").find(release)?.groupValues ?: return false
|
||||
val ma = parts[1].toInt()
|
||||
val mi = parts[2].toInt()
|
||||
return ma > major || (ma == major && mi >= minor)
|
||||
}
|
||||
|
||||
fun swapTotalKb(meminfo: List<String> = runCatching { File("/proc/meminfo").readLines() }.getOrDefault(emptyList())): Long =
|
||||
meminfo.firstOrNull { it.startsWith("SwapTotal:") }
|
||||
?.substringAfter(':')?.trim()?.substringBefore(' ')?.toLongOrNull() ?: 0L
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* Cardboard mode: the compositor draws the session as two lens-distorted eye views side by side
|
||||
* (waylandcomp/src/cardboard.c), for a phone or handheld dropped into a Google Cardboard-style
|
||||
* viewer. Units are the menu's own:
|
||||
*
|
||||
* - [ipdMm] distance between the eyes, millimetres
|
||||
* - [screenWidthDm] the virtual screen's width, decimetres (40 = 4 m)
|
||||
* - [screenDistanceDm] how far away it hangs, decimetres (30 = 3 m)
|
||||
* - [viewer] a [Viewer] id: the lens it is drawn for
|
||||
*
|
||||
* [source] SCREEN shows the frame as a flat virtual screen, world-locked by the rotation sensor
|
||||
* when [headTracking] is on (3DoF), with real stereo depth from the IPD. SBS takes a frame that is
|
||||
* already a left/right pair (SteamVR, SBS 3D games and video) and only adds the lens.
|
||||
*/
|
||||
data class Cardboard(
|
||||
val enabled: Boolean = false,
|
||||
val source: Int = SOURCE_SCREEN,
|
||||
val viewer: String = Viewer.CARDBOARD_V2.id,
|
||||
val ipdMm: Int = 64,
|
||||
val screenWidthDm: Int = 40,
|
||||
val screenDistanceDm: Int = 30,
|
||||
val headTracking: Boolean = true,
|
||||
) {
|
||||
val lens: Viewer get() = Viewer.byId(viewer)
|
||||
|
||||
/**
|
||||
* Hands the settings to the compositor. [panelWidthMm] x [panelHeightMm] is the physical size of
|
||||
* the panel the eyes are drawn on (0 = unknown). The width decides how far each lens centre sits
|
||||
* from its viewport's centre, so the two pictures line up with the viewer's lenses; the height,
|
||||
* seen through the lens from its focal distance, is the field of view the distortion works in.
|
||||
*/
|
||||
fun push(panelWidthMm: Float, panelHeightMm: Float) {
|
||||
val l = lens
|
||||
WaylandCompositor.nativeSetCardboard(enabled, source, ipdMm / 1000f, screenDistanceDm / 10f,
|
||||
screenWidthDm / 10f, l.k1, l.k2, fovDeg(l, panelHeightMm), lensInset(panelWidthMm, l.lensSeparationMm), l.chroma)
|
||||
}
|
||||
|
||||
fun encode(): JSONObject = JSONObject()
|
||||
.put("enabled", enabled).put("source", source).put("viewer", viewer).put("ipdMm", ipdMm)
|
||||
.put("screenWidthDm", screenWidthDm).put("screenDistanceDm", screenDistanceDm).put("headTracking", headTracking)
|
||||
|
||||
/**
|
||||
* A lens the eyes can be drawn for: its distortion (Cardboard viewer profile coefficients, in
|
||||
* tangent units at the panel), how far it sits from the panel, and how far apart the two are.
|
||||
* [fallbackFovDeg] is the eye's field of view when the panel's size is unknown, or with no lens.
|
||||
*/
|
||||
enum class Viewer(val id: String, val k1: Float, val k2: Float, val screenToLensMm: Float,
|
||||
val lensSeparationMm: Float, val chroma: Float, val fallbackFovDeg: Float) {
|
||||
/** Google Cardboard (2015): the common plastic and cardboard viewers. */
|
||||
CARDBOARD_V2("cardboard2", 0.34f, 0.55f, 39.3f, 63.9f, 0.006f, 90f),
|
||||
/** The original 2014 Cardboard: narrower, gentler lenses. */
|
||||
CARDBOARD_V1("cardboard1", 0.441f, 0.156f, 42f, 60f, 0.004f, 80f),
|
||||
/** No lens: side-by-side 3D glasses, a 3D TV, or just looking at the stereo pair. */
|
||||
NONE("none", 0f, 0f, 0f, 0f, 0f, 60f);
|
||||
|
||||
companion object {
|
||||
fun byId(id: String): Viewer = entries.firstOrNull { it.id == id } ?: CARDBOARD_V2
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val SOURCE_SCREEN = 0
|
||||
const val SOURCE_SBS = 1
|
||||
|
||||
val OFF = Cardboard()
|
||||
|
||||
fun decode(json: JSONObject): Cardboard = Cardboard(
|
||||
enabled = json.optBoolean("enabled", false),
|
||||
source = if (json.optInt("source", SOURCE_SCREEN) == SOURCE_SBS) SOURCE_SBS else SOURCE_SCREEN,
|
||||
viewer = Viewer.byId(json.optString("viewer", Viewer.CARDBOARD_V2.id)).id,
|
||||
ipdMm = json.optInt("ipdMm", 64).coerceIn(50, 80),
|
||||
screenWidthDm = json.optInt("screenWidthDm", 40).coerceIn(5, 200),
|
||||
screenDistanceDm = json.optInt("screenDistanceDm", 30).coerceIn(5, 200),
|
||||
headTracking = json.optBoolean("headTracking", true),
|
||||
)
|
||||
|
||||
/**
|
||||
* One eye's vertical field of view on the panel side of the lens: half the panel's height
|
||||
* seen from the lens's focal distance. The lens then spreads it wider (the distortion).
|
||||
*/
|
||||
fun fovDeg(viewer: Viewer, panelHeightMm: Float): Float {
|
||||
if (panelHeightMm <= 0f || viewer.screenToLensMm <= 0f) return viewer.fallbackFovDeg
|
||||
val half = Math.toDegrees(kotlin.math.atan((panelHeightMm / 2f / viewer.screenToLensMm).toDouble())).toFloat()
|
||||
return (2f * half).coerceIn(30f, 140f)
|
||||
}
|
||||
|
||||
/**
|
||||
* The lens centre's inset towards the nose, as a fraction of one eye viewport's width. Each
|
||||
* eye gets half the panel, so its viewport centre is a quarter of the panel from the middle;
|
||||
* the lens centre is half the lens separation from it. 0 when either is unknown.
|
||||
*/
|
||||
fun lensInset(panelWidthMm: Float, lensSeparationMm: Float): Float {
|
||||
if (panelWidthMm <= 0f || lensSeparationMm <= 0f) return 0f
|
||||
val inset = (panelWidthMm / 4f - lensSeparationMm / 2f) / (panelWidthMm / 2f)
|
||||
return inset.coerceIn(-0.25f, 0.25f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Head pose maths for Cardboard mode, kept free of Android types so it is unit-tested on the JVM.
|
||||
* Matrices are row-major 3x3 FloatArrays. "World" is Android's sensor world (x east, y north,
|
||||
* z up); "screen" axes are x right, y up, z out of the panel towards the viewer's eyes.
|
||||
*/
|
||||
object HeadPose {
|
||||
val IDENTITY = floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f)
|
||||
|
||||
/** Unit quaternion (x, y, z, w) -> rotation matrix: what SensorManager.getRotationMatrixFromVector gives. */
|
||||
fun fromQuaternion(x: Float, y: Float, z: Float, w: Float): FloatArray {
|
||||
val n = sqrt(x * x + y * y + z * z + w * w).takeIf { it > 1e-6f } ?: 1f
|
||||
val qx = x / n; val qy = y / n; val qz = z / n; val qw = w / n
|
||||
return floatArrayOf(
|
||||
1 - 2 * (qy * qy + qz * qz), 2 * (qx * qy - qz * qw), 2 * (qx * qz + qy * qw),
|
||||
2 * (qx * qy + qz * qw), 1 - 2 * (qx * qx + qz * qz), 2 * (qy * qz - qx * qw),
|
||||
2 * (qx * qz - qy * qw), 2 * (qy * qz + qx * qw), 1 - 2 * (qx * qx + qy * qy),
|
||||
)
|
||||
}
|
||||
|
||||
/** The rotation vector sensor's values -> (x, y, z, w), computing w when the sensor leaves it out. */
|
||||
fun quaternionFromRotationVector(v: FloatArray): FloatArray {
|
||||
val x = v[0]; val y = v[1]; val z = v[2]
|
||||
val w = if (v.size >= 4) v[3] else sqrt((1f - x * x - y * y - z * z).coerceAtLeast(0f))
|
||||
return floatArrayOf(x, y, z, w)
|
||||
}
|
||||
|
||||
/**
|
||||
* Device -> screen axes for a Display rotation (Surface.ROTATION_* as 0..3): the returned matrix
|
||||
* maps screen to world, given the device's own device -> world matrix. The same transform as
|
||||
* input/PadMotion's and SensorManager.remapCoordinateSystem's (ROTATION_90 = AXIS_Y, AXIS_MINUS_X:
|
||||
* the device's x is the screen's y, its y the screen's -x).
|
||||
*/
|
||||
fun toScreen(deviceToWorld: FloatArray, rotation: Int): FloatArray {
|
||||
// Columns of A: where each screen axis points in device coordinates.
|
||||
val a = when (rotation and 3) {
|
||||
1 -> floatArrayOf(0f, 1f, 0f, -1f, 0f, 0f, 0f, 0f, 1f) // screen x = -device y, y = device x
|
||||
2 -> floatArrayOf(-1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, 1f) // screen x = -device x, y = -device y
|
||||
3 -> floatArrayOf(0f, -1f, 0f, 1f, 0f, 0f, 0f, 0f, 1f) // screen x = device y, y = -device x
|
||||
else -> IDENTITY
|
||||
}
|
||||
return multiply(deviceToWorld, a)
|
||||
}
|
||||
|
||||
/** sin(60 degrees): a view further from level than this is "held flat" for recentring. */
|
||||
private const val FLAT_SIN = 0.866f
|
||||
|
||||
/**
|
||||
* What a recentre locks to. The pose the compositor gets is basis^T * screenToWorld * tilt:
|
||||
* - [basis]: a level frame (columns right, up, back in world) facing the recentred heading. Every
|
||||
* rotation is measured in it, so turning about the real vertical always pans the view;
|
||||
* - [tilt]: the device's own tilt at the recentre, taken out so that pose starts straight ahead.
|
||||
* Identity when the device was held upright: the horizon then stays the true one.
|
||||
*/
|
||||
class Reference(val basis: FloatArray, val tilt: FloatArray)
|
||||
|
||||
/**
|
||||
* Recentre on the current orientation. Held upright (the screen within 60 degrees of vertical, as
|
||||
* in a viewer), only the heading resets: forward is where the screen faces. Held flat (lying back,
|
||||
* or the device on a table or in the hands like a tray), forward is where the top of the screen
|
||||
* points and the tilt resets too; turning at the hips still pans, tipping the device still tilts.
|
||||
*/
|
||||
fun recenter(screenToWorld: FloatArray): Reference {
|
||||
val fz = -screenToWorld[8]
|
||||
val flat = kotlin.math.abs(fz) > FLAT_SIN
|
||||
// Upright: the screen's -z. Flat: the screen's +y (its top edge), which is level then.
|
||||
var fx = if (flat) screenToWorld[1] else -screenToWorld[2]
|
||||
var fy = if (flat) screenToWorld[4] else -screenToWorld[5]
|
||||
val len = sqrt(fx * fx + fy * fy).takeIf { it > 1e-4f } ?: run { fx = 0f; fy = 1f; 1f }
|
||||
fx /= len; fy /= len
|
||||
// right = forward x up(0,0,1) = (fy, -fx, 0); up = (0,0,1); back = -forward.
|
||||
val basis = floatArrayOf(
|
||||
fy, 0f, -fx,
|
||||
-fx, 0f, -fy,
|
||||
0f, 1f, 0f,
|
||||
)
|
||||
val tilt = if (flat) multiply(transpose(screenToWorld), basis) else IDENTITY
|
||||
return Reference(basis, tilt)
|
||||
}
|
||||
|
||||
/** head -> recentred world: what the compositor takes. */
|
||||
fun relative(ref: Reference, screenToWorld: FloatArray): FloatArray =
|
||||
multiply(multiply(transpose(ref.basis), screenToWorld), ref.tilt)
|
||||
|
||||
fun multiply(a: FloatArray, b: FloatArray): FloatArray = FloatArray(9) { i ->
|
||||
val r = i / 3; val c = i % 3
|
||||
a[r * 3] * b[c] + a[r * 3 + 1] * b[3 + c] + a[r * 3 + 2] * b[6 + c]
|
||||
}
|
||||
|
||||
fun transpose(m: FloatArray): FloatArray = floatArrayOf(m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8])
|
||||
|
||||
/** m * v for a 3-vector. */
|
||||
fun apply(m: FloatArray, v: FloatArray): FloatArray = floatArrayOf(
|
||||
m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
|
||||
m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
|
||||
m[6] * v[0] + m[7] * v[1] + m[8] * v[2],
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.gpu;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
|
||||
/** Setup breadcrumbs survive failures before a session log exists. No account data. */
|
||||
public final class DriverSetupLog {
|
||||
private DriverSetupLog() {}
|
||||
|
||||
public static synchronized void write(Context context, String stage) {
|
||||
Log.i("DriverSetup", stage);
|
||||
append(context.getFilesDir(), stage);
|
||||
try { append(context.getExternalFilesDir(null), stage); }
|
||||
catch (Exception ignored) { /* External storage is optional. */ }
|
||||
}
|
||||
|
||||
private static void append(File directory, String stage) {
|
||||
if (directory == null) return;
|
||||
try {
|
||||
directory.mkdirs();
|
||||
File file = new File(directory, "driver-setup.txt");
|
||||
// Keep the latest run's breadcrumbs bounded across repeated attempts.
|
||||
try (FileWriter out = new FileWriter(file, file.length() < 131072)) {
|
||||
out.write(System.currentTimeMillis() + " " + stage + "\n");
|
||||
}
|
||||
} catch (Exception ignored) { /* Diagnostics must never prevent startup. */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
|
||||
/**
|
||||
* 3DoF head tracking for Cardboard mode: the rotation sensor -> the compositor's head pose
|
||||
* ([HeadPose] for the maths). Game rotation vector first (gyro + accelerometer: no compass jumps
|
||||
* indoors, and only the heading drifts, which a recentre fixes); the plain rotation vector where a
|
||||
* device has no game one. Events arrive on a thread of their own and go straight to native code,
|
||||
* so the session's UI thread never sits between the sensor and the screen.
|
||||
*
|
||||
* [rotation] is the Display rotation (Surface.ROTATION_*) the session is drawn in.
|
||||
*/
|
||||
class HeadTracker(context: Context, private val rotation: () -> Int) : SensorEventListener {
|
||||
private val sensors = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
|
||||
private val sensor: Sensor? = sensors.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR)
|
||||
?: sensors.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
|
||||
private var thread: HandlerThread? = null
|
||||
@Volatile private var reference: HeadPose.Reference? = null
|
||||
@Volatile private var recenterPending = true
|
||||
@Volatile private var latest: FloatArray? = null
|
||||
|
||||
/** Whether this device has a rotation sensor at all (no sensor = a fixed, head-locked screen). */
|
||||
val available: Boolean get() = sensor != null
|
||||
val sensorName: String get() = sensor?.let { "${it.name} (${if (it.type == Sensor.TYPE_GAME_ROTATION_VECTOR) "game rotation vector" else "rotation vector"})" } ?: "none"
|
||||
|
||||
fun start() {
|
||||
val s = sensor ?: run {
|
||||
WaylandCompositor.nativeLog("cardboard", "no rotation sensor: the virtual screen stays head-locked")
|
||||
WaylandCompositor.nativeSetCardboardPose(HeadPose.IDENTITY, false)
|
||||
return
|
||||
}
|
||||
if (thread != null) return
|
||||
recenterPending = true
|
||||
val t = HandlerThread("droiddeck-headtracker").also { it.start() }
|
||||
thread = t
|
||||
sensors.registerListener(this, s, SensorManager.SENSOR_DELAY_FASTEST, Handler(t.looper))
|
||||
WaylandCompositor.nativeLog("cardboard", "head tracking on: $sensorName")
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
val t = thread ?: return
|
||||
sensors.unregisterListener(this)
|
||||
t.quitSafely()
|
||||
thread = null
|
||||
WaylandCompositor.nativeSetCardboardPose(HeadPose.IDENTITY, false)
|
||||
}
|
||||
|
||||
/** Make where the viewer looks now straight ahead (see HeadPose.recenter). */
|
||||
fun recenter() {
|
||||
recenterPending = true
|
||||
latest?.let { apply(it) }
|
||||
}
|
||||
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
val q = HeadPose.quaternionFromRotationVector(event.values)
|
||||
val m = HeadPose.toScreen(HeadPose.fromQuaternion(q[0], q[1], q[2], q[3]), rotation())
|
||||
latest = m
|
||||
apply(m)
|
||||
}
|
||||
|
||||
private fun apply(screenToWorld: FloatArray) {
|
||||
val ref = reference.takeUnless { recenterPending } ?: HeadPose.recenter(screenToWorld).also {
|
||||
reference = it
|
||||
recenterPending = false
|
||||
}
|
||||
WaylandCompositor.nativeSetCardboardPose(HeadPose.relative(ref, screenToWorld), true)
|
||||
}
|
||||
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
|
||||
Log.d("DroidDeck", "head tracker accuracy $accuracy")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Cardboard mode's SteamVR (docs/cardboard-vr.md): Valve's ARM64 SteamVR in the guest, rendering
|
||||
* through the DroidDeck driver as a side-by-side pair that the Cardboard pass puts the lens on. Driven
|
||||
* through the guest agent's fixed "vr" request (droiddeck-steamvr), so it needs no agent commands.
|
||||
* Every call blocks on the guest: run them off the main thread.
|
||||
*/
|
||||
object SteamVr {
|
||||
enum class Status {
|
||||
/** No session, no agent, or a runtime without the helper or the driver. */
|
||||
UNAVAILABLE,
|
||||
NOT_INSTALLED,
|
||||
/** Downloading or unpacking (571 MB). */
|
||||
INSTALLING,
|
||||
READY,
|
||||
RUNNING,
|
||||
}
|
||||
|
||||
fun status(context: Context): Status = runCatching {
|
||||
parse(AgentGuest.call(context, JSONObject().put("kind", "vr").put("action", "status"), STATUS_TIMEOUT_MS))
|
||||
}.getOrDefault(Status.UNAVAILABLE)
|
||||
|
||||
/** install, start or stop; true when the guest did it. */
|
||||
fun run(context: Context, action: String): Boolean = runCatching {
|
||||
require(action in setOf("install", "start", "stop"))
|
||||
succeeded(action, AgentGuest.call(context, JSONObject().put("kind", "vr").put("action", action), ACTION_TIMEOUT_MS))
|
||||
}.getOrDefault(false)
|
||||
|
||||
/**
|
||||
* The agent answers ok whenever it ran the request, even when droiddeck-steamvr then failed; the
|
||||
* helper's own exit code says whether start or stop worked. install runs detached and only reports
|
||||
* that it started (its progress shows in status).
|
||||
*/
|
||||
fun succeeded(action: String, answer: JSONObject): Boolean = when {
|
||||
!answer.optBoolean("ok", false) -> false
|
||||
action == "install" -> answer.optBoolean("started", false)
|
||||
else -> answer.optInt("exitCode", -1) == 0
|
||||
}
|
||||
|
||||
/** The agent's status answer -> what the menu shows. */
|
||||
fun parse(answer: JSONObject): Status = when {
|
||||
!answer.optBoolean("ok", false) -> Status.UNAVAILABLE
|
||||
answer.optInt("exitCode", 0) != 0 -> Status.UNAVAILABLE
|
||||
answer.optBoolean("installing") -> Status.INSTALLING
|
||||
!answer.optBoolean("driver") -> Status.UNAVAILABLE
|
||||
!answer.optBoolean("installed") -> Status.NOT_INSTALLED
|
||||
answer.optBoolean("running") -> Status.RUNNING
|
||||
else -> Status.READY
|
||||
}
|
||||
|
||||
private const val STATUS_TIMEOUT_MS = 10_000L
|
||||
private const val ACTION_TIMEOUT_MS = 40_000L
|
||||
}
|
||||
@@ -45,13 +45,16 @@ import java.util.zip.ZipInputStream;
|
||||
*/
|
||||
public final class TurnipDriver {
|
||||
private static final String TAG = "TurnipDriver";
|
||||
/** Pinned A6xx/A7xx upstream build; used as the A6xx offline fallback. */
|
||||
private static final String DRIVER_A6XX = "turnip26.3.0-a6xx";
|
||||
/** Adreno 7xx (8 Gen 2/3, e.g. the Pocket FIT's A750). */
|
||||
private static final String DRIVER_A7XX = "turnip25.1.0";
|
||||
/** Adreno 8xx (8 Elite, e.g. a Fold 8's A830). */
|
||||
private static final String DRIVER_A8XX = "turnip-sdk36";
|
||||
/** The two the apk carries; never removable, unpacked on demand. */
|
||||
public static final List<String> BUNDLED = Collections.unmodifiableList(Arrays.asList(
|
||||
DRIVER_A7XX, DRIVER_A8XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER));
|
||||
DRIVER_A7XX, DRIVER_A8XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER,
|
||||
DRIVER_A6XX, com.droiddeck.launcher.session.QuestExperimental.DRIVER_A6XX));
|
||||
/** Overrides the pick, for a device we cannot reach: a7xx, a8xx or system. */
|
||||
private static final String OVERRIDE_FILE = "Download/droiddeck-driver";
|
||||
/** Bundled drivers the user deleted: hidden from the list, their unpacked copy removed. */
|
||||
@@ -289,12 +292,14 @@ public final class TurnipDriver {
|
||||
*/
|
||||
public String install() {
|
||||
String id = choose();
|
||||
DriverSetupLog.write(context, "install.begin driver=" + id);
|
||||
if (id == null) return null;
|
||||
File dir = new File(contentDir, id);
|
||||
if (!new File(dir, "meta.json").isFile()) {
|
||||
FileUtils.delete(dir);
|
||||
if (!TarZst.extractAsset(context, "graphics_driver/adrenotools-" + id + ".tzst", dir)) {
|
||||
Log.e(TAG, "could not unpack " + id);
|
||||
DriverSetupLog.write(context, "install.unpack-failed driver=" + id);
|
||||
FileUtils.delete(dir);
|
||||
return null;
|
||||
}
|
||||
@@ -305,6 +310,7 @@ public final class TurnipDriver {
|
||||
return null;
|
||||
}
|
||||
Log.i(TAG, "graphics driver " + id + " (" + library + ")");
|
||||
DriverSetupLog.write(context, "install.ready driver=" + id + " library=" + library);
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -338,6 +344,7 @@ public final class TurnipDriver {
|
||||
if (forced.startsWith("system")) return null;
|
||||
if (forced.startsWith("a8")) return DRIVER_A8XX;
|
||||
if (forced.startsWith("a7")) return DRIVER_A7XX;
|
||||
if (forced.startsWith("a6")) return DRIVER_A6XX;
|
||||
}
|
||||
String model = gpuModel();
|
||||
Log.i(TAG, "gpu model: " + (model == null ? "unknown" : model));
|
||||
@@ -348,6 +355,7 @@ public final class TurnipDriver {
|
||||
char generation = m.group(1).charAt(0);
|
||||
if (generation >= '8') return DRIVER_A8XX;
|
||||
if (generation == '7') return DRIVER_A7XX;
|
||||
if (generation == '6') return DRIVER_A6XX;
|
||||
}
|
||||
}
|
||||
// Nothing to go on: Android 16 shipped with the 8 Elite, so treat a new device as 8xx.
|
||||
|
||||
@@ -2,10 +2,12 @@ package com.droiddeck.launcher.input
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.text.InputType
|
||||
import android.view.KeyCharacterMap
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.WindowInsets
|
||||
import android.view.inputmethod.BaseInputConnection
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.view.inputmethod.InputConnection
|
||||
@@ -53,7 +55,10 @@ class KeyboardHost(
|
||||
return KeyConnection()
|
||||
}
|
||||
|
||||
fun toggle() = if (shown) hide() else show()
|
||||
fun toggle() = if (shown && imeVisible()) hide() else show()
|
||||
|
||||
private fun imeVisible() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R ||
|
||||
rootWindowInsets?.isVisible(WindowInsets.Type.ime()) != false
|
||||
|
||||
fun show() {
|
||||
shown = true
|
||||
|
||||
@@ -13,6 +13,7 @@ import android.util.Log
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.widget.Toast
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.SteamTouchConfig.Element
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.abs
|
||||
@@ -335,7 +336,7 @@ class SteamTouchControls(
|
||||
if (editing) {
|
||||
text.textSize = r * 0.3f
|
||||
text.color = Color.argb(alpha / 2, 255, 255, 255)
|
||||
canvas.drawText("Trackpad", x, y - (text.descent() + text.ascent()) / 2, text)
|
||||
canvas.drawText(context.getString(R.string.deck_surface_trackpad), x, y - (text.descent() + text.ascent()) / 2, text)
|
||||
}
|
||||
}
|
||||
SteamTouchConfig.STEAM -> {
|
||||
@@ -579,7 +580,7 @@ class SteamTouchControls(
|
||||
SteamTouchConfig.STEAM -> "STEAM"
|
||||
SteamTouchConfig.THUMB -> "…"
|
||||
SteamTouchConfig.KEYBOARD -> "⌨"
|
||||
SteamTouchConfig.PASTE -> "Paste"
|
||||
SteamTouchConfig.PASTE -> context.getString(R.string.touch_paste)
|
||||
SteamTouchConfig.SELECT -> "⧉"
|
||||
SteamTouchConfig.START -> "☰"
|
||||
SteamTouchConfig.BUMPER_LEFT -> "LB"
|
||||
@@ -880,15 +881,15 @@ class SteamTouchControls(
|
||||
}
|
||||
|
||||
private fun controlName(type: Int) = when (type) {
|
||||
SteamTouchConfig.DPAD -> "D-pad"
|
||||
SteamTouchConfig.JOYSTICK_LEFT -> "Left stick"
|
||||
SteamTouchConfig.JOYSTICK_RIGHT -> "Right stick"
|
||||
SteamTouchConfig.TRACKPAD_LEFT -> "Left trackpad"
|
||||
SteamTouchConfig.TRACKPAD_RIGHT -> "Right trackpad"
|
||||
SteamTouchConfig.TRACKPAD_CENTER -> "Trackpad"
|
||||
SteamTouchConfig.DPAD -> context.getString(R.string.touch_dpad)
|
||||
SteamTouchConfig.JOYSTICK_LEFT -> context.getString(R.string.touch_left_stick)
|
||||
SteamTouchConfig.JOYSTICK_RIGHT -> context.getString(R.string.touch_right_stick)
|
||||
SteamTouchConfig.TRACKPAD_LEFT -> context.getString(R.string.deck_left_trackpad)
|
||||
SteamTouchConfig.TRACKPAD_RIGHT -> context.getString(R.string.deck_right_trackpad)
|
||||
SteamTouchConfig.TRACKPAD_CENTER -> context.getString(R.string.deck_surface_trackpad)
|
||||
SteamTouchConfig.STEAM -> "Steam"
|
||||
SteamTouchConfig.THUMB -> "Menu"
|
||||
SteamTouchConfig.KEYBOARD -> "Keyboard"
|
||||
SteamTouchConfig.THUMB -> context.getString(R.string.touch_menu)
|
||||
SteamTouchConfig.KEYBOARD -> context.getString(R.string.touch_keyboard)
|
||||
else -> label(type)
|
||||
}
|
||||
|
||||
@@ -899,22 +900,22 @@ class SteamTouchControls(
|
||||
val list = android.widget.LinearLayout(context).apply { orientation = android.widget.LinearLayout.VERTICAL; setPadding((12 * density).toInt(), 0, (12 * density).toInt(), 0) }
|
||||
var close: () -> Unit = {}
|
||||
val copied = prefs.getString("copiedLayout", null)
|
||||
fun item(name: String, enabled: Boolean = true, action: () -> Unit) = list.addView(android.widget.Button(context).apply {
|
||||
text = name
|
||||
fun item(name: Int, enabled: Boolean = true, action: () -> Unit) = list.addView(android.widget.Button(context).apply {
|
||||
setText(name)
|
||||
isAllCaps = false
|
||||
isEnabled = enabled
|
||||
setOnClickListener { close(); action(); invalidate() }
|
||||
})
|
||||
item("Colour and opacity…") { pickColor() }
|
||||
item("Copy this layout") {
|
||||
item(R.string.touch_color_opacity) { pickColor() }
|
||||
item(R.string.touch_copy_layout) {
|
||||
prefs.edit().putString("copiedLayout", (editElements + hidden).joinToString(";") {
|
||||
"${it.type},${it.visible},${it.x},${it.y},${it.xScale},${it.yScale}"
|
||||
}).apply()
|
||||
Toast.makeText(context, "Layout copied; paste it into any game's touch layout", Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context, R.string.touch_layout_copied, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
item("Paste copied layout", copied != null) { pasteLayout(copied ?: "") }
|
||||
item("Reset to Steam's default") { resetEditSet() }
|
||||
close = SteamTouchIconPicker.showPanel(host, "Layout", list, listOf("Close" to {}))
|
||||
item(R.string.touch_paste_layout, copied != null) { pasteLayout(copied ?: "") }
|
||||
item(R.string.touch_reset_layout) { resetEditSet() }
|
||||
close = SteamTouchIconPicker.showPanel(host, context.getString(R.string.ctrl_layout), list, listOf(context.getString(R.string.common_close) to {}))
|
||||
}
|
||||
|
||||
/** A copied layout onto this action set: each control the set has takes the copied place. */
|
||||
@@ -985,11 +986,12 @@ class SteamTouchControls(
|
||||
RectF(frame.left + l * s, frame.top + t * s, frame.left + r * s, frame.top + b * s)
|
||||
|
||||
private fun text(canvas: Canvas, str: String, x: Float, y: Float, size: Float, color: Int = Color.WHITE, bold: Boolean = true,
|
||||
align: Paint.Align = Paint.Align.CENTER) {
|
||||
align: Paint.Align = Paint.Align.CENTER, maxWidth: Float = 0f) {
|
||||
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
this.color = color; textSize = size; textAlign = align
|
||||
typeface = if (bold) android.graphics.Typeface.DEFAULT_BOLD else android.graphics.Typeface.DEFAULT
|
||||
}
|
||||
if (maxWidth > 0f) p.measureText(str).let { if (it > maxWidth) p.textSize = size * maxWidth / it }
|
||||
canvas.drawText(str, x, y - (p.descent() + p.ascent()) / 2, p)
|
||||
}
|
||||
|
||||
@@ -1004,7 +1006,7 @@ class SteamTouchControls(
|
||||
canvas.drawRoundRect(r, radius, radius, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = line2; style = Paint.Style.STROKE; strokeWidth = 1.2f * s })
|
||||
}
|
||||
val ink = when { !enabled -> Color.argb(110, 242, 244, 247); primary -> onAccent; else -> onSurface }
|
||||
text(canvas, text, r.centerX(), r.centerY(), 14f * s, ink)
|
||||
text(canvas, text, r.centerX(), r.centerY(), 14f * s, ink, maxWidth = r.width() - 16f * s)
|
||||
if (enabled) hots += Hot(r, onTap)
|
||||
}
|
||||
|
||||
@@ -1044,7 +1046,7 @@ class SteamTouchControls(
|
||||
BIG_PICTURE -> "Steam"
|
||||
else -> gameNames[appId] ?: run {
|
||||
val app = appId
|
||||
gameNames[app] = "app $app"
|
||||
gameNames[app] = context.getString(R.string.touch_app_id, app)
|
||||
loader.execute {
|
||||
val name = SteamTouchConfig.gameName(context, app) ?: return@execute
|
||||
handler.post { gameNames[app] = name; invalidate() }
|
||||
@@ -1061,7 +1063,7 @@ class SteamTouchControls(
|
||||
// Header: power (DroidDeck's own menu: stop, settings), the Steam mark, what is running, close.
|
||||
iconButton(canvas, ref(f, s, 494f, 18f, 531f, 55f), false, { menuOpen = false; onMenu() }) { c, r, col -> drawPower(c, r, col) }
|
||||
drawMark(canvas, f.left + 104f * s, f.top + 37f * s, 13f * s)
|
||||
text(canvas, "Touch controls", f.left + 124f * s, f.top + 30f * s, 14f * s, onSurface, align = Paint.Align.LEFT)
|
||||
text(canvas, context.getString(R.string.touch_title), f.left + 124f * s, f.top + 30f * s, 14f * s, onSurface, align = Paint.Align.LEFT)
|
||||
text(canvas, gameName(), f.left + 124f * s, f.top + 46f * s, 11f * s, muted, bold = false, align = Paint.Align.LEFT)
|
||||
closeButton(canvas, f, s) { menuOpen = false }
|
||||
val controller = options.inputMode != SteamTouchConfig.INPUT_MOUSE
|
||||
@@ -1071,10 +1073,10 @@ class SteamTouchControls(
|
||||
m -> SteamTouchConfig.INPUT_MOUSE
|
||||
else -> SteamTouchConfig.INPUT_CONTROLLER
|
||||
}))
|
||||
tile(canvas, ref(f, s, 45f, 81f, 249f, 271f), s, "Touch Controller", controller, { setModes(!controller, mouse || controller) }) { c, r, col ->
|
||||
tile(canvas, ref(f, s, 45f, 81f, 249f, 271f), s, context.getString(R.string.touch_controller), controller, { setModes(!controller, mouse || controller) }) { c, r, col ->
|
||||
drawPhonePad(c, r, col)
|
||||
}
|
||||
tile(canvas, ref(f, s, 271f, 81f, 475f, 271f), s, "Mouse", mouse, { setModes(controller || mouse, !mouse) }) { c, r, col ->
|
||||
tile(canvas, ref(f, s, 271f, 81f, 475f, 271f), s, context.getString(R.string.touch_mouse), mouse, { setModes(controller || mouse, !mouse) }) { c, r, col ->
|
||||
drawMouse(c, r, col, crossed = false)
|
||||
}
|
||||
// Under the controller: gyroscope, fade, vibrate on touch.
|
||||
@@ -1102,10 +1104,13 @@ class SteamTouchControls(
|
||||
val speed = speeds.indexOfFirst { abs(it - options.trackpadSensitivity) < 0.2f }.coerceAtLeast(1)
|
||||
iconButton(canvas, ref(f, s, 412f, 278f, 475f, 318f), mouse && relative, {
|
||||
setOptions(options.copy(trackpadSensitivity = speeds[(speed + 1) % speeds.size]))
|
||||
}) { c, r, col -> text(c, listOf("Slow", "Normal", "Fast")[speed], r.centerX(), r.centerY(), r.height() * 0.32f, col) }
|
||||
}) { c, r, col ->
|
||||
val name = context.getString(listOf(R.string.touch_speed_slow, R.string.touch_speed_normal, R.string.touch_speed_fast)[speed])
|
||||
text(c, name, r.centerX(), r.centerY(), r.height() * 0.32f, col, maxWidth = r.width() - 6f * s)
|
||||
}
|
||||
drawVolume(canvas, f, s)
|
||||
blueButton(canvas, ref(f, s, 45f, 329f, 249f, 372f), "Edit layout", s, primary = true) { menuOpen = false; startEditing() }
|
||||
blueButton(canvas, ref(f, s, 271f, 329f, 475f, 372f), "DroidDeck menu", s) { menuOpen = false; onMenu() }
|
||||
blueButton(canvas, ref(f, s, 45f, 329f, 249f, 372f), context.getString(R.string.touch_edit_layout), s, primary = true) { menuOpen = false; startEditing() }
|
||||
blueButton(canvas, ref(f, s, 271f, 329f, 475f, 372f), context.getString(R.string.touch_droiddeck_menu), s) { menuOpen = false; onMenu() }
|
||||
}
|
||||
|
||||
private val audio by lazy { context.getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager }
|
||||
@@ -1173,7 +1178,7 @@ class SteamTouchControls(
|
||||
canvas.drawRoundRect(r, radius, radius, Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = if (on) accent else line; style = Paint.Style.STROKE; strokeWidth = (if (on) 2f else 1.2f) * s
|
||||
})
|
||||
text(canvas, title, r.left + 16f * s, r.top + 22f * s, 14f * s, onSurface, align = Paint.Align.LEFT)
|
||||
text(canvas, title, r.left + 16f * s, r.top + 22f * s, 14f * s, onSurface, align = Paint.Align.LEFT, maxWidth = r.width() - 72f * s)
|
||||
// A switch, top right.
|
||||
val sw = RectF(r.right - 50f * s, r.top + 12f * s, r.right - 14f * s, r.top + 32f * s)
|
||||
canvas.drawRoundRect(sw, sw.height() / 2, sw.height() / 2, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (on) accent else line2 })
|
||||
@@ -1181,7 +1186,7 @@ class SteamTouchControls(
|
||||
Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (on) onAccent else muted })
|
||||
val artRect = RectF(r.centerX() - 58f * s, r.top + 62f * s, r.centerX() + 58f * s, r.top + 140f * s)
|
||||
art(canvas, artRect, if (on) onSurface else muted)
|
||||
text(canvas, if (on) "On" else "Off", r.left + 16f * s, r.bottom - 18f * s, 12f * s, if (on) accent else muted, bold = false, align = Paint.Align.LEFT)
|
||||
text(canvas, context.getString(if (on) R.string.touch_on else R.string.touch_off), r.left + 16f * s, r.bottom - 18f * s, 12f * s, if (on) accent else muted, bold = false, align = Paint.Align.LEFT)
|
||||
hots += Hot(r, toggle)
|
||||
}
|
||||
|
||||
@@ -1194,9 +1199,9 @@ class SteamTouchControls(
|
||||
closeButton(canvas, f, s) { save() }
|
||||
val sets = SteamTouchConfig.actionSets(config)
|
||||
val setName = sets.firstOrNull { it.first == editSet }?.second
|
||||
val title = if (sets.size > 1 && setName != null) "${gameName()} · $setName" else "${gameName()} ${config.title ?: "Layout"}"
|
||||
text(canvas, title, f.centerX(), f.top + 30f * s, 14f * s, onSurface)
|
||||
text(canvas, "Drag controls onto the screen", f.centerX(), f.top + 47f * s, 11f * s, muted, bold = false)
|
||||
val title = if (sets.size > 1 && setName != null) "${gameName()} · $setName" else "${gameName()} ${config.title ?: context.getString(R.string.ctrl_layout)}"
|
||||
text(canvas, title, f.centerX(), f.top + 30f * s, 14f * s, onSurface, maxWidth = f.width() - 200f * s)
|
||||
text(canvas, context.getString(R.string.touch_drag_hint), f.centerX(), f.top + 47f * s, 11f * s, muted, bold = false, maxWidth = f.width() - 200f * s)
|
||||
if (sets.size > 1) {
|
||||
arrowPill(canvas, ref(f, s, 120f, 26f, 150f, 44f), -1) { stepEditSet(-1) }
|
||||
arrowPill(canvas, ref(f, s, 474f, 26f, 504f, 44f), 1) { stepEditSet(1) }
|
||||
@@ -1251,8 +1256,8 @@ class SteamTouchControls(
|
||||
shader = android.graphics.RadialGradient(wheel.centerX(), wheel.centerY(), wheel.width() / 2f, Color.WHITE, Color.TRANSPARENT, android.graphics.Shader.TileMode.CLAMP)
|
||||
})
|
||||
hots += Hot(wheel, { pickColor() })
|
||||
blueButton(canvas, ref(f, s, 45f, 329f, 232f, 372f), "Arrange", s, primary = true) { trayOpen = false }
|
||||
blueButton(canvas, ref(f, s, 254f, 329f, 441f, 372f), "Discard", s) { stopEditing() }
|
||||
blueButton(canvas, ref(f, s, 45f, 329f, 232f, 372f), context.getString(R.string.touch_arrange), s, primary = true) { trayOpen = false }
|
||||
blueButton(canvas, ref(f, s, 254f, 329f, 441f, 372f), context.getString(R.string.touch_discard), s) { stopEditing() }
|
||||
}
|
||||
|
||||
private fun arrowPill(canvas: Canvas, r: RectF, dir: Int, onTap: () -> Unit) {
|
||||
@@ -1290,7 +1295,10 @@ class SteamTouchControls(
|
||||
return RectF(x - r, y - r, x + r, y + r)
|
||||
}
|
||||
|
||||
private val contextLabels = listOf("Icon", "W−", "W+", "H−", "H+", "Hide")
|
||||
private val contextLabels by lazy {
|
||||
listOf(R.string.touch_icon, R.string.touch_narrower, R.string.touch_wider, R.string.touch_shorter, R.string.touch_taller, R.string.touch_hide)
|
||||
.map(context::getString)
|
||||
}
|
||||
|
||||
private fun contextRects(): List<RectF> {
|
||||
val e = editElements.getOrNull(selected) ?: return emptyList()
|
||||
@@ -1313,11 +1321,11 @@ class SteamTouchControls(
|
||||
canvas.drawRoundRect(m, m.width() * 0.15f, m.width() * 0.15f, p)
|
||||
drawDots(canvas, m.centerX(), m.centerY() - m.height() * 0.1f, m.width() * 0.5f, Color.WHITE)
|
||||
hots += Hot(m, { trayOpen = true })
|
||||
if (saving) text(canvas, "Saving…", width / 2f, height * 0.08f, 22f * max(unit(), 0.6f))
|
||||
if (saving) text(canvas, context.getString(R.string.touch_saving), width / 2f, height * 0.08f, 22f * max(unit(), 0.6f))
|
||||
contextRects().forEachIndexed { i, r ->
|
||||
canvas.drawRoundRect(r, r.height() * 0.3f, r.height() * 0.3f, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = surface })
|
||||
canvas.drawRoundRect(r, r.height() * 0.3f, r.height() * 0.3f, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = line2; style = Paint.Style.STROKE; strokeWidth = 1.2f })
|
||||
text(canvas, contextLabels[i], r.centerX(), r.centerY(), r.height() * 0.4f, onSurface, bold = false)
|
||||
text(canvas, contextLabels[i], r.centerX(), r.centerY(), r.height() * 0.4f, onSurface, bold = false, maxWidth = r.width() - 6f)
|
||||
hots += Hot(r, { contextTool(i) })
|
||||
}
|
||||
}
|
||||
@@ -1448,12 +1456,14 @@ class SteamTouchControls(
|
||||
val ref = visual?.ref
|
||||
val binding = visual?.binding
|
||||
if (ref == null || binding == null) {
|
||||
Toast.makeText(context, "This control has no binding in Steam to put an icon on", Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context, R.string.touch_no_binding, Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
val name = if (e.type == SteamTouchConfig.DPAD) "D-pad " + listOf("up", "down", "left", "right")[selectedArm] else label(e.type)
|
||||
val name = if (e.type == SteamTouchConfig.DPAD) {
|
||||
context.getString(listOf(R.string.touch_dpad_up, R.string.touch_dpad_down, R.string.touch_dpad_left, R.string.touch_dpad_right)[selectedArm])
|
||||
} else label(e.type)
|
||||
val host = parent as? android.view.ViewGroup ?: return
|
||||
SteamTouchIconPicker(context, host, appId, "Icon for $name", binding) { picked ->
|
||||
SteamTouchIconPicker(context, host, appId, context.getString(R.string.touch_icon_for, name), binding) { picked ->
|
||||
pendingBindings[ref] = picked
|
||||
rebuildVisuals()
|
||||
invalidate()
|
||||
@@ -1480,9 +1490,9 @@ class SteamTouchControls(
|
||||
}
|
||||
}, android.widget.LinearLayout.LayoutParams(dp(30), dp(30)).apply { marginEnd = dp(6) })
|
||||
}
|
||||
root.addView(android.widget.TextView(context).apply { text = "Colour" })
|
||||
root.addView(android.widget.TextView(context).apply { setText(R.string.ctrl_color) })
|
||||
root.addView(android.widget.HorizontalScrollView(context).apply { addView(swatchRow) })
|
||||
root.addView(android.widget.TextView(context).apply { text = "Opacity"; setPadding(0, dp(12), 0, 0) })
|
||||
root.addView(android.widget.TextView(context).apply { setText(R.string.ctrl_opacity); setPadding(0, dp(12), 0, 0) })
|
||||
val opacityRow = android.widget.LinearLayout(context)
|
||||
listOf(20, 35, 50, 65, 80, 100).forEach { percent ->
|
||||
opacityRow.addView(android.widget.Button(context).apply {
|
||||
@@ -1497,7 +1507,7 @@ class SteamTouchControls(
|
||||
}
|
||||
root.addView(android.widget.HorizontalScrollView(context).apply { addView(opacityRow) })
|
||||
val host = parent as? android.view.ViewGroup ?: return
|
||||
SteamTouchIconPicker.showPanel(host, "Touch layout colour", root, listOf("Done" to {}))
|
||||
SteamTouchIconPicker.showPanel(host, context.getString(R.string.touch_layout_color), root, listOf(context.getString(R.string.touch_done) to {}))
|
||||
}
|
||||
|
||||
private fun save() {
|
||||
@@ -1528,11 +1538,11 @@ class SteamTouchControls(
|
||||
handler.post {
|
||||
saving = false
|
||||
if (file == null) {
|
||||
Toast.makeText(context, "Could not save the touch layout", Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context, R.string.touch_save_failed, Toast.LENGTH_SHORT).show()
|
||||
invalidate()
|
||||
return@post
|
||||
}
|
||||
Toast.makeText(context, "Touch layout saved to Steam", Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context, R.string.touch_saved, Toast.LENGTH_SHORT).show()
|
||||
onSaved()
|
||||
stopEditing()
|
||||
reloadConfig()
|
||||
|
||||
@@ -21,6 +21,7 @@ import android.widget.HorizontalScrollView
|
||||
import android.widget.ImageView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import com.droiddeck.launcher.R
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
@@ -50,7 +51,7 @@ class SteamTouchIconPicker(
|
||||
val root = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; setPadding(dp(16), dp(8), dp(16), 0) }
|
||||
val left = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
|
||||
val label = EditText(context).apply {
|
||||
hint = "Label (optional)"
|
||||
setHint(R.string.touch_label_hint)
|
||||
setText(current.label)
|
||||
inputType = InputType.TYPE_CLASS_TEXT
|
||||
setSingleLine()
|
||||
@@ -77,21 +78,22 @@ class SteamTouchIconPicker(
|
||||
setPadding(0, dp(8), 0, 0)
|
||||
addView(preview, LinearLayout.LayoutParams(dp(56), dp(56)))
|
||||
addView(TextView(context).apply {
|
||||
text = if (names.isEmpty()) "Steam's icons were not found" else "${names.size} icons from Steam"
|
||||
text = if (names.isEmpty()) context.getString(R.string.touch_icons_missing)
|
||||
else context.resources.getQuantityString(R.plurals.touch_icons_found, names.size, names.size)
|
||||
setPadding(dp(12), 0, 0, 0)
|
||||
})
|
||||
})
|
||||
left.addView(paletteRow("Icon colour", { foreground }) { foreground = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
|
||||
left.addView(paletteRow("Button colour", { background }) { background = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
|
||||
left.addView(paletteRow(context.getString(R.string.touch_icon_color), { foreground }) { foreground = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
|
||||
left.addView(paletteRow(context.getString(R.string.touch_button_color), { background }) { background = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
|
||||
root.addView(left, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
|
||||
root.addView(grid, LinearLayout.LayoutParams(0, dp(250), 1.2f).apply { marginStart = dp(16) })
|
||||
updatePreview(preview)
|
||||
showPanel(host, title, root, listOf(
|
||||
"No icon" to {
|
||||
context.getString(R.string.touch_no_icon) to {
|
||||
onPicked(current.copy(label = label.text.toString().replace(",", " ").trim(), icon = "", foreground = "", background = ""))
|
||||
},
|
||||
"Cancel" to {},
|
||||
"Use" to {
|
||||
context.getString(R.string.common_cancel) to {},
|
||||
context.getString(R.string.common_use) to {
|
||||
onPicked(current.copy(label = label.text.toString().replace(",", " ").trim(), icon = icon,
|
||||
foreground = if (icon.isEmpty()) "" else foreground, background = if (icon.isEmpty()) "" else background))
|
||||
},
|
||||
|
||||
@@ -3,7 +3,9 @@ package com.droiddeck.launcher.session
|
||||
import android.app.Activity
|
||||
import android.app.GameManager
|
||||
import android.app.GameState
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
@@ -16,8 +18,9 @@ import android.util.Log
|
||||
* a level the device can hold indefinitely rather than holding a floor, which cost games and
|
||||
* Big Picture their peak clocks. WinNative never asks for it; the thermal budget is left to
|
||||
* the game;
|
||||
* - the panel's fastest mode at its current size (Android 6+): a 120 Hz phone is switched to
|
||||
* 120 Hz for the menu, not only when a game votes for it. With a frame cap, the fastest mode
|
||||
* - the panel's fastest mode at its current size (Android 6+), up to the user's peak refresh rate
|
||||
* ([peakRefreshCap]): a 120 Hz phone is switched to 120 Hz for the menu, not only when a game
|
||||
* votes for it. With a frame cap, the fastest mode
|
||||
* the cap divides evenly, so every capped frame is shown for the same number of refreshes;
|
||||
* - GameManager's game state (Android 13+): "in gameplay", so an OEM framework that releases
|
||||
* its boost on loading screens or menus keeps it up.
|
||||
@@ -36,8 +39,11 @@ object PerfMode {
|
||||
val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay
|
||||
if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else {
|
||||
val cur = display.mode
|
||||
val cap = peakRefreshCap(a)
|
||||
val sameSize = display.supportedModes
|
||||
.filter { it.physicalWidth == cur.physicalWidth && it.physicalHeight == cur.physicalHeight }
|
||||
.filter { it.refreshRate <= cap + 0.5f }
|
||||
.ifEmpty { display.supportedModes.filter { it.modeId == cur.modeId } }
|
||||
val best = sameSize.filter { cadenceFits(it.refreshRate, fpsLimit) }.maxByOrNull { it.refreshRate }
|
||||
?: sameSize.maxByOrNull { it.refreshRate }
|
||||
if (best != null && best.modeId != cur.modeId &&
|
||||
@@ -68,6 +74,20 @@ object PerfMode {
|
||||
return parts.joinToString(" · ")
|
||||
}
|
||||
|
||||
/**
|
||||
* The highest rate Android will run the panel at: the user's "peak refresh rate" (Smooth display,
|
||||
* or the AYN/Odin quick-settings tile). Above it a mode can be requested and is even reported back
|
||||
* as active, while SurfaceFlinger keeps composing at the cap. The Thor set to 60 Hz ran 120 Hz
|
||||
* sessions at 60: gamescope and Steam were told 120, every game topped out at 60, and the QAM's
|
||||
* Frame Limit read "60 FPS (120 Hz)" and changed nothing. Unset (most phones) is no cap.
|
||||
*/
|
||||
fun peakRefreshCap(context: Context): Float {
|
||||
val peak = try {
|
||||
Settings.System.getFloat(context.contentResolver, "peak_refresh_rate")
|
||||
} catch (_: Throwable) { 0f }
|
||||
return if (peak >= 1f) peak else Float.POSITIVE_INFINITY
|
||||
}
|
||||
|
||||
/** A panel rate that shows every capped frame for a whole number of refreshes (no cap: any). */
|
||||
fun cadenceFits(hz: Float, fpsLimit: Int): Boolean {
|
||||
if (fpsLimit <= 0) return true
|
||||
|
||||
@@ -10,29 +10,36 @@ import java.io.File
|
||||
object QuestExperimental {
|
||||
private const val TAG = "QuestExperimental"
|
||||
const val DRIVER = "turnip25.1.0-quest1"
|
||||
const val DRIVER_A6XX = "turnip26.3.0-quest2"
|
||||
|
||||
internal fun quest2(model: String, device: String, manufacturer: String): Boolean =
|
||||
model.equals("Quest 2", ignoreCase = true) ||
|
||||
((manufacturer.equals("Oculus", ignoreCase = true) || manufacturer.equals("Meta", ignoreCase = true)) &&
|
||||
device == "hollywood")
|
||||
|
||||
// Quest 2 has an A6xx GPU and cannot use this bundled A7xx driver.
|
||||
internal fun supported(model: String, device: String, manufacturer: String): Boolean =
|
||||
model.equals("Quest 3", ignoreCase = true) || model.equals("Quest 3S", ignoreCase = true) ||
|
||||
quest2(model, device, manufacturer) || model.equals("Quest 3", ignoreCase = true) || model.equals("Quest 3S", ignoreCase = true) ||
|
||||
((manufacturer.equals("Oculus", ignoreCase = true) || manufacturer.equals("Meta", ignoreCase = true)) &&
|
||||
(device == "eureka" || device == "panther"))
|
||||
|
||||
fun isSupported(): Boolean = supported(Build.MODEL, Build.DEVICE, Build.MANUFACTURER)
|
||||
fun isQuest2(): Boolean = quest2(Build.MODEL, Build.DEVICE, Build.MANUFACTURER)
|
||||
|
||||
fun initialize(context: Context) {
|
||||
if (!isSupported()) return
|
||||
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
if (!prefs.getBoolean("questDefaultsV1", false)) {
|
||||
val defaultsKey = if (isQuest2()) "quest2DefaultsV1" else "questDefaultsV1"
|
||||
if (!prefs.getBoolean(defaultsKey, false)) {
|
||||
// Auto would download an unwrapped display driver and lose the compatibility path.
|
||||
// Apply once so deliberate changes made during headset testing remain possible.
|
||||
prefs.edit()
|
||||
.putString("gpuDriverMode", SessionPrefs.GPU_DRIVERS_MANUAL)
|
||||
.putString("androidDriver", DRIVER)
|
||||
.putString("androidDriver", if (isQuest2()) DRIVER_A6XX else DRIVER)
|
||||
.putString("linuxDriver", "")
|
||||
// The existing HDR option uses SurfaceControl presentation. This is a
|
||||
// corruption workaround from upstream issue #245, not a claim of HDR accuracy.
|
||||
.putBoolean("hdr.steam", true)
|
||||
.putBoolean("questDefaultsV1", true)
|
||||
.putBoolean(defaultsKey, true)
|
||||
.apply()
|
||||
}
|
||||
val report = buildString {
|
||||
@@ -51,7 +58,7 @@ object QuestExperimental {
|
||||
appendLine("androidDriver=${SessionPrefs.androidDriver(context)}")
|
||||
appendLine("steamSurfaceControlWorkaround=${SessionPrefs.hdr(context, "steam")}")
|
||||
appendLine("GPUOBJ fallback installed in Android driver and ARM64 libblsession")
|
||||
appendLine("Experimental Quest 3/3S compatibility; 2D panel application")
|
||||
appendLine("Experimental Quest 2/3/3S compatibility; 2D panel application")
|
||||
}
|
||||
Log.i(TAG, report)
|
||||
runCatching { File(context.filesDir, "quest-startup.txt").writeText(report) }
|
||||
|
||||
@@ -87,6 +87,8 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-open-url" to "usr/local/bin/droiddeck-open-url",
|
||||
"usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games",
|
||||
"usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults",
|
||||
// Cardboard mode's SteamVR: install, start and stop (docs/cardboard-vr.md).
|
||||
"usr/local/bin/droiddeck-steamvr" to "usr/local/bin/droiddeck-steamvr",
|
||||
// Flatpak: the bwrap stand-in, the store's helper and setup, and the front end's launcher.
|
||||
"usr/local/bin/droiddeck-bwrap" to "usr/local/bin/droiddeck-bwrap",
|
||||
"usr/local/bin/droiddeck-flatpak" to "usr/local/bin/droiddeck-flatpak",
|
||||
@@ -133,6 +135,18 @@ object SessionFiles {
|
||||
val msitools = listOf("msiinfo", "cabextract", "7z", "7z.so", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
|
||||
.map { "usr/local/lib/droiddeck-msitools/$it" } +
|
||||
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1", "7zip-License", "7zip-unRarLicense").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
|
||||
// Cardboard mode's SteamVR driver and the Vulkan layer its compositor needs (tools/vr).
|
||||
val vr = listOf(
|
||||
"droiddeck/bin/linuxarm64/driver_droiddeck.so",
|
||||
"droiddeck/driver.vrdrivermanifest",
|
||||
"droiddeck/resources/settings/default.vrsettings",
|
||||
"layer/libVkLayer_droiddeck_vr.so",
|
||||
"layer/VK_LAYER_DROIDDECK_vr.json",
|
||||
).map { "usr/local/lib/droiddeck-vr/$it" to "usr/local/lib/droiddeck-vr/$it" } +
|
||||
// The same layer, implicit for the whole session: it passes everything through until SteamVR
|
||||
// runs, then Steam's own web helper gets the shared-texture support it needs (tools/vr).
|
||||
listOf("usr/local/lib/droiddeck-vr/layer/VK_LAYER_DROIDDECK_vr_implicit.json" to
|
||||
"usr/share/vulkan/implicit_layer.d/droiddeck_vr.json")
|
||||
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
|
||||
listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
|
||||
} + listOf("libthunkaudit.so", "libvulkan-thunk.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
|
||||
@@ -140,7 +154,7 @@ object SessionFiles {
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
) + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
|
||||
) + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.CpuAllocationDefaults
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.core.ZramSupport
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import org.json.JSONObject
|
||||
|
||||
@@ -85,6 +87,14 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("gameStoresSpeedTier", tier).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Hidden A/B switch for the Epic installer: "adaptive" (default: native parallel fetch written
|
||||
* straight into staged files), "batch" (the older whole-cache native fetch, then native
|
||||
* assembly; needs about twice the game's size free) or "java" (the bounded one-chunk-at-a-time
|
||||
* Java writer). No UI; set it in the `session` preferences for benchmarks.
|
||||
*/
|
||||
fun storesEpicMode(context: Context): String = prefs(context).getString("storesEpicMode", "adaptive") ?: "adaptive"
|
||||
|
||||
/** Which tab a signed-in store opens on when its chip is picked: [STORES_OPEN_LIBRARY] or [STORES_OPEN_STORE]. */
|
||||
fun storesOpenTab(context: Context): String =
|
||||
prefs(context).getString("storesOpenTab", STORES_OPEN_LIBRARY)?.takeIf { it == STORES_OPEN_STORE } ?: STORES_OPEN_LIBRARY
|
||||
@@ -845,6 +855,31 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("screenEffects", effects.encode().toString()).apply()
|
||||
}
|
||||
|
||||
/** The key [cardboard] lives under; SessionActivity watches it so a change applies live. */
|
||||
const val CARDBOARD_KEY = "cardboard"
|
||||
|
||||
/** Cardboard mode (gpu/Cardboard) as last set; off by default. */
|
||||
fun cardboard(context: Context): Cardboard {
|
||||
val text = prefs(context).getString(CARDBOARD_KEY, null) ?: return Cardboard.OFF
|
||||
return runCatching { Cardboard.decode(JSONObject(text)) }.getOrDefault(Cardboard.OFF)
|
||||
}
|
||||
|
||||
fun setCardboard(context: Context, cardboard: Cardboard) {
|
||||
prefs(context).edit().putString(CARDBOARD_KEY, cardboard.encode().toString()).apply()
|
||||
}
|
||||
|
||||
/** The Cardboard picture (Cardboard.SOURCE_*) to go back to once SteamVR stops; -1 = none (it was
|
||||
* not switched for SteamVR). Kept across activity restarts, so a SteamVR session that outlives the
|
||||
* activity still hands the picture back. */
|
||||
fun cardboardSourceBeforeSteamVr(context: Context): Int = prefs(context).getInt("cardboardSourceBeforeSteamVr", -1)
|
||||
|
||||
fun setCardboardSourceBeforeSteamVr(context: Context, source: Int) {
|
||||
prefs(context).edit().putInt("cardboardSourceBeforeSteamVr", source).apply()
|
||||
}
|
||||
|
||||
/** The prefs file [cardboard] lives in, for a change listener. */
|
||||
fun sessionPrefs(context: Context): android.content.SharedPreferences = prefs(context)
|
||||
|
||||
val textureAnisotropyChoices = TextureFiltering.ANISOTROPY.map { it to if (it == 0) "Off" else "${it}x" }
|
||||
|
||||
/** [textureAnisotropyChoices] labelled in the app's language. */
|
||||
@@ -1031,6 +1066,16 @@ object SessionPrefs {
|
||||
}.apply()
|
||||
}
|
||||
|
||||
/** Steam only: the client's memory goes to the device's zram while a game runs (ZramSupport). */
|
||||
fun zramCompression(context: Context): Boolean {
|
||||
val prefs = prefs(context)
|
||||
return if (prefs.contains("zramCompression")) prefs.getBoolean("zramCompression", false) else ZramSupport.recommended(context)
|
||||
}
|
||||
|
||||
fun setZramCompression(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("zramCompression", on).apply()
|
||||
}
|
||||
|
||||
// ── Game storage ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -660,6 +660,8 @@ class SessionService : Service() {
|
||||
// gamescope's realtime Vulkan queues (the session script turns this into
|
||||
// GAMESCOPE_FORCE_VULKAN_REALTIME); off unless the user turns it on.
|
||||
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
|
||||
if (SessionState.mode == MODE_STEAM && SessionPrefs.zramCompression(this) &&
|
||||
com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
|
||||
guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
|
||||
// Anything else, for a device that cannot be reached with a debugger: droiddeck-env in the
|
||||
// app's own external files (envSwitchFile) holds KEY=VALUE lines that go into the session's
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
|
||||
/**
|
||||
* Setup's "Reset all settings": every choice goes back to the default its getter falls back to.
|
||||
*
|
||||
* Only settings are removed. The "session" file also holds the library (added games' names, exes,
|
||||
* appids and art picks), migration records, the drivers Auto installed, the storage and ROMs
|
||||
* folders and the one-time permission prompts; those stay, as do store sign-ins, imported drivers
|
||||
* and Lossless Scaling. Game profiles (each game's and the Default profile's environment
|
||||
* overrides) are cleared only when asked for.
|
||||
*/
|
||||
object SettingsReset {
|
||||
private const val TAG = "SettingsReset"
|
||||
|
||||
internal val SESSION_KEYS = setOf(
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"hud", "hudDeck", "backActionsInverted", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "stretch16x9",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline",
|
||||
// Cleared so the Quest's one-time compatibility defaults are written again.
|
||||
"questDefaultsV1",
|
||||
)
|
||||
|
||||
/** Per-mode settings, stored as "<prefix><mode>". */
|
||||
internal val SESSION_PREFIXES = listOf(
|
||||
"resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "suspendPolicy.",
|
||||
)
|
||||
|
||||
private val STEAM_TOUCH_KEYS = listOf("feedback", "autoFade", "gyro", "shake")
|
||||
|
||||
internal fun isSessionSetting(key: String) = key in SESSION_KEYS || SESSION_PREFIXES.any { key.startsWith(it) }
|
||||
|
||||
/**
|
||||
* Resets the settings, then per-game profiles when [gameProfiles] is set ([gameScopes] are the
|
||||
* library's profile keys; scopes with saved overrides are found on their own). Blocking: call
|
||||
* off the main thread. Returns false if a part could not be reset; the rest is still done.
|
||||
* The language is not reset here: AppLanguage.setChosen changes the process locale, so the
|
||||
* caller does that on the main thread.
|
||||
*/
|
||||
fun resetAll(context: Context, gameProfiles: Boolean, gameScopes: Collection<String> = emptyList()): Boolean {
|
||||
var ok = true
|
||||
val session = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
session.edit().apply { session.all.keys.filter { isSessionSetting(it) }.forEach { remove(it) } }.commit()
|
||||
ControllerPrefs.resetAll(context)
|
||||
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
context.getSharedPreferences("frame_gen", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
context.getSharedPreferences("steam_touch", Context.MODE_PRIVATE).edit()
|
||||
.apply { STEAM_TOUCH_KEYS.forEach { remove(it) } }.commit()
|
||||
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(context, false)
|
||||
|
||||
if (gameProfiles) {
|
||||
val scopes = (gameScopes + runCatching { GameEnvironmentStore.read(context).games.keys }.getOrDefault(emptySet()) +
|
||||
SessionPrefs.gameTextureFiltering(context).keys)
|
||||
.filter { it.isNotEmpty() && GameEnvironment.validScope(it) }.toSet()
|
||||
scopes.forEach { scope ->
|
||||
runCatching { GameProfileManager.reset(context, scope) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not reset the profile of $scope", it) }
|
||||
}
|
||||
session.edit().remove("gameTextureFiltering").commit()
|
||||
runCatching { GameEnvironmentStore.save(context, GameEnvironmentStore.read(context).copy(shared = emptyMap())) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not clear the Default profile's environment", it) }
|
||||
}
|
||||
|
||||
QuestExperimental.initialize(context)
|
||||
runCatching { OfflineMode.apply(context, LinuxRuntime.rootDir(context)) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not turn offline mode off", it) }
|
||||
runCatching { GameEnvironmentStore.publish(context) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not update game environment", it) }
|
||||
Log.i(TAG, "settings reset (game profiles: $gameProfiles, ok: $ok)")
|
||||
return ok
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.URLEncoder
|
||||
import java.time.LocalDate
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.format.FormatStyle
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* What other sites know of a store game, looked up by its title: the Metacritic score (as Steam's
|
||||
* store search carries it) and HowLongToBeat's times. Neither store publishes these, so every
|
||||
* lookup is a name match against someone else's catalog, kept on disk a fortnight (a miss for two
|
||||
* days) and in memory for the process. Blocking: call off the main thread.
|
||||
*/
|
||||
object GameFacts {
|
||||
private const val TAG = "GameFacts"
|
||||
private const val HIT_TTL_MS = 14L * 24 * 60 * 60 * 1000
|
||||
private const val MISS_TTL_MS = 2L * 24 * 60 * 60 * 1000
|
||||
private const val TIMEOUT_MS = 10_000
|
||||
|
||||
/** Metacritic's critic score (0-100) and the game's page there. */
|
||||
data class Metacritic(val score: Int, val url: String)
|
||||
|
||||
/** HowLongToBeat's community times, in seconds (0 when nobody has logged that kind of run), and the game's page there. */
|
||||
data class Hltb(val main: Int, val extras: Int, val completionist: Int, val url: String) {
|
||||
val isEmpty: Boolean get() = main <= 0 && extras <= 0 && completionist <= 0
|
||||
}
|
||||
|
||||
/** A remembered answer: [value] null is a remembered miss. */
|
||||
private class Entry<T>(val value: T?, val at: Long) {
|
||||
fun fresh(now: Long) = now - at < if (value != null) HIT_TTL_MS else MISS_TTL_MS
|
||||
}
|
||||
|
||||
private val memory = ConcurrentHashMap<String, Entry<*>>()
|
||||
|
||||
/** The score or the times already in memory, without touching disk or network; null when not yet known. */
|
||||
fun peekMetacritic(title: String): Lookup<Metacritic>? = peek("metacritic", title)
|
||||
fun peekHltb(title: String): Lookup<Hltb>? = peek("hltb", title)
|
||||
|
||||
/** The score, or null when Steam does not list the game or has no score for it. */
|
||||
fun metacritic(context: Context, title: String): Metacritic? =
|
||||
remembered(context, "metacritic", title,
|
||||
read = { o -> o.optInt("score").takeIf { it > 0 }?.let { Metacritic(it, o.optString("url").ifEmpty { metacriticSearch(title) }) } },
|
||||
write = { o, v -> o.put("score", v.score).put("url", v.url) },
|
||||
) { searchSteamScore(title) }
|
||||
|
||||
fun hltb(context: Context, title: String): Hltb? =
|
||||
remembered(context, "hltb", title,
|
||||
read = { o -> Hltb(o.optInt("main"), o.optInt("extras"), o.optInt("completionist"), o.optString("url").ifEmpty { hltbSearch(title) }).takeUnless { it.isEmpty } },
|
||||
write = { o, v -> o.put("main", v.main).put("extras", v.extras).put("completionist", v.completionist).put("url", v.url) },
|
||||
) { searchHltb(title) }
|
||||
|
||||
// Where a game goes when its own page is not known: the site's search for its name.
|
||||
private fun metacriticSearch(title: String) = "https://www.metacritic.com/search/${encodePath(TitleMatch.searchTerm(title))}/?category=13"
|
||||
private fun hltbSearch(title: String) = "$HLTB/?q=${URLEncoder.encode(TitleMatch.searchTerm(title), "UTF-8")}"
|
||||
private fun encodePath(s: String) = URLEncoder.encode(s, "UTF-8").replace("+", "%20")
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private fun <T> peek(kind: String, title: String): Lookup<T>? {
|
||||
val e = memory[key(kind, title)] as Entry<T>? ?: return null
|
||||
return e.value?.let { Lookup.Found(it) } ?: Lookup.None
|
||||
}
|
||||
|
||||
/**
|
||||
* The memory copy, else the disk copy while fresh, else [fetch]. [fetch] answers a [Fetched]:
|
||||
* a failed request is not a miss, so it leaves the stale copy (if any) standing.
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private fun <T : Any> remembered(
|
||||
context: Context, kind: String, title: String,
|
||||
read: (JSONObject) -> T?, write: (JSONObject, T) -> Unit, fetch: () -> Fetched<T>,
|
||||
): T? {
|
||||
val now = System.currentTimeMillis()
|
||||
val k = key(kind, title)
|
||||
(memory[k] as Entry<T>?)?.takeIf { it.fresh(now) }?.let { return it.value }
|
||||
val file = File(context.filesDir, "game-facts/$kind/${fileName(title)}.json")
|
||||
val disk = runCatching { JSONObject(file.readText()) }.getOrNull()
|
||||
?.let { o -> Entry(if (o.optBoolean("none")) null else read(o), o.optLong("at")) }
|
||||
if (disk != null && disk.fresh(now)) { memory[k] = disk; return disk.value }
|
||||
return when (val got = fetch()) {
|
||||
is Fetched.Failed -> disk?.value
|
||||
is Fetched.Answer -> {
|
||||
val entry = Entry(got.value, now)
|
||||
memory[k] = entry
|
||||
runCatching {
|
||||
file.parentFile?.mkdirs()
|
||||
val o = JSONObject().put("at", now)
|
||||
if (got.value != null) write(o, got.value) else o.put("none", true)
|
||||
file.writeText(o.toString())
|
||||
}
|
||||
got.value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface Fetched<out T> {
|
||||
object Failed : Fetched<Nothing>
|
||||
class Answer<T>(val value: T?) : Fetched<T>
|
||||
}
|
||||
|
||||
private fun key(kind: String, title: String) = "$kind:${TitleMatch.normalize(title)}"
|
||||
|
||||
private fun fileName(title: String) = TitleMatch.normalize(title).take(80).ifEmpty { "_" + title.hashCode().toUInt() }
|
||||
|
||||
// Steam's store search lists a game's Metacritic score beside its name: one request, no key.
|
||||
// The game's own Metacritic page is in its app details, asked for only once there is a score.
|
||||
private fun searchSteamScore(title: String): Fetched<Metacritic> {
|
||||
val term = URLEncoder.encode(TitleMatch.searchTerm(title), "UTF-8")
|
||||
val body = StoreNet.get("https://store.steampowered.com/api/storesearch/?l=english&cc=US&term=$term", timeoutMs = TIMEOUT_MS)
|
||||
?: return Fetched.Failed
|
||||
return runCatching {
|
||||
val items = JSONObject(body).optJSONArray("items") ?: JSONArray()
|
||||
val scored = (0 until items.length()).mapNotNull { items.optJSONObject(it) }
|
||||
.filter { it.optString("type") == "app" && (it.optString("metascore").toIntOrNull() ?: 0) > 0 }
|
||||
val best = TitleMatch.pick(title, scored) { listOf(it.optString("name")) }
|
||||
val score = best?.optString("metascore")?.toIntOrNull() ?: return Fetched.Answer(null)
|
||||
Fetched.Answer(Metacritic(score, metacriticPage(best.optLong("id")) ?: metacriticSearch(title)))
|
||||
}.getOrElse { Fetched.Failed }
|
||||
}
|
||||
|
||||
/** Steam's link to the game on Metacritic, without its tracking tag; null when Steam gives none. */
|
||||
private fun metacriticPage(appId: Long): String? {
|
||||
if (appId <= 0) return null
|
||||
val body = StoreNet.get("https://store.steampowered.com/api/appdetails?appids=$appId&filters=metacritic", timeoutMs = TIMEOUT_MS) ?: return null
|
||||
return runCatching {
|
||||
JSONObject(body).optJSONObject("$appId")?.optJSONObject("data")?.optJSONObject("metacritic")?.optString("url")
|
||||
?.substringBefore('?')?.takeIf { it.startsWith("https://") }
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
// HowLongToBeat's own site search: a short-lived token from init, sent back as x-auth-token.
|
||||
// The token is bound to the User-Agent that asked for it, so both calls send the same one.
|
||||
private const val HLTB = "https://howlongtobeat.com"
|
||||
private val hltbHeaders = mapOf("Referer" to "$HLTB/", "Origin" to HLTB)
|
||||
@Volatile private var hltbToken: Pair<String, Long>? = null
|
||||
|
||||
private fun hltbToken(renew: Boolean): String? {
|
||||
val now = System.currentTimeMillis()
|
||||
hltbToken?.takeIf { !renew && now - it.second < 10 * 60 * 1000 }?.let { return it.first }
|
||||
val body = StoreNet.get("$HLTB/api/search/site/init?t=$now", timeoutMs = TIMEOUT_MS, headers = hltbHeaders) ?: return null
|
||||
val token = runCatching { JSONObject(body).optString("token") }.getOrNull()?.takeIf { it.isNotBlank() } ?: return null
|
||||
hltbToken = token to now
|
||||
return token
|
||||
}
|
||||
|
||||
private fun searchHltb(title: String): Fetched<Hltb> {
|
||||
val terms = JSONArray().apply { TitleMatch.searchTerm(title).split(' ').filter { it.isNotBlank() }.forEach { put(it) } }
|
||||
val request = JSONObject()
|
||||
.put("searchType", "games").put("searchTerms", terms).put("searchPage", 1).put("size", 20)
|
||||
.put("searchOptions", JSONObject()
|
||||
.put("games", JSONObject().put("userId", 0).put("platform", "").put("sortCategory", "popular").put("rangeCategory", "main")
|
||||
.put("rangeTime", JSONObject().put("min", 0).put("max", 0))
|
||||
.put("gameplay", JSONObject().put("perspective", "").put("flow", "").put("genre", ""))
|
||||
.put("year", "").put("modifier", ""))
|
||||
.put("users", JSONObject().put("sortCategory", "postcount"))
|
||||
.put("lists", JSONObject().put("sortCategory", "follows"))
|
||||
.put("filter", "").put("sort", 0).put("randomizer", 0))
|
||||
.put("useCache", true)
|
||||
.toString()
|
||||
// A token can lapse between init and search; one fresh one is worth a second try.
|
||||
var body: String? = null
|
||||
for (renew in listOf(false, true)) {
|
||||
val token = hltbToken(renew) ?: return Fetched.Failed
|
||||
body = StoreNet.postJson("$HLTB/api/search/site", request, timeoutMs = TIMEOUT_MS, headers = hltbHeaders + ("x-auth-token" to token))
|
||||
if (body != null) break
|
||||
}
|
||||
if (body == null) return Fetched.Failed
|
||||
return runCatching {
|
||||
val data = JSONObject(body).optJSONArray("data") ?: JSONArray()
|
||||
val games = (0 until data.length()).mapNotNull { data.optJSONObject(it) }
|
||||
.sortedByDescending { it.optString("game_type") == "game" }
|
||||
val best = TitleMatch.pick(title, games) { g -> listOf(g.optString("game_name")) + g.optString("game_alias").split(',') }
|
||||
Fetched.Answer(best?.let {
|
||||
val page = it.optInt("game_id").takeIf { id -> id > 0 }?.let { id -> "$HLTB/game/$id" } ?: hltbSearch(title)
|
||||
Hltb(it.optInt("comp_main"), it.optInt("comp_plus"), it.optInt("comp_100"), page)
|
||||
}?.takeUnless { it.isEmpty })
|
||||
}.getOrElse {
|
||||
Log.w(TAG, "HowLongToBeat answer unreadable: ${it.javaClass.simpleName}")
|
||||
Fetched.Failed
|
||||
}
|
||||
}
|
||||
|
||||
/** A store's release date ("2015.05.19", "2015-05-19T00:00:00+02:00", ...) in the reader's own words, or null. */
|
||||
fun releaseLabel(raw: String): String? {
|
||||
val m = Regex("""^(\d{4})[.\-/](\d{2})[.\-/](\d{2})""").find(raw.trim()) ?: return null
|
||||
val (y, mo, d) = m.destructured
|
||||
// Epic dates a title it has no date for 2099-01-01.
|
||||
val date = runCatching { LocalDate.of(y.toInt(), mo.toInt(), d.toInt()) }.getOrNull()?.takeIf { it.year in 1970..2098 } ?: return null
|
||||
return date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))
|
||||
}
|
||||
|
||||
/** Whole hours, with a half when the time is nearer one: "51½". Under an hour, null (the caller says minutes). */
|
||||
fun hours(seconds: Int): String? {
|
||||
if (seconds < 3600) return null
|
||||
val halves = Math.round(seconds / 1800.0).toInt()
|
||||
return "${halves / 2}" + if (halves % 2 == 1) "½" else ""
|
||||
}
|
||||
}
|
||||
|
||||
/** A fact looked up off the page: still asking, found, or not to be had. */
|
||||
sealed interface Lookup<out T> {
|
||||
object Pending : Lookup<Nothing>
|
||||
object None : Lookup<Nothing>
|
||||
data class Found<T>(val value: T) : Lookup<T>
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two catalogs mean the same game. Store titles carry marks, editions and subtitles the
|
||||
* other site spells differently ("The Witcher 3: Wild Hunt" is Steam's "...Wild Hunt — Remastered");
|
||||
* a sequel is never the same game ("Hades" is not "Hades II").
|
||||
*/
|
||||
internal object TitleMatch {
|
||||
private val MARKS = Regex("[™®©]")
|
||||
private val EDITION = Regex(
|
||||
"(?i)[\\s:\\-–—]*\\b(?:(?:complete|definitive|legendary|deluxe|ultimate|enhanced|gold|premium|standard|special|anniversary|collector'?s|digital deluxe|game of the year|goty)\\s+edition|goty|director'?s cut)\\b",
|
||||
)
|
||||
// Where a subtitle starts: a colon or dash with space around it, or an opening bracket.
|
||||
private val SUBTITLE = Regex("\\s*[:–—]\\s*|\\s+-\\s+|\\s*\\(")
|
||||
|
||||
fun normalize(s: String): String = s.lowercase().replace(MARKS, "").replace("&", "and").replace(Regex("[^\\p{L}\\p{N}]"), "")
|
||||
|
||||
fun stripEdition(s: String): String = s.replace(EDITION, " ").trim().ifEmpty { s }
|
||||
|
||||
/**
|
||||
* What to type into another site's search: the title without its marks, edition or subtitle
|
||||
* punctuation (Steam finds nothing for "Disco Elysium - The Final Cut", all of it for the words).
|
||||
*/
|
||||
fun searchTerm(title: String): String =
|
||||
stripEdition(title.replace(MARKS, "")).replace(Regex("\\s+[-–—]\\s+|[:–—()\\[\\]]"), " ").replace(Regex("\\s+"), " ").trim()
|
||||
|
||||
/** 3 the same name, 2 the same but for the edition, 1 one is the other with a subtitle, 0 not the same game. */
|
||||
fun score(want: String, got: String): Int {
|
||||
val w = normalize(want)
|
||||
val g = normalize(got)
|
||||
if (w.isEmpty() || g.isEmpty()) return 0
|
||||
if (w == g) return 3
|
||||
val ws = normalize(stripEdition(want))
|
||||
val gs = normalize(stripEdition(got))
|
||||
if (ws == gs || ws == g || w == gs) return 2
|
||||
if (ws in heads(got) || gs in heads(want)) return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
/** The title up to each place a subtitle could start, normalized. */
|
||||
private fun heads(title: String): Set<String> =
|
||||
SUBTITLE.findAll(title).map { normalize(title.substring(0, it.range.first)) }.filter { it.isNotEmpty() }.toSet()
|
||||
|
||||
/** The best-named of [items] in their order (the site's own ranking breaks a tie), or null when none is the game. */
|
||||
fun <T> pick(want: String, items: List<T>, names: (T) -> List<String>): T? {
|
||||
var best: T? = null
|
||||
var bestScore = 0
|
||||
for (item in items) {
|
||||
val s = names(item).filter { it.isNotBlank() }.maxOfOrNull { score(want, it.trim()) } ?: 0
|
||||
if (s > bestScore) { best = item; bestScore = s }
|
||||
}
|
||||
return best
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ data class CatalogItem(
|
||||
/** The web product page: where "Get for free" and "View on <store>" land. */
|
||||
val storeUrl: String = "",
|
||||
val developer: String = "",
|
||||
val publisher: String = "",
|
||||
val releaseDate: String = "",
|
||||
val description: String = "",
|
||||
/** True for a title the signed-in account owns (a library entry). */
|
||||
|
||||
@@ -90,6 +90,7 @@ class StoreGameSidecar(
|
||||
const val VERSION = 1
|
||||
const val STATE_INSTALLED = "installed"
|
||||
const val STATE_INSTALLING = "installing"
|
||||
const val STATE_UPDATING = "updating"
|
||||
|
||||
fun file(folder: File): File = File(folder, FILE_NAME)
|
||||
|
||||
|
||||
@@ -20,13 +20,68 @@ import java.util.zip.CRC32
|
||||
* shortcut's path - and with it its appid - stays the same from one session to the next.
|
||||
*/
|
||||
object StoreInstallRoot {
|
||||
const val SPACE_UNKNOWN = -1L
|
||||
private const val INTERNAL = "root/Games/Stores"
|
||||
private const val ON_VOLUME = "Games"
|
||||
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
|
||||
|
||||
/** One place a game can be installed: the folder, its name for the dialog, and whether it is a card. */
|
||||
class Target(val root: File, val label: String, val removable: Boolean) {
|
||||
val freeBytes: Long get() = try { StatFs((if (root.isDirectory) root else root.parentFile ?: root).path).availableBytes } catch (e: Exception) { 0L }
|
||||
val freeBytes: Long get() = availableBytes(root)
|
||||
}
|
||||
|
||||
data class StorageCheck(
|
||||
val enough: Boolean,
|
||||
val requiredBytes: Long,
|
||||
val availableBytes: Long,
|
||||
val errorMessage: String? = null
|
||||
)
|
||||
|
||||
@JvmStatic
|
||||
fun availableBytes(file: File): Long = probeAvailableBytes(file, { StatFs(it.path).availableBytes }, { it.usableSpace })
|
||||
|
||||
internal fun probeAvailableBytes(file: File, statBytes: (File) -> Long, usableBytes: (File) -> Long): Long {
|
||||
var dir: File? = if (file.isDirectory) file else file.parentFile
|
||||
if (dir == null) dir = file
|
||||
while (dir != null && !dir.exists()) dir = dir.parentFile
|
||||
val existing = dir ?: return SPACE_UNKNOWN
|
||||
return try {
|
||||
statBytes(existing).coerceAtLeast(SPACE_UNKNOWN)
|
||||
} catch (e: Exception) {
|
||||
StoresState.logLine("storage: StatFs failed for store install target (${e.javaClass.simpleName})")
|
||||
try {
|
||||
// File's zero also means an unavailable measurement; only StatFs establishes zero.
|
||||
usableBytes(existing).takeIf { it > 0L } ?: SPACE_UNKNOWN
|
||||
} catch (fallback: Exception) {
|
||||
StoresState.logLine("storage: usable-space fallback failed for store install target (${fallback.javaClass.simpleName})")
|
||||
SPACE_UNKNOWN
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun insufficientSpace(required: Long, available: Long): Boolean = required > 0L && available >= 0L && available < required
|
||||
|
||||
/**
|
||||
* The catalog size is the known minimum for an install. Epic's actual chunk-cache requirement
|
||||
* is determined from its manifest before chunk downloads begin.
|
||||
*/
|
||||
fun estimatedBytesNeeded(item: CatalogItem): Long = StoreSizes.size(item).coerceAtLeast(0L)
|
||||
|
||||
/** Pre-install storage check to detect insufficient space before starting. */
|
||||
fun checkStorage(context: Context, item: CatalogItem, targetRoot: File): StorageCheck {
|
||||
val size = estimatedBytesNeeded(item)
|
||||
val existing = existingFolder(context, item.store, item.id, item.title)
|
||||
val freeTarget = availableBytes(existing ?: targetRoot)
|
||||
// Backends account for completed files on resume; the catalog cannot describe remaining work.
|
||||
// Comparing the full catalog size to remaining free space would reject valid resumes.
|
||||
if (item.store == Store.EPIC || existing != null) return StorageCheck(enough = true, requiredBytes = size, availableBytes = freeTarget)
|
||||
if (size <= 0L) return StorageCheck(enough = true, requiredBytes = 0L, availableBytes = freeTarget)
|
||||
if (insufficientSpace(size, freeTarget)) {
|
||||
val msg = context.getString(com.droiddeck.launcher.R.string.stores_storage_insufficient, formatBytes(size), formatBytes(freeTarget))
|
||||
return StorageCheck(enough = false, requiredBytes = size, availableBytes = freeTarget, errorMessage = msg)
|
||||
}
|
||||
return StorageCheck(enough = true, requiredBytes = size, availableBytes = freeTarget)
|
||||
}
|
||||
|
||||
/** The internal root: always there, always the default. */
|
||||
|
||||
@@ -7,6 +7,8 @@ import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.frontend.LibraryCache
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
/**
|
||||
* What happens around a store install so the rest of the app sees the game: the sidecar is
|
||||
@@ -30,10 +32,28 @@ object StoreInstalls {
|
||||
* updated keeps its finished sidecar, so the game stays in Steam meanwhile.
|
||||
*/
|
||||
fun begin(folder: File, store: Store, id: String, title: String, cover: String?, hero: String?) {
|
||||
if (StoreGameSidecar.read(folder)?.isInstalled == true) return
|
||||
val before = StoreGameSidecar.read(folder)
|
||||
if (before?.isInstalled == true || before?.state == StoreGameSidecar.STATE_UPDATING) return
|
||||
StoreGameSidecar(store, id, title, exe = "", cover = cover, hero = hero, state = StoreGameSidecar.STATE_INSTALLING).write(folder)
|
||||
}
|
||||
|
||||
/** Epic commits verified files individually, not a whole-game transaction. Keep updates resumable. */
|
||||
@JvmStatic
|
||||
fun markUpdating(folder: File) {
|
||||
val before = StoreGameSidecar.read(folder) ?: return
|
||||
if (!before.isInstalled) return
|
||||
val stage = File.createTempFile(".droiddeck-update-", ".stage", folder)
|
||||
try {
|
||||
java.io.FileOutputStream(stage).use {
|
||||
it.write(before.copy(state = StoreGameSidecar.STATE_UPDATING, installVersion = "").toJson().toString(2).toByteArray(Charsets.UTF_8))
|
||||
it.fd.sync()
|
||||
}
|
||||
Files.move(stage.toPath(), StoreGameSidecar.file(folder).toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
|
||||
} finally {
|
||||
stage.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes an install: writes the launcher and the finished sidecar, then the art, then
|
||||
* registers the game. Runs on the caller's worker thread. The launcher and sidecar writes
|
||||
@@ -105,16 +125,18 @@ object StoreInstalls {
|
||||
/**
|
||||
* What Cancel does: everything the install wrote goes - the game folder with its sidecar and
|
||||
* the caches in [caches] - unless the folder holds a finished install being repaired or updated;
|
||||
* then only the caches go and the working game stays. Off the caller's thread; the library
|
||||
* follows when it is done, so the game reads Install again.
|
||||
* then only the caches go. An Epic `updating` folder is retained too: its verified swaps are
|
||||
* not rolled back, and it must be resumed before being advertised as installed again.
|
||||
* Off the caller's thread; the library follows when it is done.
|
||||
*/
|
||||
fun discard(context: Context, folder: File, caches: List<File>) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val keep = StoreGameSidecar.read(folder)?.isInstalled == true
|
||||
val sidecar = StoreGameSidecar.read(folder)
|
||||
val keep = sidecar?.isInstalled == true || sidecar?.state == StoreGameSidecar.STATE_UPDATING
|
||||
caches.forEach { deleteTree(it) }
|
||||
if (!keep) deleteTree(folder)
|
||||
StoresState.logLine(if (keep) "removed the partial update of ${folder.name}" else "removed ${folder.name}")
|
||||
StoresState.logLine(if (keep) "removed update caches for ${folder.name}; verified file swaps are retained" else "removed ${folder.name}")
|
||||
StoresState.notifyLibraryChanged(app)
|
||||
}, "store-cancel-clean").start()
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ internal object StoreNet {
|
||||
}
|
||||
}
|
||||
|
||||
fun postJson(url: String, body: String, bearer: String? = null, userAgent: String = BROWSER_UA, timeoutMs: Int = 25_000): String? {
|
||||
fun postJson(url: String, body: String, bearer: String? = null, userAgent: String = BROWSER_UA, timeoutMs: Int = 25_000, headers: Map<String, String> = emptyMap()): String? {
|
||||
var conn: HttpURLConnection? = null
|
||||
return try {
|
||||
conn = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
@@ -53,6 +53,7 @@ internal object StoreNet {
|
||||
setRequestProperty("Content-Type", "application/json")
|
||||
setRequestProperty("Accept", "application/json")
|
||||
if (bearer != null) setRequestProperty("Authorization", "Bearer $bearer")
|
||||
headers.forEach { (k, v) -> setRequestProperty(k, v) }
|
||||
}
|
||||
OutputStreamWriter(conn.outputStream, "UTF-8").use { it.write(body) }
|
||||
val code = conn.responseCode
|
||||
|
||||
@@ -219,7 +219,25 @@ object StoresState {
|
||||
/** Starts an install into [root] (the internal root when null). */
|
||||
fun install(context: Context, item: CatalogItem, root: java.io.File? = null) {
|
||||
val app = context.applicationContext
|
||||
val target = root ?: StoreInstallRoot.installRoot(app)
|
||||
val folder = StoreInstallRoot.folderFor(app, item.store, item.id, item.title, root ?: StoreInstallRoot.installRoot(app))
|
||||
val target = folder.parentFile!!.parentFile!!
|
||||
val check = StoreInstallRoot.checkStorage(app, item, target)
|
||||
if (!check.enough) {
|
||||
val errorMsg = check.errorMessage ?: app.getString(com.droiddeck.launcher.R.string.stores_storage_insufficient, formatBytes(check.requiredBytes), formatBytes(check.availableBytes))
|
||||
val entry = com.droiddeck.launcher.stores.download.DownloadEntry(
|
||||
item.store,
|
||||
item.id,
|
||||
item.title,
|
||||
cover = item.imageUrl,
|
||||
bytesTotal = item.sizeBytes,
|
||||
location = StoreInstallRoot.labelFor(app, folder)
|
||||
)
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, target)
|
||||
com.droiddeck.launcher.stores.download.DownloadQueue.recordFailed(app, entry, errorMsg) {
|
||||
install(app, item, target)
|
||||
}
|
||||
return
|
||||
}
|
||||
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, target)
|
||||
backends[item.store]?.install(app, item, target) ?: logLine("${item.store.label}: this build cannot install yet")
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ object AmazonBackend : StoreBackend {
|
||||
val quiet = cached.isNotEmpty() && !force
|
||||
StoresState.post {
|
||||
if (cached.isNotEmpty()) publish(app, cached)
|
||||
if (!quiet) StoresState.status[store] = "Fetching your library…"
|
||||
if (!quiet) StoresState.status[store] = app.getString(com.droiddeck.launcher.R.string.stores_sync_library)
|
||||
}
|
||||
val result = AmazonLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
|
||||
StoresState.post {
|
||||
@@ -94,7 +94,7 @@ object AmazonBackend : StoreBackend {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
handle.stage(DownloadStage.MANIFEST, "Checking sign-in…")
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(com.droiddeck.launcher.R.string.stores_sync_sign_in))
|
||||
val token = AmazonCredentialStore.getValidAccessToken(app) ?: throw AmazonDownloadManager.InstallException("Not signed in to Amazon Games")
|
||||
StoreInstalls.begin(folder, Store.AMAZON, game.productId, game.title, item.tallImageUrl ?: item.imageUrl, item.imageUrl)
|
||||
var downloading = false
|
||||
@@ -111,7 +111,7 @@ object AmazonBackend : StoreBackend {
|
||||
override fun onSizes(downloadBytes: Long, diskBytes: Long) { handle.diskSize(diskBytes) }
|
||||
}) ?: return null
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL, "Registering with Steam…")
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(com.droiddeck.launcher.R.string.stores_registering))
|
||||
AmazonLibrary.rememberSize(app, game.productId, result.bytes)
|
||||
AmazonPrefs.get(app).edit().putString("version_${game.productId}", result.versionId).apply()
|
||||
val spec = AmazonLaunchHelper.buildLaunchSpec(folder, game.title)
|
||||
|
||||
@@ -77,9 +77,10 @@ public final class AmazonDownloadManager {
|
||||
if (manifestBytes == null) throw new InstallException("The manifest could not be downloaded");
|
||||
AmazonManifest.ParsedManifest manifest = AmazonManifest.parse(manifestBytes);
|
||||
cb.onLog("amazon: " + manifest.allFiles.size() + " files, " + fmt(manifest.totalInstallSize));
|
||||
long usable = installDir.getUsableSpace();
|
||||
if (manifest.totalInstallSize > 0 && usable > 0 && manifest.totalInstallSize > usable)
|
||||
throw new InstallException("Not enough free space: need " + fmt(manifest.totalInstallSize) + ", only " + fmt(usable) + " free");
|
||||
long remainingBytes = remainingInstallBytes(manifest.allFiles, installDir);
|
||||
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installDir);
|
||||
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(remainingBytes, usable))
|
||||
throw new InstallException("Not enough free space: need " + fmt(remainingBytes) + ", only " + fmt(usable) + " free");
|
||||
cb.onSizes(manifest.totalInstallSize, manifest.totalInstallSize);
|
||||
cb.onBytes(0, manifest.totalInstallSize, 0);
|
||||
if (cancel.get()) return null;
|
||||
@@ -184,7 +185,7 @@ public final class AmazonDownloadManager {
|
||||
AtomicLong lastSpeedMs, AtomicLong lastSpeedBytes, AtomicLong speedBps, Callback cb, AtomicBoolean cancel) {
|
||||
File destFile = new File(installDir, file.unixPath());
|
||||
File tmpFile = new File(installDir, file.unixPath() + ".tmp");
|
||||
if (destFile.exists() && destFile.length() == file.size) { totalDownloaded.addAndGet(file.size); return true; }
|
||||
if (fileComplete(file, destFile)) { totalDownloaded.addAndGet(file.size); return true; }
|
||||
String fileUrl = AmazonApiClient.appendPath(baseUrl, "files/" + file.hashHex());
|
||||
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
destFile.getParentFile().mkdirs();
|
||||
@@ -256,6 +257,21 @@ public final class AmazonDownloadManager {
|
||||
|
||||
public static boolean isInstalled(File installDir) { return new File(installDir, COMPLETE_MARKER).exists(); }
|
||||
|
||||
static long remainingInstallBytes(List<AmazonManifest.ManifestFile> files, File installDir) {
|
||||
long remaining = 0;
|
||||
for (AmazonManifest.ManifestFile file : files) {
|
||||
if (!fileComplete(file, new File(installDir, file.unixPath()))) remaining += file.size;
|
||||
}
|
||||
return remaining;
|
||||
}
|
||||
|
||||
private static boolean fileComplete(AmazonManifest.ManifestFile file, File output) {
|
||||
if (!output.isFile() || output.length() != file.size) return false;
|
||||
if (file.hashAlgorithm != 0 || file.hashBytes.length == 0) return true;
|
||||
try { return Arrays.equals(sha256(output), file.hashBytes); }
|
||||
catch (Exception e) { return false; }
|
||||
}
|
||||
|
||||
private static byte[] sha256(File file) throws Exception {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
try (FileInputStream fis = new FileInputStream(file)) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.stores.amazon
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
@@ -66,38 +67,38 @@ object AmazonLibrary {
|
||||
val p = AmazonPrefs.get(app)
|
||||
val cachedList = cached(app)
|
||||
if (!force && cachedList.isNotEmpty() && System.currentTimeMillis() - p.getLong(LAST_SYNC_KEY, 0L) < THROTTLE_MS) {
|
||||
backfillPosters(p, cachedList, onStatus)
|
||||
backfillPosters(app, p, cachedList, onStatus)
|
||||
return SyncResult.Throttled
|
||||
}
|
||||
onStatus("Checking sign-in…")
|
||||
onStatus(app.getString(R.string.stores_sync_sign_in))
|
||||
val creds = AmazonCredentialStore.load(app) ?: return SyncResult.NotLoggedIn
|
||||
val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed(StoresState.notSignedInLine(Store.AMAZON))
|
||||
onStatus("Fetching game list…")
|
||||
onStatus(app.getString(R.string.stores_sync_game_list))
|
||||
// Refused with the stored token (revoked, or an expiry read wrong): once more on a fresh one.
|
||||
val all = AmazonApiClient.getEntitlements(token, creds.deviceSerial)
|
||||
?: AmazonCredentialStore.refresh(app)?.let { AmazonApiClient.getEntitlements(it, creds.deviceSerial) }
|
||||
if (all == null) return if (cachedList.isEmpty()) SyncResult.Failed("Amazon Games did not answer for your library: refresh, or sign in again") else SyncResult.Ok(cachedList)
|
||||
if (all.isEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed("No games found in your Amazon library") else SyncResult.Ok(cachedList)
|
||||
if (all == null) return if (cachedList.isEmpty()) SyncResult.Failed(app.getString(R.string.stores_sync_amazon_no_answer)) else SyncResult.Ok(cachedList)
|
||||
if (all.isEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed(app.getString(R.string.stores_sync_no_games, Store.AMAZON.label)) else SyncResult.Ok(cachedList)
|
||||
val games = all.filter { !(it.isDLC && it.parentProductId.isNotEmpty()) }.ifEmpty { all }
|
||||
.sortedWith { a, b -> a.title.compareTo(b.title, ignoreCase = true) }
|
||||
for (fresh in games) cachedList.firstOrNull { it.productId == fresh.productId }?.let { fresh.versionId = it.versionId }
|
||||
saveCache(p, games)
|
||||
p.edit().putLong(LAST_SYNC_KEY, System.currentTimeMillis()).apply()
|
||||
backfillPosters(p, games, onStatus)
|
||||
backfillPosters(app, p, games, onStatus)
|
||||
Log.i(TAG, "sync: entitlements=${all.size} games=${games.size}")
|
||||
return SyncResult.Ok(games)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "sync failed: ${e.message}")
|
||||
return SyncResult.Failed(e.message ?: "Sync failed")
|
||||
return SyncResult.Failed(e.message ?: context.getString(R.string.stores_sync_failed))
|
||||
} finally {
|
||||
syncing.set(false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun backfillPosters(p: SharedPreferences, games: List<AmazonGame>, onStatus: (String) -> Unit) {
|
||||
private fun backfillPosters(app: Context, p: SharedPreferences, games: List<AmazonGame>, onStatus: (String) -> Unit) {
|
||||
val missing = games.filter { it.productId.isNotEmpty() && !p.contains("vcover_${it.productId}") }.take(POSTER_BUDGET)
|
||||
if (missing.isEmpty()) return
|
||||
onStatus("Fetching cover art…")
|
||||
onStatus(app.getString(R.string.stores_sync_cover_art))
|
||||
val pool = Executors.newFixedThreadPool(4)
|
||||
val futures = missing.map { g -> pool.submit(Callable { g.productId to StoreNet.sgdbPoster(g.title) }) }
|
||||
pool.shutdown()
|
||||
|
||||
@@ -128,7 +128,7 @@ object DownloadQueue {
|
||||
}
|
||||
}
|
||||
|
||||
private class Item(var entry: DownloadEntry, val factory: () -> DownloadJob, var job: DownloadJob? = null, val cancelled: AtomicBoolean = AtomicBoolean(false), var pauseRequested: Boolean = false) {
|
||||
private class Item(var entry: DownloadEntry, val factory: (() -> DownloadJob)? = null, val retry: (() -> Unit)? = null, var job: DownloadJob? = null, val cancelled: AtomicBoolean = AtomicBoolean(false), var pauseRequested: Boolean = false) {
|
||||
/** The shown speed's state: the last sample's clock and bytes, and the running average (bytes/s). */
|
||||
var speedAt = 0L
|
||||
var speedBytes = 0L
|
||||
@@ -185,6 +185,32 @@ object DownloadQueue {
|
||||
advance(app)
|
||||
}
|
||||
|
||||
/** Immediately records a failed download (e.g. from pre-flight storage check). */
|
||||
fun recordFailed(context: Context, entry: DownloadEntry, error: String, retry: (() -> Unit)? = null) {
|
||||
val app = context.applicationContext
|
||||
val now = System.currentTimeMillis()
|
||||
synchronized(lock) {
|
||||
if (items[entry.key]?.entry?.isActive == true) return
|
||||
items.remove(entry.key)
|
||||
heldPaused.remove(entry.key)
|
||||
items[entry.key] = Item(
|
||||
entry.copy(
|
||||
state = DownloadState.FAILED,
|
||||
error = error,
|
||||
speedBps = 0,
|
||||
etaSeconds = -1,
|
||||
startedAt = now,
|
||||
finishedAt = now
|
||||
),
|
||||
retry = retry
|
||||
)
|
||||
renumber()
|
||||
publishLocked()
|
||||
}
|
||||
StoresState.logLine("${entry.store.label}: \"${entry.name}\" failed: $error")
|
||||
StoreDownloadService.ended(app, entry.copy(state = DownloadState.FAILED, error = error), installed = false, gamesKey = null)
|
||||
}
|
||||
|
||||
fun pause(key: String) {
|
||||
val item = synchronized(lock) { items[key] } ?: return
|
||||
synchronized(lock) {
|
||||
@@ -199,14 +225,21 @@ object DownloadQueue {
|
||||
|
||||
fun resume(context: Context, key: String) {
|
||||
val app = context.applicationContext
|
||||
val retry: (() -> Unit)?
|
||||
synchronized(lock) {
|
||||
val item = items[key] ?: return
|
||||
if (item.entry.state != DownloadState.PAUSED && item.entry.state != DownloadState.FAILED) return
|
||||
retry = item.retry
|
||||
if (retry == null && item.factory == null) return
|
||||
items.remove(key)
|
||||
items[key] = Item(item.entry.copy(state = DownloadState.QUEUED, speedBps = 0, etaSeconds = -1, error = null, startedAt = System.currentTimeMillis()), item.factory)
|
||||
if (retry == null) {
|
||||
items[key] = Item(item.entry.copy(state = DownloadState.QUEUED, speedBps = 0, etaSeconds = -1, error = null, startedAt = System.currentTimeMillis()), item.factory)
|
||||
}
|
||||
renumber()
|
||||
publishLocked()
|
||||
}
|
||||
// A preflight retry rechecks storage and enqueues the real backend, never a running placeholder.
|
||||
if (retry != null) { retry(); return }
|
||||
StoresState.logLine("resumed \"${entry(key)?.name}\"")
|
||||
advance(app)
|
||||
}
|
||||
@@ -231,7 +264,7 @@ object DownloadQueue {
|
||||
item.job?.cancel(deleteFiles = true)
|
||||
} else {
|
||||
// Never started: nothing is on disk, but the job knows where it would have gone.
|
||||
Thread({ runCatching { item.factory().cancel(deleteFiles = true) } }, "store-dl-cancel").start()
|
||||
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-cancel").start()
|
||||
}
|
||||
StoresState.logLine("cancelled \"${item.entry.name}\"")
|
||||
StoreDownloadService.finish(app, key)
|
||||
@@ -248,7 +281,7 @@ object DownloadQueue {
|
||||
val item = synchronized(lock) { items[key] } ?: return
|
||||
if (item.entry.state == DownloadState.RUNNING || item.entry.state == DownloadState.QUEUED) return
|
||||
if (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) {
|
||||
Thread({ runCatching { item.factory().cancel(deleteFiles = true) } }, "store-dl-clear").start()
|
||||
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-clear").start()
|
||||
}
|
||||
synchronized(lock) { items.remove(key); publishLocked() }
|
||||
StoreDownloadService.finish(context.applicationContext, key)
|
||||
@@ -343,7 +376,7 @@ object DownloadQueue {
|
||||
var result: String? = null
|
||||
var error: String? = null
|
||||
try {
|
||||
val job = item.factory()
|
||||
val job = checkNotNull(item.factory).invoke()
|
||||
synchronized(lock) { item.job = job }
|
||||
StoresState.logLine("${item.entry.store.label}: fetching manifest for \"${item.entry.name}\"")
|
||||
result = job.run(handle)
|
||||
|
||||
@@ -263,12 +263,16 @@ class StoreDownloadService : Service() {
|
||||
val app = context.applicationContext
|
||||
channels(app)
|
||||
val code = entry.key.hashCode()
|
||||
val n = Notification.Builder(app, DONE_CHANNEL)
|
||||
val builder = Notification.Builder(app, DONE_CHANNEL)
|
||||
.setSmallIcon(if (installed) android.R.drawable.stat_sys_download_done else android.R.drawable.stat_notify_error)
|
||||
.setContentTitle(app.getString(if (installed) R.string.stores_notification_installed else R.string.stores_notification_failed, entry.name))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(if (installed && gamesKey != null) openPage(app, gamesKey, code + 10) else openDownloads(app, code + 11))
|
||||
.build()
|
||||
if (!installed && !entry.error.isNullOrBlank()) {
|
||||
builder.setContentText(entry.error)
|
||||
builder.style = Notification.BigTextStyle().bigText(entry.error)
|
||||
}
|
||||
val n = builder.build()
|
||||
runCatching { app.getSystemService(NotificationManager::class.java)?.notify(ID + 1 + (code and 0xFFFF), n) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +103,11 @@ public final class EpicApiClient {
|
||||
if (attrs != null) {
|
||||
JSONObject offline = attrs.optJSONObject("CanRunOffline");
|
||||
if (offline != null) game.canRunOffline = !"false".equalsIgnoreCase(offline.optString("value", "true"));
|
||||
JSONObject publisher = attrs.optJSONObject("publisherName");
|
||||
if (publisher != null) game.publisher = publisher.optString("value", "").trim();
|
||||
}
|
||||
JSONObject seller = item.optJSONObject("seller");
|
||||
if (game.publisher.isEmpty() && seller != null) game.publisher = seller.optString("name", "").trim();
|
||||
String rd = item.optString("viewableDate", "");
|
||||
if (rd.isEmpty()) rd = item.optString("effectiveDate", "");
|
||||
if (!rd.isEmpty()) game.releaseDate = rd;
|
||||
|
||||
@@ -47,7 +47,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
val quiet = cached.isNotEmpty() && !force
|
||||
StoresState.post {
|
||||
if (cached.isNotEmpty()) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached)
|
||||
if (!quiet) StoresState.status[store] = "Fetching your library…"
|
||||
if (!quiet) StoresState.status[store] = app.getString(com.droiddeck.launcher.R.string.stores_sync_library)
|
||||
}
|
||||
val result = EpicLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
|
||||
StoresState.post {
|
||||
@@ -80,7 +80,12 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
val byCatalogItem = owned.associateBy { it.extra["catalogItemId"] ?: "" }
|
||||
fun mark(l: List<CatalogItem>) = l.map { i ->
|
||||
val match = i.extra["items"]?.split(',')?.firstNotNullOfOrNull { byCatalogItem[it] }
|
||||
if (match != null) match.copy(imageUrl = i.imageUrl ?: match.imageUrl, tallImageUrl = i.tallImageUrl ?: match.tallImageUrl) else i
|
||||
// The offer's art, and its facts where the library's catalog record has none.
|
||||
if (match != null) match.copy(
|
||||
imageUrl = i.imageUrl ?: match.imageUrl, tallImageUrl = i.tallImageUrl ?: match.tallImageUrl,
|
||||
developer = match.developer.ifBlank { i.developer }, publisher = match.publisher.ifBlank { i.publisher },
|
||||
releaseDate = match.releaseDate.ifBlank { i.releaseDate },
|
||||
) else i
|
||||
}
|
||||
return StoreShelves(mark(s.whatsNew), mark(s.deals), mark(s.free), mark(s.trending))
|
||||
}
|
||||
@@ -117,7 +122,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
private fun hasChunks(dir: File): Boolean = dir.isDirectory && (dir.list()?.isNotEmpty() == true)
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
handle.stage(DownloadStage.MANIFEST, "Checking sign-in…")
|
||||
handle.stage(DownloadStage.MANIFEST, app.getString(com.droiddeck.launcher.R.string.stores_sync_sign_in))
|
||||
val token = EpicCredentialStore.getValidAccessToken(app) ?: throw EpicDownloadManager.InstallException("Not signed in to Epic Games")
|
||||
StoreInstalls.begin(folder, Store.EPIC, item.id, item.title, item.tallImageUrl ?: item.imageUrl, item.imageUrl)
|
||||
if (scratch == null && hasChunks(File(folder, ".chunks"))) handle.log("epic: resuming \"${item.title}\" with the chunks already beside it")
|
||||
@@ -141,12 +146,14 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
EpicLibrary.rememberSize(app, item.id, diskBytes)
|
||||
}
|
||||
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
|
||||
// Assembly overlaps chunk fetching; only the final install event advances the UI.
|
||||
if (stage == "stream") return
|
||||
handle.stage(when (stage) { "check" -> DownloadStage.MANIFEST; "verify" -> DownloadStage.VERIFY; else -> DownloadStage.INSTALL })
|
||||
handle.stageProgress(done, total, items, itemsTotal, bytes = stage == "install")
|
||||
}
|
||||
}) ?: return null
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL, "Registering with Steam…")
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(com.droiddeck.launcher.R.string.stores_registering))
|
||||
EpicLibrary.rememberSize(app, item.id, result.bytes)
|
||||
val deploymentId = runCatching { JSONObject(manifestJson).optString("deploymentId", "") }.getOrDefault("")
|
||||
val exe = StoreExe.pick(folder, result.launchExe, item.title)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -22,4 +22,5 @@ public class EpicGame {
|
||||
public boolean isDLC = false;
|
||||
public String baseGameCatalogItemId = "";
|
||||
public String releaseDate = "";
|
||||
public String publisher = "";
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.stores.epic
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import org.json.JSONArray
|
||||
@@ -44,6 +45,8 @@ object EpicLibrary {
|
||||
g.developer = j.optString("developer", ""); g.description = j.optString("description", ""); g.version = j.optString("version", "")
|
||||
g.installSize = j.optLong("installSize", 0L).let { if (it > 1_099_511_627_776L) 0L else it }
|
||||
g.canRunOffline = j.optBoolean("canRunOffline", true)
|
||||
g.releaseDate = j.optString("releaseDate", "")
|
||||
g.publisher = j.optString("publisher", "")
|
||||
if (g.appName.isNotEmpty()) list.add(g)
|
||||
}
|
||||
list.distinctBy { it.appName }.sortedBy { it.title.lowercase() }
|
||||
@@ -65,18 +68,17 @@ object EpicLibrary {
|
||||
val cachedList = cached(app)
|
||||
val lastSync = p.getLong(LAST_SYNC_KEY, 0L)
|
||||
if (!force && cachedList.isNotEmpty() && System.currentTimeMillis() - lastSync < THROTTLE_MS) return SyncResult.Throttled
|
||||
onStatus("Checking sign-in…")
|
||||
onStatus(app.getString(R.string.stores_sync_sign_in))
|
||||
val token = EpicCredentialStore.getValidAccessToken(app) ?: return SyncResult.NotLoggedIn
|
||||
onStatus("Fetching game list…")
|
||||
onStatus(app.getString(R.string.stores_sync_game_list))
|
||||
val raw = EpicApiClient.getLibraryItems(token)
|
||||
if (raw.isNullOrEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed("No games found in your Epic library") else SyncResult.Ok(cachedList)
|
||||
if (raw.isNullOrEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed(app.getString(R.string.stores_sync_no_games, Store.EPIC.label)) else SyncResult.Ok(cachedList)
|
||||
val total = raw.size
|
||||
var done = 0
|
||||
for (game in raw) {
|
||||
EpicApiClient.enrichFromCatalog(token, game)
|
||||
if (game.releaseDate.isNotEmpty()) p.edit().putString("release_${game.appName}", game.releaseDate).apply()
|
||||
done++
|
||||
if (done % 5 == 0) onStatus("Loading game details… ($done/$total)")
|
||||
if (done % 5 == 0) onStatus(app.getString(R.string.stores_sync_details, done, total))
|
||||
}
|
||||
val main = raw.filter { !it.isDLC }
|
||||
val display = (if (main.isEmpty()) raw else main).distinctBy { it.appName }.sortedWith { a, b -> a.title.compareTo(b.title, ignoreCase = true) }
|
||||
@@ -91,7 +93,7 @@ object EpicLibrary {
|
||||
return SyncResult.Ok(display)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "sync failed: ${e.message}")
|
||||
return SyncResult.Failed(e.message ?: "Sync failed")
|
||||
return SyncResult.Failed(e.message ?: context.getString(R.string.stores_sync_failed))
|
||||
} finally {
|
||||
syncing.set(false)
|
||||
}
|
||||
@@ -102,7 +104,8 @@ object EpicLibrary {
|
||||
val arr = JSONArray()
|
||||
for (g in games) arr.put(JSONObject().put("appName", g.appName).put("namespace", g.namespace).put("catalogItemId", g.catalogItemId)
|
||||
.put("title", g.title).put("artCover", g.artCover).put("artSquare", g.artSquare).put("developer", g.developer)
|
||||
.put("description", g.description).put("version", g.version).put("installSize", g.installSize).put("canRunOffline", g.canRunOffline))
|
||||
.put("description", g.description).put("version", g.version).put("installSize", g.installSize).put("canRunOffline", g.canRunOffline)
|
||||
.put("releaseDate", g.releaseDate).put("publisher", g.publisher))
|
||||
prefs.edit().putString(CACHE_KEY, arr.toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -111,7 +114,9 @@ object EpicLibrary {
|
||||
store = Store.EPIC, id = g.appName, title = g.title.ifBlank { g.appName },
|
||||
imageUrl = g.artSquare.ifBlank { null } ?: g.artCover.ifBlank { null },
|
||||
tallImageUrl = g.artCover.ifBlank { null } ?: g.artSquare.ifBlank { null },
|
||||
developer = g.developer, description = com.droiddeck.launcher.stores.cleanStoreText(g.description), owned = true,
|
||||
developer = g.developer, publisher = g.publisher, description = com.droiddeck.launcher.stores.cleanStoreText(g.description), owned = true,
|
||||
// A cache from before the release date was kept still has it under the older per-game key.
|
||||
releaseDate = g.releaseDate.ifEmpty { EpicPrefs.get(context).getString("release_${g.appName}", "").orEmpty() },
|
||||
sizeBytes = EpicPrefs.get(context).getLong("size_${g.appName}", g.installSize),
|
||||
storeUrl = "https://store.epicgames.com/en-US/browse?q=${java.net.URLEncoder.encode(g.title, "UTF-8")}",
|
||||
extra = mapOf("namespace" to g.namespace, "catalogItemId" to g.catalogItemId, "version" to (g.version ?: "")),
|
||||
|
||||
@@ -9,17 +9,20 @@ import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/**
|
||||
* The native half of an Epic install in `libdroiddeckstores.so`: [run] fills the chunk cache with
|
||||
* verified, decompressed chunks for the files the manager says are pending, [assemble] writes those
|
||||
* files from the cache. Everything around them (manifest, install tags, delta pass, post-install)
|
||||
* stays in the manager.
|
||||
* The native Epic engines in `libdroiddeckstores.so`. [stream] is the install the manager uses
|
||||
* whenever the library loads: chunks fetched in parallel by the adaptive fetch core and written
|
||||
* straight into each file's staging file as they arrive, shared chunks kept in a cache of at most
|
||||
* the given budget, every file verified and swapped in with the same rules as the bounded Java
|
||||
* writer (see `stream.rs`). [run] and [assemble] are the older batch pair: [run] fills the chunk
|
||||
* cache with verified, decompressed chunks for the pending files, [assemble] writes the files from
|
||||
* it. They stay for callers that explicitly want a whole-game cache.
|
||||
*
|
||||
* The cache is `<installDir>/.chunks` when `chunkCacheDir` is `""`, else the scratch folder given -
|
||||
* the app's own cache when the game installs to a card, where the assembler drops each chunk right
|
||||
* after its last use and the folder at the end. Both calls take the same value for one install.
|
||||
* the app's own cache when the game installs to a card.
|
||||
*
|
||||
* Both block like the Java loops they replace and poll [AtomicBoolean] `cancel` every 250 ms: on
|
||||
* cancel they flip the native flag, wait up to 5 s for the run to wind down, then return.
|
||||
* All block while polling [AtomicBoolean] `cancel` every 250 ms. [run] and [assemble] flip the
|
||||
* native flag on cancel and wait up to 5 s; [stream] waits for the run to finish, because its
|
||||
* cleanup (removing unfinished staging files) must be done before the manager returns.
|
||||
*/
|
||||
object EpicNative {
|
||||
private const val TAG = "EpicNative"
|
||||
@@ -36,6 +39,18 @@ object EpicNative {
|
||||
fun onComplete(success: Boolean, error: String, bytes: Long)
|
||||
}
|
||||
|
||||
/** Callbacks from a [stream] run; every method is called on a native thread. */
|
||||
interface StreamListener {
|
||||
/** File bytes written so far (staging included), and the files verified and swapped in so far. */
|
||||
fun onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long)
|
||||
/** Engine log line (already in logcat under `EpicNative`). */
|
||||
fun onLog(line: String)
|
||||
/** Once, before the first file replaces its destination; false (or a throw) fails the run with nothing replaced. */
|
||||
fun onBeforeReplace(): Boolean
|
||||
/** Terminal; `bytes` = file bytes written. */
|
||||
fun onComplete(success: Boolean, error: String, bytes: Long)
|
||||
}
|
||||
|
||||
/** Outcome of a run. `started == false`: nothing happened on disk, the caller runs its own loop. */
|
||||
class Result(
|
||||
@JvmField val started: Boolean, @JvmField val success: Boolean, @JvmField val cancelled: Boolean,
|
||||
@@ -58,6 +73,59 @@ object EpicNative {
|
||||
fun assemble(manifest: ByteArray, installDir: String, chunkCacheDir: String, fileIdx: IntArray, cancel: AtomicBoolean?, listener: Listener): Result =
|
||||
drive("nativeAssemble", cancel, listener) { inner -> nativeAssemble(manifest, installDir, chunkCacheDir, fileIdx, inner) }
|
||||
|
||||
/**
|
||||
* The adaptive install of the files [pendingFileIdx] (indices into the manifest's file list),
|
||||
* with at most [cacheBudget] bytes of shared chunks cached. `started == false` means nothing
|
||||
* was fetched or written and the caller runs the bounded Java writer.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun stream(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedBytes: Long,
|
||||
cacheBudget: Long, caBundlePath: String, maxWorkers: Int, processWorkers: Int, cancel: AtomicBoolean?, listener: StreamListener,
|
||||
): Result {
|
||||
if (!StoresNative.ensureLoaded()) return Result(false, false, false, "engine not built", 0L, 0, 0)
|
||||
val latch = CountDownLatch(1)
|
||||
val completion = AtomicReference<Completion?>(null)
|
||||
val doneRef = AtomicReference(0)
|
||||
val totalRef = AtomicReference(pendingFileIdx.size)
|
||||
val inner = object : StreamListener {
|
||||
override fun onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long) {
|
||||
doneRef.set(filesDone); totalRef.set(filesTotal)
|
||||
listener.onStreamProgress(bytesWritten, bytesTotal, filesDone, filesTotal, filesBytes)
|
||||
}
|
||||
override fun onLog(line: String) = listener.onLog(line)
|
||||
override fun onBeforeReplace(): Boolean = runCatching { listener.onBeforeReplace() }.getOrDefault(false)
|
||||
override fun onComplete(success: Boolean, error: String, bytes: Long) {
|
||||
completion.set(Completion(success, error, bytes))
|
||||
latch.countDown()
|
||||
runCatching { listener.onComplete(success, error, bytes) }
|
||||
}
|
||||
}
|
||||
val handle: Long = try {
|
||||
nativeStream(manifest, installDir, chunkCacheDir, cdnPrefixes, pendingFileIdx, expectedBytes, cacheBudget, caBundlePath, maxWorkers, processWorkers, inner)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "engine unavailable: ${t.javaClass.simpleName}: ${t.message}")
|
||||
return Result(false, false, false, "nativeStream: ${t.javaClass.simpleName}", 0L, 0, 0)
|
||||
}
|
||||
if (handle == 0L) return Result(false, false, false, completion.get()?.error ?: "not started", 0L, 0, totalRef.get())
|
||||
var cancelSent = false
|
||||
try {
|
||||
while (!latch.await(250, TimeUnit.MILLISECONDS)) {
|
||||
if (!cancelSent && cancel != null && cancel.get()) {
|
||||
nativeCancel(handle)
|
||||
cancelSent = true
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
nativeRelease(handle)
|
||||
}
|
||||
val c = completion.get()
|
||||
val cancelled = cancelSent || (c != null && !c.success && c.error == "cancelled")
|
||||
val success = !cancelled && c != null && c.success
|
||||
val error = when { cancelled -> "cancelled"; c == null -> "no completion"; else -> c.error }
|
||||
return Result(true, success, cancelled, error, c?.bytes ?: 0L, doneRef.get(), totalRef.get())
|
||||
}
|
||||
|
||||
private fun drive(what: String, cancel: AtomicBoolean?, listener: Listener, start: (Listener) -> Long): Result {
|
||||
if (!StoresNative.ensureLoaded()) return Result(false, false, false, "engine not built", 0L, 0, 0)
|
||||
val latch = CountDownLatch(1)
|
||||
@@ -109,6 +177,12 @@ object EpicNative {
|
||||
@JvmStatic
|
||||
private external fun nativeAssemble(manifest: ByteArray, installDir: String, chunkCacheDir: String, fileIdx: IntArray, listener: Listener): Long
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeStream(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedBytes: Long,
|
||||
cacheBudget: Long, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: StreamListener,
|
||||
): Long
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeCancel(handle: Long)
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ object EpicStoreCatalog {
|
||||
|
||||
private const val ELEMENT_FIELDS =
|
||||
"title id namespace description effectiveDate releaseDate offerType productSlug urlSlug " +
|
||||
"items{id namespace} keyImages{type url} seller{name} tags{name} " +
|
||||
"items{id namespace} keyImages{type url} seller{name} tags{name} customAttributes{key value} " +
|
||||
"catalogNs{mappings(pageType:\"productHome\"){pageSlug pageType}} " +
|
||||
"price(country:\$country){totalPrice{discountPrice originalPrice discount currencyCode " +
|
||||
"fmtPrice(locale:\$locale){originalPrice discountPrice}}}"
|
||||
@@ -116,13 +116,21 @@ object EpicStoreCatalog {
|
||||
return CatalogItem(
|
||||
store = Store.EPIC, id = id, title = title, imageUrl = wide ?: thumb, tallImageUrl = tall ?: thumb, tags = tagLine,
|
||||
isFree = isFree, hasPrice = hasPrice, finalPrice = finalPrice, originalPrice = if (discountPct > 0) fmtOriginal else "", discountPercent = discountPct,
|
||||
storeUrl = storeUrl, developer = e.optJSONObject("seller")?.optString("name", "").orEmpty(),
|
||||
storeUrl = storeUrl, developer = attribute(e, "developerName"),
|
||||
publisher = attribute(e, "publisherName").ifEmpty { e.optJSONObject("seller")?.optString("name", "").orEmpty() },
|
||||
releaseDate = e.optString("releaseDate", e.optString("effectiveDate", "")), description = com.droiddeck.launcher.stores.cleanStoreText(e.optString("description", "")),
|
||||
extra = buildMap { put("namespace", ns); if (itemIds.isNotEmpty()) put("items", itemIds.joinToString(",")); if (slug.isNotBlank()) put("slug", slug) },
|
||||
mature = com.droiddeck.launcher.stores.matureByTags(allTags),
|
||||
)
|
||||
}
|
||||
|
||||
// An offer's custom attribute (developerName, publisherName), or "".
|
||||
private fun attribute(e: JSONObject, key: String): String {
|
||||
val attrs = e.optJSONArray("customAttributes") ?: return ""
|
||||
return (0 until attrs.length()).mapNotNull { attrs.optJSONObject(it) }.firstOrNull { it.optString("key") == key }
|
||||
?.optString("value", "")?.trim().orEmpty()
|
||||
}
|
||||
|
||||
private fun pageSlugOf(e: JSONObject): String {
|
||||
e.optJSONObject("catalogNs")?.optJSONArray("mappings")?.let { m ->
|
||||
for (i in 0 until m.length()) { val map = m.optJSONObject(i) ?: continue; if (map.optString("pageType") == "productHome") { val s = map.optString("pageSlug", ""); if (s.isNotBlank()) return s } }
|
||||
@@ -193,7 +201,7 @@ object EpicStoreCatalog {
|
||||
private fun itemToJson(i: CatalogItem): JSONObject = JSONObject().apply {
|
||||
put("id", i.id); put("title", i.title); put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: ""); put("tags", i.tags)
|
||||
put("free", i.isFree); put("hasPrice", i.hasPrice); put("final", i.finalPrice); put("orig", i.originalPrice); put("disc", i.discountPercent)
|
||||
put("url", i.storeUrl); put("dev", i.developer); put("rel", i.releaseDate); put("desc", i.description); put("extra", JSONObject(i.extra as Map<*, *>))
|
||||
put("url", i.storeUrl); put("dev", i.developer); put("pub", i.publisher); put("rel", i.releaseDate); put("desc", i.description); put("extra", JSONObject(i.extra as Map<*, *>))
|
||||
if (i.mature) put("mature", true)
|
||||
}
|
||||
|
||||
@@ -203,7 +211,7 @@ object EpicStoreCatalog {
|
||||
return CatalogItem(
|
||||
store = Store.EPIC, id = o.optString("id"), title = o.optString("title"), imageUrl = o.optString("image").ifBlank { null }, tallImageUrl = o.optString("tall").ifBlank { null },
|
||||
tags = o.optString("tags"), isFree = o.optBoolean("free"), hasPrice = o.optBoolean("hasPrice"), finalPrice = o.optString("final"), originalPrice = o.optString("orig"),
|
||||
discountPercent = o.optInt("disc"), storeUrl = o.optString("url"), developer = o.optString("dev"), releaseDate = o.optString("rel"), description = o.optString("desc"), extra = extra,
|
||||
discountPercent = o.optInt("disc"), storeUrl = o.optString("url"), developer = o.optString("dev"), publisher = o.optString("pub"), releaseDate = o.optString("rel"), description = o.optString("desc"), extra = extra,
|
||||
mature = o.optBoolean("mature"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ object GogBackend : StoreBackend {
|
||||
val quiet = cached.isNotEmpty() && !force
|
||||
StoresState.post {
|
||||
if (cached.isNotEmpty()) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached)
|
||||
if (!quiet) StoresState.status[store] = "Fetching your library…"
|
||||
if (!quiet) StoresState.status[store] = app.getString(com.droiddeck.launcher.R.string.stores_sync_library)
|
||||
}
|
||||
val result = GogLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }
|
||||
StoresState.post {
|
||||
@@ -71,7 +71,7 @@ object GogBackend : StoreBackend {
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
val app = context.applicationContext
|
||||
val game = GogGame(item.id, item.title, item.imageUrl ?: "", item.description, item.developer, item.tags, 2, item.tallImageUrl)
|
||||
val game = GogGame(item.id, item.title, item.imageUrl ?: "", item.description, item.developer, item.tags, 2, item.tallImageUrl, item.releaseDate, item.publisher)
|
||||
val folder = StoreInstallRoot.folderFor(app, Store.GOG, game.gameId, game.title, root)
|
||||
val entry = DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))
|
||||
DownloadQueue.enqueue(app, entry) { InstallJob(app, game, item, folder) }
|
||||
@@ -106,7 +106,7 @@ object GogBackend : StoreBackend {
|
||||
}
|
||||
}, cancelled) ?: return null
|
||||
if (cancelled.get()) return null
|
||||
handle.stage(DownloadStage.INSTALL, "Registering with Steam…")
|
||||
handle.stage(DownloadStage.INSTALL, app.getString(com.droiddeck.launcher.R.string.stores_registering))
|
||||
val sidecar = StoreGameSidecar(
|
||||
Store.GOG, game.gameId, game.title, exe = result.exeRelative.ifEmpty { "" },
|
||||
installVersion = result.buildId, installedAt = System.currentTimeMillis(),
|
||||
|
||||
@@ -189,11 +189,12 @@ public final class GogDownloadManager {
|
||||
installPath.mkdirs();
|
||||
long plannedBytes = 0;
|
||||
for (DepotFile df : files) plannedBytes += df.totalSize;
|
||||
if (plannedBytes > 0) {
|
||||
long usable = installPath.getUsableSpace();
|
||||
if (usable > 0 && plannedBytes > usable) {
|
||||
long remainingBytes = remainingInstallBytes(files, installPath);
|
||||
if (remainingBytes > 0) {
|
||||
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
|
||||
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(remainingBytes, usable)) {
|
||||
out.hardStop = true;
|
||||
out.error = "Not enough free space: need " + formatBytes(plannedBytes) + ", only " + formatBytes(usable) + " free";
|
||||
out.error = "Not enough free space: need " + formatBytes(remainingBytes) + ", only " + formatBytes(usable) + " free";
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -1018,7 +1019,16 @@ public final class GogDownloadManager {
|
||||
for (File f : files) if (f.isDirectory()) collectExeRecursive(f, out);
|
||||
}
|
||||
|
||||
private static final class DepotFile {
|
||||
static long remainingInstallBytes(List<DepotFile> files, File installPath) {
|
||||
long remaining = 0;
|
||||
for (DepotFile file : files) {
|
||||
File output = new File(installPath, file.relativePath);
|
||||
if (!fileVerified(output, file.totalSize, file.md5)) remaining += file.totalSize;
|
||||
}
|
||||
return remaining;
|
||||
}
|
||||
|
||||
static final class DepotFile {
|
||||
final String relativePath;
|
||||
final List<ChunkRef> chunks = new ArrayList<>();
|
||||
String md5;
|
||||
|
||||
@@ -12,9 +12,12 @@ public class GogGame {
|
||||
public final int generation;
|
||||
/** gamesdb.gog.com 2:3 box art, or null when the lookup found none. */
|
||||
public final String verticalCover;
|
||||
/** ISO date-time of the worldwide release, or "" when GOG gave none. */
|
||||
public final String releaseDate;
|
||||
public final String publisher;
|
||||
|
||||
public GogGame(String gameId, String title, String imageUrl, String description, String developer,
|
||||
String category, int generation, String verticalCover) {
|
||||
String category, int generation, String verticalCover, String releaseDate, String publisher) {
|
||||
this.gameId = gameId;
|
||||
this.title = title;
|
||||
this.imageUrl = imageUrl;
|
||||
@@ -23,5 +26,7 @@ public class GogGame {
|
||||
this.category = category;
|
||||
this.generation = generation;
|
||||
this.verticalCover = verticalCover;
|
||||
this.releaseDate = releaseDate;
|
||||
this.publisher = publisher;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.stores.gog
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
@@ -45,7 +46,8 @@ object GogLibrary {
|
||||
(0 until arr.length()).mapNotNull { i ->
|
||||
val o = arr.optJSONObject(i) ?: return@mapNotNull null
|
||||
GogGame(o.optString("gameId", ""), o.optString("title", ""), o.optString("imageUrl", ""), cleanStoreText(o.optString("description", "")),
|
||||
o.optString("developer", ""), o.optString("category", ""), o.optInt("generation", 1), o.optString("verticalCover", "").ifEmpty { null })
|
||||
o.optString("developer", ""), o.optString("category", ""), o.optInt("generation", 1), o.optString("verticalCover", "").ifEmpty { null },
|
||||
o.optString("releaseDate", ""), o.optString("publisher", ""))
|
||||
}.filter { it.gameId.isNotEmpty() }.sortedBy { it.title.lowercase() }
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
@@ -59,9 +61,9 @@ object GogLibrary {
|
||||
val app = context.applicationContext
|
||||
val p = GogPrefs.get(app)
|
||||
val token = GogAuth.validToken(app) ?: return SyncResult.NotLoggedIn
|
||||
onStatus("Fetching game list…")
|
||||
onStatus(app.getString(R.string.stores_sync_game_list))
|
||||
val gamesJson = StoreNet.get("https://embed.gog.com/user/data/games", bearer = token, userAgent = GogAuth.GALAXY_UA)
|
||||
?: return SyncResult.Failed("Couldn't reach GOG")
|
||||
?: return SyncResult.Failed(app.getString(R.string.stores_sync_gog_unreachable))
|
||||
val ids = ArrayList<String>()
|
||||
val parsed = runCatching {
|
||||
val owned = JSONObject(gamesJson).optJSONArray("owned")
|
||||
@@ -71,7 +73,7 @@ object GogLibrary {
|
||||
if (id != "1801418160" && id != "0") ids.add(id)
|
||||
}
|
||||
}.isSuccess
|
||||
if (!parsed) return SyncResult.Failed("Error parsing library")
|
||||
if (!parsed) return SyncResult.Failed(app.getString(R.string.stores_sync_gog_unreadable))
|
||||
|
||||
val ownedSet = ids.toHashSet()
|
||||
val cachedList = cached(app)
|
||||
@@ -91,7 +93,7 @@ object GogLibrary {
|
||||
saveCache(p, list)
|
||||
return SyncResult.Ok(list.sortedBy { it.title.lowercase() }, 0)
|
||||
}
|
||||
onStatus("Syncing ${idsToFetch.size} game${if (idsToFetch.size == 1) "" else "s"}…")
|
||||
onStatus(app.resources.getQuantityString(R.plurals.stores_sync_games, idsToFetch.size, idsToFetch.size))
|
||||
val pool = Executors.newFixedThreadPool(5)
|
||||
val futures = idsToFetch.map { id -> pool.submit(Callable<GogGame?> { fetchGame(p, id, token, skipped) }) }
|
||||
pool.shutdown()
|
||||
@@ -99,7 +101,7 @@ object GogLibrary {
|
||||
for ((idx, f) in futures.withIndex()) {
|
||||
val g = runCatching { f.get() }.getOrNull()
|
||||
if (g != null) { merged[g.gameId] = g; fetched++ }
|
||||
if ((idx + 1) % 5 == 0) onStatus("Syncing… ${idx + 1}/${futures.size}")
|
||||
if ((idx + 1) % 5 == 0) onStatus(app.getString(R.string.stores_sync_progress, idx + 1, futures.size))
|
||||
}
|
||||
val finalList = merged.values.toList()
|
||||
saveCache(p, finalList)
|
||||
@@ -110,7 +112,7 @@ object GogLibrary {
|
||||
return SyncResult.Ok(finalList.sortedBy { it.title.lowercase() }, fetched)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "sync failed: ${e.message}")
|
||||
return SyncResult.Failed(e.message ?: "Sync failed")
|
||||
return SyncResult.Failed(e.message ?: context.getString(R.string.stores_sync_failed))
|
||||
} finally {
|
||||
syncing.set(false)
|
||||
}
|
||||
@@ -148,7 +150,15 @@ object GogLibrary {
|
||||
val desc = cleanStoreText(prod.optJSONObject("description")?.optString("lead", ""))
|
||||
.ifEmpty { cleanStoreText(v2?.optString("overview", "")) }
|
||||
.ifEmpty { cleanStoreText(v2?.optString("description", "")) }
|
||||
val developer = prod.optJSONObject("developers")?.optString("name", "") ?: prod.optString("developer", "")
|
||||
// The products endpoint names no developer or publisher; the v2 record does, with the worldwide release date.
|
||||
val embedded = v2?.optJSONObject("_embedded")
|
||||
fun names(key: String) = embedded?.optJSONArray(key)
|
||||
?.let { arr -> (0 until arr.length()).mapNotNull { arr.optJSONObject(it)?.optString("name")?.takeIf(String::isNotBlank) } }
|
||||
?.joinToString(", ").orEmpty()
|
||||
val developer = names("developers")
|
||||
val publisher = embedded?.optJSONObject("publisher")?.optString("name")?.takeIf(String::isNotBlank) ?: names("publishers")
|
||||
val releaseDate = listOf(embedded?.optJSONObject("product")?.optString("globalReleaseDate"), prod.optString("release_date"))
|
||||
.firstOrNull { !it.isNullOrBlank() && it != "null" }.orEmpty()
|
||||
val genres = prod.optJSONArray("genres")
|
||||
val category = if (genres != null && genres.length() > 0) genres.optJSONObject(0)?.optString("name", "") ?: "" else ""
|
||||
|
||||
@@ -164,9 +174,7 @@ object GogLibrary {
|
||||
if (maxGen > 0) generation = maxGen
|
||||
}
|
||||
}
|
||||
val ed = prefs.edit().putInt("gen_$id", generation)
|
||||
prod.optString("release_date", "").takeIf { it.isNotEmpty() }?.let { ed.putString("release_$id", it) }
|
||||
ed.apply()
|
||||
prefs.edit().putInt("gen_$id", generation).apply()
|
||||
if (prefs.getLong("size_$id", -1L) <= 0) {
|
||||
val size = GogDownloadManager.fetchInstallSizeBytes(id, token)
|
||||
if (size > 0) prefs.edit().putLong("size_$id", size).apply()
|
||||
@@ -182,7 +190,7 @@ object GogLibrary {
|
||||
verticalCover = fetchVerticalCover(id).ifEmpty { StoreNet.sgdbPoster(title) }
|
||||
}
|
||||
if (!verticalCover.isNullOrEmpty()) prefs.edit().putString("vcover_$id", verticalCover).apply()
|
||||
return GogGame(id, title, GogStoreCatalog.absolutize(imageUrl), desc, developer, category, generation, verticalCover?.ifEmpty { null })
|
||||
return GogGame(id, title, GogStoreCatalog.absolutize(imageUrl), desc, developer, category, generation, verticalCover?.ifEmpty { null }, releaseDate, publisher)
|
||||
} catch (_: Exception) {
|
||||
return null
|
||||
}
|
||||
@@ -203,7 +211,7 @@ object GogLibrary {
|
||||
val arr = JSONArray()
|
||||
for (g in games) {
|
||||
arr.put(JSONObject().put("gameId", g.gameId).put("title", g.title).put("imageUrl", g.imageUrl).put("description", g.description)
|
||||
.put("developer", g.developer).put("category", g.category).put("generation", g.generation)
|
||||
.put("developer", g.developer).put("category", g.category).put("generation", g.generation).put("releaseDate", g.releaseDate).put("publisher", g.publisher)
|
||||
.apply { if (!g.verticalCover.isNullOrEmpty()) put("verticalCover", g.verticalCover) })
|
||||
}
|
||||
prefs.edit().putString(CACHE_KEY, arr.toString()).apply()
|
||||
@@ -215,7 +223,9 @@ object GogLibrary {
|
||||
store = Store.GOG, id = g.gameId, title = g.title,
|
||||
imageUrl = GogStoreCatalog.absolutize(g.imageUrl).ifBlank { null },
|
||||
tallImageUrl = GogStoreCatalog.absolutize(g.verticalCover ?: g.imageUrl).ifBlank { null },
|
||||
tags = g.category, developer = g.developer, description = g.description, owned = true,
|
||||
tags = g.category, developer = g.developer, publisher = g.publisher, description = g.description, owned = true,
|
||||
// A cache from before the release date was kept still has it under the older per-game key.
|
||||
releaseDate = g.releaseDate.ifEmpty { GogPrefs.get(context).getString("release_${g.gameId}", "").orEmpty() },
|
||||
sizeBytes = sizeOf(context, g.gameId),
|
||||
storeUrl = "https://www.gog.com/en/game/${g.gameId}",
|
||||
)
|
||||
|
||||
@@ -133,6 +133,7 @@ object GogStoreCatalog {
|
||||
finalPrice = finalStr, originalPrice = if (discount > 0) baseStr else "",
|
||||
discountPercent = if (discount > 0 && baseStr.isNotBlank()) discount else 0,
|
||||
storeUrl = storeLink, developer = p.optJSONArray("developers")?.optString(0, "").orEmpty(),
|
||||
publisher = p.optJSONArray("publishers")?.optString(0, "").orEmpty(),
|
||||
releaseDate = p.optString("releaseDate", ""),
|
||||
extra = buildMap { if (slug.isNotBlank()) put("slug", slug) },
|
||||
mature = mature,
|
||||
@@ -175,7 +176,7 @@ object GogStoreCatalog {
|
||||
private fun itemToJson(i: CatalogItem): JSONObject = JSONObject().apply {
|
||||
put("id", i.id); put("title", i.title); put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: "")
|
||||
put("tags", i.tags); put("free", i.isFree); put("hasPrice", i.hasPrice); put("final", i.finalPrice); put("orig", i.originalPrice)
|
||||
put("disc", i.discountPercent); put("url", i.storeUrl); put("dev", i.developer); put("rel", i.releaseDate)
|
||||
put("disc", i.discountPercent); put("url", i.storeUrl); put("dev", i.developer); put("pub", i.publisher); put("rel", i.releaseDate)
|
||||
if (i.mature) put("mature", true)
|
||||
}
|
||||
|
||||
@@ -184,7 +185,7 @@ object GogStoreCatalog {
|
||||
imageUrl = o.optString("image").ifBlank { null }, tallImageUrl = o.optString("tall").ifBlank { null },
|
||||
tags = o.optString("tags"), isFree = o.optBoolean("free"), hasPrice = o.optBoolean("hasPrice"),
|
||||
finalPrice = o.optString("final"), originalPrice = o.optString("orig"), discountPercent = o.optInt("disc"),
|
||||
storeUrl = o.optString("url"), developer = o.optString("dev"), releaseDate = o.optString("rel"),
|
||||
storeUrl = o.optString("url"), developer = o.optString("dev"), publisher = o.optString("pub"), releaseDate = o.optString("rel"),
|
||||
mature = o.optBoolean("mature"),
|
||||
)
|
||||
|
||||
|
||||
@@ -205,6 +205,8 @@ class FrontEndActions(
|
||||
val onAgentCommands: () -> Unit = {},
|
||||
val onShareLogs: () -> Unit = {},
|
||||
val onClearLogs: () -> Unit = {},
|
||||
/** Setup's Reset all settings: asks first, then puts every setting back to its default. */
|
||||
val onResetSettings: () -> Unit = {},
|
||||
val onOffline: () -> Unit,
|
||||
val onPageBack: () -> Unit = {},
|
||||
val onTheme: (String) -> Unit = {},
|
||||
|
||||
@@ -405,6 +405,8 @@ internal fun SetupPanel(
|
||||
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
|
||||
progress = com.droiddeck.launcher.session.SessionLogShare.progress)
|
||||
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
|
||||
ActionRow(stringResource(R.string.setup_reset_settings), stringResource(R.string.setup_reset_settings_hint),
|
||||
stringResource(R.string.setup_reset_settings_button), a.onResetSettings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,29 @@ package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
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.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
@@ -53,3 +65,32 @@ fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () ->
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** Setup's Reset all settings, with the choice to clear game profiles too (off unless ticked). */
|
||||
@Composable
|
||||
fun ResetSettingsDialog(onConfirm: (gameProfiles: Boolean) -> Unit, onDismiss: () -> Unit) {
|
||||
var gameProfiles by remember { mutableStateOf(false) }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.setup_reset_settings_title)) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(stringResource(R.string.setup_reset_settings_body))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().toggleable(gameProfiles, role = Role.Checkbox) { gameProfiles = it },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Checkbox(checked = gameProfiles, onCheckedChange = null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.setup_reset_settings_profiles), style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onDismiss(); onConfirm(gameProfiles) }) {
|
||||
Text(stringResource(R.string.setup_reset_settings_button), color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -70,6 +70,10 @@ class ModeSettings(
|
||||
val touchMode: String,
|
||||
val suspendPolicy: String,
|
||||
val steamDownloadsInBackground: Boolean = false,
|
||||
/** Steam only; null hides it. */
|
||||
val zramCompression: Boolean? = null,
|
||||
/** Null until checked off the main thread. */
|
||||
val zramSupported: Boolean? = null,
|
||||
val pipSupported: Boolean = false,
|
||||
val pipAutoEnter: Boolean = false,
|
||||
/** Steam only. */
|
||||
@@ -127,6 +131,7 @@ class ModeSettingsActions(
|
||||
val onTouch: (String) -> Unit,
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
|
||||
val onZramCompression: (Boolean) -> Unit = {},
|
||||
val onPipAutoEnter: (Boolean) -> Unit = {},
|
||||
val onOsc: (String) -> Unit,
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
@@ -303,6 +308,12 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
stringResource(R.string.mode_background_downloads_hint),
|
||||
s.steamDownloadsInBackground, onChange = a.onSteamDownloadsInBackground,
|
||||
)
|
||||
if (s.zramCompression != null) ToggleRow(
|
||||
host, "zram", stringResource(R.string.mode_zram),
|
||||
stringResource(if (s.zramSupported == false) R.string.mode_zram_unsupported else R.string.mode_zram_hint),
|
||||
s.zramCompression && s.zramSupported != false, enabled = s.zramSupported == true,
|
||||
onChange = a.onZramCompression,
|
||||
)
|
||||
}
|
||||
if (s.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) {
|
||||
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
|
||||
|
||||
@@ -137,6 +137,8 @@ import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.Lossless
|
||||
import com.droiddeck.launcher.gpu.ScreenEffectLooks
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.SteamVr
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
@@ -209,6 +211,12 @@ class DrawerActions(
|
||||
val upscaleSharpness: Int = 75,
|
||||
/** The compositor's post chain (gpu/ScreenEffects), changed live. */
|
||||
val effects: ScreenEffects = ScreenEffects.OFF,
|
||||
/** Cardboard mode (gpu/Cardboard): side-by-side eyes for a phone VR viewer, changed live. */
|
||||
val cardboard: Cardboard = Cardboard.OFF,
|
||||
/** Whether the device has a rotation sensor (head tracking possible). */
|
||||
val cardboardSensor: Boolean = false,
|
||||
/** SteamVR in the guest for Cardboard mode (gpu/SteamVr); null while unknown. */
|
||||
val steamVr: SteamVr.Status? = null,
|
||||
/** Texture filtering for DirectX 9-11 games (core/TextureFiltering); lands on their next launch. */
|
||||
val textureAnisotropy: Int? = 0,
|
||||
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
|
||||
@@ -244,6 +252,10 @@ class DrawerActions(
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
val onEffects: (ScreenEffects) -> Unit = {},
|
||||
val onCardboard: (Cardboard) -> Unit = {},
|
||||
val onCardboardRecenter: () -> Unit = {},
|
||||
/** install, start or stop SteamVR. */
|
||||
val onSteamVr: (String) -> Unit = {},
|
||||
val onTextureAnisotropy: (Int?) -> Unit = {},
|
||||
val onTextureLodBias: (String?) -> Unit = {},
|
||||
val onSecondScreenMode: (SecondScreenMode) -> Unit,
|
||||
@@ -465,6 +477,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
stringResource(R.string.display_sharpness), null, a.upscaleSharpness, 0..100, step = 5,
|
||||
format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"), onChange = a.onUpscaleSharpness)
|
||||
}
|
||||
CardboardGroup(host, a) { key -> focus.track(page, key) }
|
||||
}
|
||||
SessionDrawerPage.EFFECTS -> {
|
||||
ScreenEffectsGroup(host, a, advancedEffectsExpanded,
|
||||
@@ -903,6 +916,53 @@ private fun ScreenEffectsGroup(
|
||||
}
|
||||
}
|
||||
|
||||
/** Cardboard mode: the eyes, the lens and the virtual screen; everything applies live. */
|
||||
@Composable
|
||||
private fun CardboardGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val c = a.cardboard
|
||||
SettingsGroup(stringResource(R.string.cardboard_title)) {
|
||||
ToggleRow(host, "cardboard", stringResource(R.string.cardboard_mode), stringResource(R.string.cardboard_mode_hint),
|
||||
c.enabled, chipModifier = track("cardboard")) { a.onCardboard(c.copy(enabled = it)) }
|
||||
if (!c.enabled) return@SettingsGroup
|
||||
ChoiceRow(host, "cardboard-source", stringResource(R.string.cardboard_source), null,
|
||||
listOf(Cardboard.SOURCE_SCREEN to stringResource(R.string.cardboard_source_screen),
|
||||
Cardboard.SOURCE_SBS to stringResource(R.string.cardboard_source_sbs)),
|
||||
c.source, chipModifier = track("cardboard-source")) { a.onCardboard(c.copy(source = it)) }
|
||||
ChoiceRow(host, "cardboard-viewer", stringResource(R.string.cardboard_viewer), null,
|
||||
listOf(Cardboard.Viewer.CARDBOARD_V2.id to stringResource(R.string.cardboard_viewer_v2),
|
||||
Cardboard.Viewer.CARDBOARD_V1.id to stringResource(R.string.cardboard_viewer_v1),
|
||||
Cardboard.Viewer.NONE.id to stringResource(R.string.cardboard_viewer_none)),
|
||||
c.viewer, chipModifier = track("cardboard-viewer")) { a.onCardboard(c.copy(viewer = it)) }
|
||||
SliderRow(stringResource(R.string.cardboard_ipd), null, c.ipdMm, 50..80, step = 1,
|
||||
format = { "$it mm" }, modifier = track("cardboard-ipd")) { a.onCardboard(c.copy(ipdMm = it)) }
|
||||
if (c.source == Cardboard.SOURCE_SCREEN) {
|
||||
SliderRow(stringResource(R.string.cardboard_screen_width), null, c.screenWidthDm, 5..200, step = 5,
|
||||
format = { String.format(Locale.US, "%.1f m", it / 10f) }, modifier = track("cardboard-width")) { a.onCardboard(c.copy(screenWidthDm = it)) }
|
||||
SliderRow(stringResource(R.string.cardboard_screen_distance), null, c.screenDistanceDm, 5..200, step = 5,
|
||||
format = { String.format(Locale.US, "%.1f m", it / 10f) }, modifier = track("cardboard-distance")) { a.onCardboard(c.copy(screenDistanceDm = it)) }
|
||||
}
|
||||
ToggleRow(host, "cardboard-tracking", stringResource(R.string.cardboard_head_tracking),
|
||||
if (a.cardboardSensor) null else stringResource(R.string.cardboard_no_sensor),
|
||||
c.headTracking && a.cardboardSensor, enabled = a.cardboardSensor, chipModifier = track("cardboard-tracking")) {
|
||||
a.onCardboard(c.copy(headTracking = it))
|
||||
}
|
||||
if (c.headTracking && a.cardboardSensor)
|
||||
ActionRow(stringResource(R.string.cardboard_recenter), null, stringResource(R.string.cardboard_recenter_button), a.onCardboardRecenter)
|
||||
val vrLabel = stringResource(R.string.cardboard_steamvr)
|
||||
when (a.steamVr) {
|
||||
SteamVr.Status.NOT_INSTALLED -> ActionRow(vrLabel, stringResource(R.string.cardboard_steamvr_install_hint),
|
||||
stringResource(R.string.cardboard_steamvr_install), { a.onSteamVr("install") })
|
||||
SteamVr.Status.INSTALLING -> SettingsRow(vrLabel, stringResource(R.string.cardboard_steamvr_installing)) {}
|
||||
SteamVr.Status.READY -> ActionRow(vrLabel, stringResource(R.string.cardboard_steamvr_ready_hint),
|
||||
stringResource(R.string.cardboard_steamvr_start), { a.onSteamVr("start") })
|
||||
SteamVr.Status.RUNNING -> ActionRow(vrLabel, stringResource(R.string.cardboard_steamvr_running_hint),
|
||||
stringResource(R.string.cardboard_steamvr_stop), { a.onSteamVr("stop") })
|
||||
SteamVr.Status.UNAVAILABLE -> SettingsRow(vrLabel, stringResource(R.string.cardboard_steamvr_unavailable)) {}
|
||||
null -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Secondary-display modes are mutually exclusive and apply immediately. */
|
||||
@Composable
|
||||
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.ExitTransition
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkHorizontally
|
||||
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.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
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.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
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.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.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.GameFacts
|
||||
import com.droiddeck.launcher.stores.Lookup
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
// A store game's facts under its hero: who made it and when, from the store; the Metacritic score
|
||||
// and HowLongToBeat's times, looked up elsewhere by name. The store's facts are there at once; the
|
||||
// looked-up ones hold their place while they come and step out if there is nothing to show.
|
||||
|
||||
internal class GameScores(val metacritic: Lookup<GameFacts.Metacritic>, val hltb: Lookup<GameFacts.Hltb>)
|
||||
|
||||
/** Both lookups at once and off the main thread, each landing on its own; what memory already has shows without a wait. */
|
||||
@Composable
|
||||
internal fun rememberGameScores(title: String?): GameScores {
|
||||
val ctx = LocalContext.current.applicationContext
|
||||
var metacritic by remember(title) { mutableStateOf(title?.let { GameFacts.peekMetacritic(it) } ?: if (title == null) Lookup.None else Lookup.Pending) }
|
||||
var hltb by remember(title) { mutableStateOf(title?.let { GameFacts.peekHltb(it) } ?: if (title == null) Lookup.None else Lookup.Pending) }
|
||||
LaunchedEffect(title) {
|
||||
if (title == null) return@LaunchedEffect
|
||||
launch { metacritic = withContext(Dispatchers.IO) { GameFacts.metacritic(ctx, title) }?.let { Lookup.Found(it) } ?: Lookup.None }
|
||||
launch { hltb = withContext(Dispatchers.IO) { GameFacts.hltb(ctx, title) }?.let { Lookup.Found(it) } ?: Lookup.None }
|
||||
}
|
||||
return GameScores(metacritic, hltb)
|
||||
}
|
||||
|
||||
/**
|
||||
* The facts: who made it, when, and what critics made of it on the first row; how long it takes,
|
||||
* across the page, on the second. A looked-up tile holds its place while it asks and steps out if
|
||||
* the site does not have the game; nothing is drawn when there is nothing to say.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
internal fun StoreGameFacts(developer: String, publisher: String, releaseDate: String, scores: GameScores, modifier: Modifier = Modifier) {
|
||||
val released = remember(releaseDate) { GameFacts.releaseLabel(releaseDate) }
|
||||
// A studio that publishes itself is named once.
|
||||
val publishedBy = publisher.takeUnless { it.isBlank() || it.trim().equals(developer.trim(), ignoreCase = true) }
|
||||
val firstRow = developer.isNotBlank() || publishedBy != null || released != null || scores.metacritic != Lookup.None
|
||||
if (!firstRow && scores.hltb == Lookup.None) return
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = modifier.fillMaxWidth().padding(top = 12.dp)) {
|
||||
if (firstRow) FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (developer.isNotBlank()) FactTile(stringResource(R.string.stores_fact_developer)) { FactText(developer) }
|
||||
if (publishedBy != null) FactTile(stringResource(R.string.stores_fact_publisher)) { FactText(publishedBy) }
|
||||
if (released != null) FactTile(stringResource(R.string.stores_fact_released)) { FactText(released) }
|
||||
Looked(scores.metacritic, exit = shrinkHorizontally()) { lookup ->
|
||||
val found = (lookup as? Lookup.Found)?.value
|
||||
FactTile(stringResource(R.string.stores_fact_metacritic), link = found?.url) {
|
||||
if (found != null) MetacriticBadge(found.score) else Placeholder(ValueHeight)
|
||||
}
|
||||
}
|
||||
}
|
||||
Looked(scores.hltb, exit = shrinkVertically()) { lookup ->
|
||||
val found = (lookup as? Lookup.Found)?.value
|
||||
FactTile(stringResource(R.string.stores_fact_hltb), fill = true, link = found?.url) {
|
||||
if (found != null) HltbTimes(found) else Placeholder(220.dp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A looked-up tile: in from the start (holding its place while it asks), out with a fade when there was nothing. */
|
||||
@Composable
|
||||
private fun <T> Looked(lookup: Lookup<T>, exit: ExitTransition, content: @Composable (Lookup<T>) -> Unit) {
|
||||
// The last answer worth drawing, so the tile does not blank as it leaves.
|
||||
var shown by remember { mutableStateOf(lookup) }
|
||||
if (lookup != Lookup.None) shown = lookup
|
||||
AnimatedVisibility(visible = lookup != Lookup.None, enter = fadeIn(), exit = fadeOut() + exit) { content(shown) }
|
||||
}
|
||||
|
||||
private val FactShape = RoundedCornerShape(12.dp)
|
||||
private val ValueHeight = 24.dp
|
||||
|
||||
/**
|
||||
* A label over its value; [fill] takes the row's whole width, for a value laid out across it. With
|
||||
* a [link] it is a control like any other on the page: focus, hover and A or a tap open the page.
|
||||
*/
|
||||
@Composable
|
||||
private fun FactTile(label: String, fill: Boolean = false, link: String? = null, value: @Composable () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = link != null && rememberHot(src)
|
||||
val open = { if (link != null) openUrl(ctx, link) }
|
||||
val base = if (fill) Modifier.fillMaxWidth() else Modifier.widthIn(max = 360.dp)
|
||||
val tile = if (link == null) base.clip(FactShape).background(pal.surface).border(1.dp, pal.line, FactShape)
|
||||
else base.paneItem("fact:$label").clip(FactShape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.14f) else pal.surface)
|
||||
.glideBorder(hot, FactShape, pal.signal, restColor = pal.line)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = open)
|
||||
.controllerConfirm(onClick = open)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = tile.padding(horizontal = 14.dp, vertical = 10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(label.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = if (hot) pal.signal else pal.onSurfaceVariant, maxLines = 1)
|
||||
if (link != null) Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = if (hot) pal.signal else pal.onSurfaceVariant, modifier = Modifier.size(12.dp))
|
||||
}
|
||||
Box(contentAlignment = Alignment.CenterStart, modifier = (if (fill) Modifier.fillMaxWidth() else Modifier).heightIn(min = ValueHeight)) { value() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FactText(text: String) =
|
||||
Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
|
||||
/** Metacritic's own bands: green from 75, yellow from 50, red below. */
|
||||
internal fun metacriticColour(score: Int): Color = when {
|
||||
score >= 75 -> Color(0xFF66CC33)
|
||||
score >= 50 -> Color(0xFFFFCC33)
|
||||
else -> Color(0xFFFF6874)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MetacriticBadge(score: Int) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(ValueHeight).clip(RoundedCornerShape(6.dp)).background(metacriticColour(score))) {
|
||||
Text("$score", fontSize = 13.sp, fontWeight = FontWeight.Black, color = Color(0xFF0A0B0D), maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
/** Each kind of run HowLongToBeat has times for, sharing the tile's width: the hours in full, what they are for beside them. */
|
||||
@Composable
|
||||
private fun HltbTimes(t: GameFacts.Hltb) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val runs = listOf(
|
||||
t.main to stringResource(R.string.stores_hltb_main),
|
||||
t.extras to stringResource(R.string.stores_hltb_extras),
|
||||
t.completionist to stringResource(R.string.stores_hltb_completionist),
|
||||
).filter { it.first > 0 }
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
for ((secs, what) in runs) {
|
||||
val hours = GameFacts.hours(secs)?.let { stringResource(R.string.stores_hltb_hours, it) } ?: stringResource(R.string.stores_hltb_minutes, maxOf(1, secs / 60))
|
||||
val run = buildAnnotatedString {
|
||||
withStyle(SpanStyle(fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)) { append(hours) }
|
||||
withStyle(SpanStyle(fontSize = 12.sp, color = colors.onSurfaceVariant)) { append(" $what") }
|
||||
}
|
||||
Text(run, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Where a value will be, breathing while it is asked for. */
|
||||
@Composable
|
||||
private fun Placeholder(width: Dp) {
|
||||
val pulse by rememberInfiniteTransition(label = "fact").animateFloat(
|
||||
0.35f, 0.8f, infiniteRepeatable(tween(900, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "pulse",
|
||||
)
|
||||
Box(Modifier.width(width).height(16.dp).alpha(pulse).clip(RoundedCornerShape(5.dp)).background(LocalPalette.current.line2))
|
||||
}
|
||||
|
||||
// Previews: every state the row can be in, at a TV pane's width and a narrow one.
|
||||
|
||||
private val previewScores = GameScores(
|
||||
Lookup.Found(GameFacts.Metacritic(93, "https://www.metacritic.com/game/the-witcher-3-wild-hunt/")),
|
||||
Lookup.Found(GameFacts.Hltb(main = 186_070, extras = 373_519, completionist = 630_794, url = "https://howlongtobeat.com/game/10270")),
|
||||
)
|
||||
|
||||
private fun previewScore(score: Int) = Lookup.Found(GameFacts.Metacritic(score, "https://www.metacritic.com/"))
|
||||
|
||||
@Composable
|
||||
private fun FactsPreview(theme: String = Themes.GRAPHITE, narrow: Boolean = false, content: @Composable () -> Unit) {
|
||||
DroidDeckTheme(theme = theme) {
|
||||
CompositionLocalProvider(LocalNarrowPane provides narrow) {
|
||||
Box(Modifier.fillMaxSize().background(LocalPalette.current.background).padding(16.dp)) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) { content() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PreviewCaption(text: String) = Text(text, fontSize = 11.sp, color = LocalPalette.current.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp))
|
||||
|
||||
@Preview(name = "Facts, all found", widthDp = 800, heightDp = 200)
|
||||
@Composable
|
||||
private fun FactsFoundPreview() = FactsPreview {
|
||||
StoreGameFacts("CD PROJEKT RED", "CD PROJEKT RED", "2015-05-19T00:00:00+02:00", previewScores)
|
||||
}
|
||||
|
||||
@Preview(name = "Facts, looking up", widthDp = 800, heightDp = 200)
|
||||
@Composable
|
||||
private fun FactsPendingPreview() = FactsPreview {
|
||||
StoreGameFacts("Supergiant Games", "Supergiant Games", "2020.09.17", GameScores(Lookup.Pending, Lookup.Pending))
|
||||
}
|
||||
|
||||
@Preview(name = "Facts, mixed", widthDp = 800, heightDp = 640)
|
||||
@Composable
|
||||
private fun FactsMixedPreview() = FactsPreview {
|
||||
PreviewCaption("Another studio's publisher; score found, times still coming")
|
||||
StoreGameFacts("New World Computing", "Ubisoft", "1999-02-28", GameScores(previewScore(87), Lookup.Pending))
|
||||
PreviewCaption("Score found, no times")
|
||||
StoreGameFacts("Mane6", "Maximum Entertainment", "2022-12-19T16:00:00.000Z", GameScores(previewScore(68), Lookup.None))
|
||||
PreviewCaption("Neither site knows it: store facts only")
|
||||
StoreGameFacts("Tiny Indie Studio", "", "2024.03.01", GameScores(Lookup.None, Lookup.None))
|
||||
PreviewCaption("A low score, a short game with only a main-story time")
|
||||
StoreGameFacts("", "", "2019-11-05", GameScores(previewScore(42), Lookup.Found(GameFacts.Hltb(main = 2_400, extras = 0, completionist = 0, url = "https://howlongtobeat.com/"))))
|
||||
PreviewCaption("Epic's no-date placeholder (2099) is not shown")
|
||||
StoreGameFacts("Studio", "", "2099-01-01T00:00:00.000Z", GameScores(previewScore(81), Lookup.None))
|
||||
}
|
||||
|
||||
@Preview(name = "Facts, narrow pane", widthDp = 420, heightDp = 300)
|
||||
@Composable
|
||||
private fun FactsNarrowPreview() = FactsPreview(narrow = true) {
|
||||
StoreGameFacts("CD PROJEKT RED", "CD PROJEKT RED", "2015-05-19T00:00:00+02:00", previewScores)
|
||||
}
|
||||
|
||||
@Preview(name = "Facts, Paper theme", widthDp = 800, heightDp = 200)
|
||||
@Composable
|
||||
private fun FactsPaperPreview() = FactsPreview(theme = Themes.PAPER) {
|
||||
StoreGameFacts("CD PROJEKT RED", "CD PROJEKT RED", "2015-05-19T00:00:00+02:00", previewScores)
|
||||
}
|
||||
|
||||
// The real hero reads the stores' live state, so this stands one in to show where the row sits.
|
||||
@Preview(name = "Game page, facts in place", widthDp = 800, heightDp = 520)
|
||||
@Composable
|
||||
private fun FactsOnPagePreview() = FactsPreview {
|
||||
val title = "The Witcher 3: Wild Hunt"
|
||||
Box(Modifier.fillMaxWidth().height(180.dp).clip(Shape16).background(artBrush(hueOf(title)))) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp)) {
|
||||
Text(stringResource(R.string.stores_eyebrow_library).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = LocalPalette.current.signal)
|
||||
Text(title, fontSize = 30.sp, fontWeight = FontWeight.Black, color = MaterialTheme.colorScheme.onBackground)
|
||||
}
|
||||
}
|
||||
StoreGameFacts("CD PROJEKT RED", "CD PROJEKT RED", "2015-05-19T00:00:00+02:00", previewScores)
|
||||
Text(
|
||||
"As war rages on throughout the Northern Realms, you take on the greatest contract of your life — tracking down the Child of Prophecy, a living weapon that can alter the shape of the world.",
|
||||
fontSize = 13.sp, lineHeight = 19.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 12.dp),
|
||||
)
|
||||
}
|
||||
@@ -52,7 +52,9 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
val id = key.substringAfter(':')
|
||||
val item = (StoresState.library[store].orEmpty() + StoresState.shelves[store]?.all.orEmpty()).firstOrNull { it.id == id }
|
||||
val installed = StoresState.installedGame(store, id)
|
||||
val download = StoresState.download("${store.id}:$id")?.takeIf { it.isActive }
|
||||
val rawDownload = StoresState.download("${store.id}:$id")
|
||||
val download = rawDownload?.takeIf { it.isActive }
|
||||
val failedDownload = rawDownload?.takeIf { it.state == DownloadState.FAILED }
|
||||
// Removal asks twice: one stray press of A should not cost a download.
|
||||
val title = item?.title ?: installed?.sidecar?.title ?: id
|
||||
Rise(0) {
|
||||
@@ -79,12 +81,24 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
val state = when {
|
||||
installed != null -> stringResource(R.string.stores_eyebrow_installed) + " · " + com.droiddeck.launcher.stores.StoreInstallRoot.labelFor(ctx, installed.folder)
|
||||
download != null && download.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + download.location
|
||||
failedDownload != null && failedDownload.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + failedDownload.location
|
||||
item?.owned == true -> stringResource(R.string.stores_eyebrow_library)
|
||||
else -> stringResource(R.string.stores_eyebrow_store)
|
||||
}
|
||||
val size = (item?.sizeBytes ?: 0L).takeIf { it > 0 }?.let { " · " + formatBytes(it) } ?: ""
|
||||
Text((state + size).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = pal.signal)
|
||||
Text(title, fontSize = if (narrow) 24.sp else 30.sp, lineHeight = if (narrow) 27.sp else 33.sp, fontWeight = FontWeight.Black, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
if (!failedDownload?.error.isNullOrBlank()) {
|
||||
Text(
|
||||
failedDownload!!.error!!,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = colors.error,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
Actions {
|
||||
when {
|
||||
installed != null -> {
|
||||
@@ -106,6 +120,16 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) { com.droiddeck.launcher.stores.download.DownloadQueue.resume(ctx, download.key) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { com.droiddeck.launcher.stores.download.DownloadQueue.cancel(ctx, download.key) }
|
||||
}
|
||||
failedDownload != null -> {
|
||||
ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
|
||||
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) {
|
||||
if (item != null) StoresState.requestInstall(ctx, item)
|
||||
else com.droiddeck.launcher.stores.download.DownloadQueue.retry(ctx, failedDownload.key)
|
||||
}
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) {
|
||||
com.droiddeck.launcher.stores.download.DownloadQueue.clear(ctx, failedDownload.key)
|
||||
}
|
||||
}
|
||||
item?.owned == true && StoresState.isUnfinished(item) -> {
|
||||
InstallButton(stringResource(R.string.stores_resume_install)) { StoresState.requestInstall(ctx, item) }
|
||||
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
|
||||
@@ -122,11 +146,20 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
}
|
||||
}
|
||||
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
|
||||
if (store == Store.GOG || store == Store.EPIC) {
|
||||
// An owned game resolves to its library entry; the storefront's copy of it may know more.
|
||||
val listed = StoresState.shelves[store]?.all.orEmpty().firstOrNull { it.id == id }
|
||||
val developer = item?.developer?.ifBlank { null } ?: listed?.developer.orEmpty()
|
||||
val publisher = item?.publisher?.ifBlank { null } ?: listed?.publisher.orEmpty()
|
||||
val releaseDate = item?.releaseDate?.ifBlank { null } ?: listed?.releaseDate.orEmpty()
|
||||
val scores = rememberGameScores(title.takeIf { it != id })
|
||||
Rise(2) { StoreGameFacts(developer, publisher, releaseDate, scores) }
|
||||
}
|
||||
// Plain text only, and nothing at all when the store sent a template key instead of words.
|
||||
// A description that is only the title again (some stores fill it so) is no description.
|
||||
val description = item?.let { com.droiddeck.launcher.stores.cleanStoreText(it.description) }.orEmpty()
|
||||
.takeUnless { it.trim().equals(title.trim(), ignoreCase = true) }.orEmpty()
|
||||
if (description.isNotBlank()) Rise(2) {
|
||||
if (description.isNotBlank()) Rise(3) {
|
||||
Text(description, fontSize = 13.sp, lineHeight = 19.sp, color = colors.onSurfaceVariant, maxLines = 6, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 12.dp))
|
||||
}
|
||||
val achievements = remember(store, id, item?.owned, installed) {
|
||||
@@ -137,7 +170,7 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
if (achievements != null) Rise(3) { StoreAchievementsSection(achievements) }
|
||||
if (achievements != null) Rise(4) { StoreAchievementsSection(achievements) }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -339,6 +339,7 @@ private fun Modifier.timeRim(left: () -> Float, color: Color): Modifier = drawWi
|
||||
@Composable
|
||||
private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val narrow = LocalNarrowPane.current
|
||||
val ink = Color.White
|
||||
@@ -362,8 +363,11 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
val meta = when (d.state) {
|
||||
DownloadState.INSTALLED -> stringResource(R.string.stores_installed_chip)
|
||||
DownloadState.CANCELLED -> stringResource(R.string.stores_dl_cancelled)
|
||||
// The reason is in the engine log; the row only says what is kept for Resume.
|
||||
DownloadState.FAILED -> if (d.bytesDone > 0) stringResource(R.string.stores_dl_failed_kept, formatBytes(d.bytesDone)) else stringResource(R.string.stores_dl_failed)
|
||||
DownloadState.FAILED -> {
|
||||
if (!d.error.isNullOrBlank()) stringResource(R.string.stores_dl_failed_reason, d.error)
|
||||
else if (d.bytesDone > 0) stringResource(R.string.stores_dl_failed_kept, formatBytes(d.bytesDone))
|
||||
else stringResource(R.string.stores_dl_failed)
|
||||
}
|
||||
DownloadState.PAUSED -> stringResource(R.string.stores_dl_paused)
|
||||
DownloadState.QUEUED -> if (d.queuePosition > 0) stringResource(R.string.stores_dl_queued_at, d.queuePosition) else stringResource(R.string.stores_dl_queued)
|
||||
DownloadState.RUNNING -> {
|
||||
@@ -375,7 +379,8 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(meta, fontSize = 12.sp, color = dim, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
|
||||
val metaColor = if (d.state == DownloadState.FAILED) colors.error else dim
|
||||
Text(meta, fontSize = 12.sp, color = metaColor, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
|
||||
if (d.state == DownloadState.RUNNING && (d.stage == DownloadStage.DOWNLOAD || d.stage == DownloadStage.INSTALL) && d.speedBps > 0) {
|
||||
Text(formatSpeed(d.speedBps), fontSize = 12.sp, color = dim, maxLines = 1)
|
||||
if (d.etaSeconds >= 0) Text(eta(d.etaSeconds), fontSize = 12.sp, color = dim, maxLines = 1)
|
||||
@@ -393,7 +398,10 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
|
||||
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.resume(ctx, d.key) }
|
||||
CancelAction { DownloadQueue.cancel(ctx, d.key) }
|
||||
}
|
||||
DownloadState.FAILED -> RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
|
||||
DownloadState.FAILED -> {
|
||||
RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
|
||||
CancelAction { DownloadQueue.clear(ctx, d.key) }
|
||||
}
|
||||
// Just installed (this row is on its way under the line): Play blooms where the bar gathered.
|
||||
DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) {
|
||||
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
|
||||
@@ -460,6 +468,7 @@ private fun StageBar(d: DownloadEntry) {
|
||||
val x = i * (segW + gap)
|
||||
drawRoundRect(colors.surfaceVariant, Offset(x, cy - h / 2f), Size(segW, h), CornerRadius(h / 2f))
|
||||
val base = when {
|
||||
d.state == DownloadState.FAILED -> colors.error
|
||||
done[i] -> pal.good
|
||||
actives[i] && paused -> pausedColor.copy(alpha = breath)
|
||||
actives[i] && stages[i] == DownloadStage.VERIFY -> verifyColor
|
||||
|
||||
@@ -72,10 +72,21 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
|
||||
Rise(1) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
targets.forEachIndexed { i, t ->
|
||||
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
|
||||
val freeBytes = t.freeBytes
|
||||
val isLow = com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, freeBytes)
|
||||
val freeText = if (freeBytes < 0L) {
|
||||
stringResource(R.string.stores_target_free_unknown)
|
||||
} else if (isLow) {
|
||||
stringResource(R.string.stores_storage_low, formatBytes(freeBytes), formatBytes(needed))
|
||||
} else {
|
||||
stringResource(R.string.stores_target_free, formatBytes(freeBytes))
|
||||
}
|
||||
TargetRow(
|
||||
label = if (t.removable) t.label else stringResource(R.string.stores_target_internal),
|
||||
free = stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)),
|
||||
free = freeText,
|
||||
removable = t.removable, focus = focus[i],
|
||||
warning = isLow,
|
||||
) {
|
||||
SessionPrefs.setStoresInstallTarget(ctx, t.root.absolutePath)
|
||||
StoresState.install(ctx, item, t.root)
|
||||
@@ -88,7 +99,7 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, onPick: () -> Unit) {
|
||||
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, warning: Boolean = false, onPick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
@@ -104,6 +115,6 @@ private fun TargetRow(label: String, free: String, removable: Boolean, focus: Fo
|
||||
) {
|
||||
Icon(if (removable) Icons.Outlined.SdCard else Icons.Outlined.Smartphone, null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(22.dp))
|
||||
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
Text(free, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
Text(free, fontSize = 12.sp, color = if (warning) colors.error else colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
@@ -511,10 +511,20 @@ private fun InstallWhere(item: CatalogItem) {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
targets.forEachIndexed { i, t ->
|
||||
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
|
||||
val freeBytes = t.freeBytes
|
||||
val isLow = com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, freeBytes)
|
||||
val trailingText = if (freeBytes < 0L) {
|
||||
stringResource(R.string.stores_target_free_unknown)
|
||||
} else if (isLow) {
|
||||
stringResource(R.string.stores_storage_low, formatBytes(freeBytes), formatBytes(needed))
|
||||
} else {
|
||||
stringResource(R.string.stores_target_free, formatBytes(freeBytes))
|
||||
}
|
||||
StepChoice(
|
||||
label = if (t.removable) t.label else internalLabel,
|
||||
icon = if (t.removable) androidx.compose.material.icons.Icons.Outlined.SdCard else androidx.compose.material.icons.Icons.Outlined.Smartphone,
|
||||
trailing = stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)),
|
||||
trailing = trailingText,
|
||||
enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(1 + i).then(if (i == defaultIndex) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
@@ -1306,8 +1316,11 @@ internal fun stageLabel(stage: DownloadStage): String = when (stage) {
|
||||
}
|
||||
|
||||
/** The game's web page, in the device's browser: this app buys nothing and claims nothing itself. */
|
||||
internal fun openStoreUrl(ctx: android.content.Context, item: CatalogItem) {
|
||||
val url = item.storeUrl.ifBlank { return }
|
||||
internal fun openStoreUrl(ctx: android.content.Context, item: CatalogItem) = openUrl(ctx, item.storeUrl)
|
||||
|
||||
/** A web page in the browser; nothing when the URL is blank or no app can open it. */
|
||||
internal fun openUrl(ctx: android.content.Context, url: String) {
|
||||
if (url.isBlank()) return
|
||||
runCatching { ctx.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
|
||||
|
||||
@@ -450,6 +450,20 @@ public final class WaylandCompositor {
|
||||
/** The Look the controls currently match ({@code null} = Custom); only named in the log line. */
|
||||
public static native void nativeSetLookName(String name);
|
||||
|
||||
/** Cardboard mode (waylandcomp/src/cardboard.h): two lens-distorted eye views side by side.
|
||||
* {@code source} 0 = the frame as a virtual screen, 1 = the frame is already a side-by-side
|
||||
* stereo pair. Distances in metres, field of view in degrees. */
|
||||
public static native void nativeSetCardboard(boolean enabled, int source, float ipdM, float screenDistM,
|
||||
float screenWidthM, float k1, float k2, float fovDeg,
|
||||
float lensInset, float chroma);
|
||||
|
||||
/** The head pose for Cardboard mode: head -> world rotation, row-major 3x3 (any thread). {@code live}
|
||||
* = a sensor produced it. */
|
||||
public static native void nativeSetCardboardPose(float[] rotation, boolean live);
|
||||
|
||||
/** Where the head pose is shared with the guest (waylandcomp/src/headpose_shm.h); set once. */
|
||||
public static native void nativeSetCardboardPoseFile(String path);
|
||||
|
||||
/** The in-game FPS limiter: frames per second, 0 = unlimited. Paces when replaced buffers go
|
||||
* back to the game, like the X11 IdleNotify pacer, so the game itself slows to the cap. */
|
||||
public static native void nativeSetFpsLimit(int fps);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,93 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string-array name="loading_hints">
|
||||
<item>La primera vez se descarga Steam. Puede tardar unos minutos.</item>
|
||||
<item>De forma predeterminada, al salir de la app Steam se pausa y continúa donde lo dejaste cuando vuelves.</item>
|
||||
<item>Tu control aparece como un control de Xbox 360. Si no, usa los controles en pantalla.</item>
|
||||
</string-array>
|
||||
<string-array name="loading_hints_desktop">
|
||||
<item>La primera vez se prepara el escritorio. Puede tardar unos minutos.</item>
|
||||
<item>De forma predeterminada, al salir de la app la sesión se pausa y continúa donde la dejaste cuando vuelves.</item>
|
||||
<item>El tacto funciona como un touchpad: arrastra para mover el puntero y toca para hacer clic.</item>
|
||||
<item>Tu control aparece como un control de Xbox 360. Si no, usa los controles en pantalla.</item>
|
||||
</string-array>
|
||||
<string name="second_library_import_hint">Agrega una biblioteca de Steam y busca juegos de Windows en ella. Los juegos que tienes usan sus entradas de Steam; el resto se convierten en accesos directos ajenos a Steam.</string>
|
||||
<string name="game_env_add">Agregar variable</string>
|
||||
<string name="game_env_xalia">Pon 0 para desactivar el asistente de navegación con control de Proton en este juego.</string>
|
||||
<string name="user_apps_add">Agregar</string>
|
||||
<string name="user_apps_added">%1$s agregada</string>
|
||||
<string name="user_apps_remove_confirm">Presiona de nuevo para quitar</string>
|
||||
<string name="user_apps_failed">No se pudo agregar la app</string>
|
||||
<string name="add_app_title">Agregar una app</string>
|
||||
<string name="add_app_confirm">Agregar</string>
|
||||
<string name="common_add_ellipsis">Agregar…</string>
|
||||
<string name="mode_osc_note">Auto muestra los controles en pantalla cuando no hay ningún control conectado.</string>
|
||||
<string name="mode_controller">Control</string>
|
||||
<string name="mode_controller_hint">Cómo ve Steam tu control. Se aplica en la próxima sesión.</string>
|
||||
<string name="mode_controller_deck">Control de Steam Deck</string>
|
||||
<string name="mode_controller_x360">Control de Xbox 360</string>
|
||||
<string name="games_add">Agregar juego</string>
|
||||
<string name="games_add_title">Agregar un juego:</string>
|
||||
<string name="mode_storage_note">Los juegos que cargan recursos desde la SD o el almacenamiento compartido pueden tener microcortes.</string>
|
||||
<string name="comp_no_proton">Aún no hay ningún Proton instalado. Inicia Steam una vez para descargar su Proton ARM64, o agrega GE-Proton o CachyOS desde Configuración.</string>
|
||||
<string name="perf_gpuclock_hint">Solo Adreno. Menos microcortes, más consumo de batería y calor.</string>
|
||||
<string name="perf_xalia_hint">Desactiva el asistente de navegación con control de Proton, que consume CPU en cada juego.</string>
|
||||
<string name="perf_fastpath_hint">Búsquedas de archivos más rápidas y menos microcortes. Desactívalo si un programa no encuentra sus archivos.</string>
|
||||
<string name="drawer_page_controller">Control</string>
|
||||
<string name="setup_manage">Administrar</string>
|
||||
<string name="setup_tab_controller">Control</string>
|
||||
<string name="setup_sign_in">Presiona Jugar en Steam e inicia sesión</string>
|
||||
<string name="setup_controller">Control</string>
|
||||
<string name="setup_controller_unavailable">Los ajustes del control no están disponibles.</string>
|
||||
<string name="setup_tool_files_hint">Explorar y administrar archivos</string>
|
||||
<string name="store_setup_text">Agrega Flatpak y lo conecta a Flathub (unos 20 MB). La primera app también descarga su runtime.</string>
|
||||
<string name="store_press_again">Presiona de nuevo para quitar</string>
|
||||
<string name="gate_no_toggle">Esta versión de Android no tiene un interruptor para ello, así que DroidDeck lo cambia mediante la Depuración inalámbrica. Tarda un minuto y no necesitas una computadora.</string>
|
||||
<string name="gate_code_needed">Ventana encontrada. Ingresa su código en la notificación.</string>
|
||||
<string name="gate_other_toggle">Depuración inalámbrica, dirección manual, ADB desde una computadora</string>
|
||||
<string name="gate_other_no_toggle">Dirección manual, ADB desde una computadora, Opciones de desarrollador</string>
|
||||
<string name="gate_some_roms">Algunas ROM agregan el interruptor de todos modos. Busca “procesos secundarios” en Opciones de desarrollador.</string>
|
||||
<string name="gate_manual_hint">Si la notificación no funciona, ingresa manualmente la dirección y el código de la ventana.</string>
|
||||
<string name="gate_enter_manually">Ingresar dirección manualmente</string>
|
||||
<string name="gate_from_computer">Desde una computadora con ADB:</string>
|
||||
<string name="wadb_enter_port">Vinculado. Ingresa el puerto de Ajustes.</string>
|
||||
<string name="wadb_computer_last">3 · ADB desde una computadora (último recurso)</string>
|
||||
<string name="wadb_computer_group">3 · ADB desde una computadora (último recurso)</string>
|
||||
<string name="ctrl_select_steam">Presiona Select para abrir el menú de Steam</string>
|
||||
<string name="ctrl_reset_all">Restablecer control</string>
|
||||
<string name="ctrl_reset_all_hint">Restaura todos los ajustes del control y la disposición</string>
|
||||
<string name="content_add_roms">Agrega juegos de %1$s a ROMs/%2$s.</string>
|
||||
<string name="desktop_remove_text">Elimina el escritorio y sus apps incluidas. Se conservan los juegos, las apps agregadas, los ajustes y las bibliotecas compartidas.</string>
|
||||
<string name="games_manage_saves">Administrar partidas guardadas</string>
|
||||
<string name="games_added">Juego agregado</string>
|
||||
<string name="deck_tab_gamepad">Control</string>
|
||||
<string name="game_shortcut_add">Agregar a la pantalla de inicio</string>
|
||||
<string name="game_shortcut_unsupported">Este launcher no puede agregar accesos directos. Usa Copiar enlace de inicio.</string>
|
||||
<string name="session_runtime_catalog_unreachable">No se pudo acceder al catálogo del runtime. Revisa la conexión y vuelve a presionar Jugar.</string>
|
||||
<string name="session_runtime_install_failed">El runtime de Linux no se instaló. Revisa el runtime en Configuración y vuelve a presionar Jugar.</string>
|
||||
<string name="session_desktop_install_failed">El escritorio no se instaló (%1$s). Revisa la conexión y presiona Escritorio de nuevo.</string>
|
||||
<string name="store_cat_audio_video">Audio y video</string>
|
||||
<string name="theme_graphite_detail">Superficies grafito, con el azul del orbe del logotipo para todo lo seleccionado, enfocado o presionado.</string>
|
||||
<string name="theme_icon_blue_detail">Fondo negro, texto blanco y el azul para todo lo seleccionado, enfocado o presionado.</string>
|
||||
<string name="pckb_key_enter">Enter ⏎</string>
|
||||
<string name="game_sync_err_added_games">La carpeta de juegos agregados no está disponible</string>
|
||||
<string name="fm_favorite_add">Agregar a Favoritos</string>
|
||||
<string name="fm_conflict_merge_hint">Combinar agrega y reemplaza archivos dentro de la carpeta existente.</string>
|
||||
<string name="fm_favorite_added">Se agregó \"%1$s\" a Favoritos</string>
|
||||
<string name="adbfix_enter_address">Ingresa la dirección IP y el puerto actuales de la Depuración inalámbrica</string>
|
||||
<string name="adbpair_six_digits">Ingresa los 6 dígitos del código</string>
|
||||
<string name="adbpair_code_rejected">Ese código no funcionó. Vuelve a abrir la ventana de vinculación e ingresa su nuevo código.</string>
|
||||
<string name="adbpair_waiting_long">Activa la Depuración inalámbrica y toca “Vincular dispositivo con código de vinculación”. Quédate en Ajustes: el código se ingresa en esta notificación.</string>
|
||||
<string name="adbpair_code_hint">Toca Ingresar código y escribe los 6 dígitos que muestra Ajustes.</string>
|
||||
<string name="adbpair_title_code">Ingresa el código de vinculación Wi-Fi</string>
|
||||
<string name="adbpair_enter_code">Ingresar código</string>
|
||||
<string name="phantom_instructions_fix">%1$s Si no es posible, conecta este dispositivo a una computadora con ADB y ejecuta el comando de abajo. Después vuelve aquí y comprueba de nuevo.</string>
|
||||
<string name="stores_kv_steam_on">se agrega a Steam al instalar (interfaz Deck + Steam Input)</string>
|
||||
<string name="stores_download_manager">Administrador de descargas</string>
|
||||
<string name="games_add_all">Agregar todos los juegos de esta carpeta</string>
|
||||
<plurals name="games_added_n">
|
||||
<item quantity="one">%1$d juego agregado</item>
|
||||
<item quantity="many">%1$d juegos agregados</item>
|
||||
<item quantity="other">%1$d juegos agregados</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -278,6 +278,9 @@
|
||||
<string name="mode_suspend_steam_note">Auto pauses and resumes when shown. Native prepares Steam for sleep first. Manual waits for Resume. Never keeps running.</string>
|
||||
<string name="mode_background_downloads">Keep downloads running</string>
|
||||
<string name="mode_background_downloads_hint">Delay background suspension while Steam is actively downloading.</string>
|
||||
<string name="mode_zram">zRAM compression</string>
|
||||
<string name="mode_zram_hint">While a game runs, the Steam client\'s memory is compressed into the device\'s zram, leaving more RAM for the game. Applies the next time Steam starts.</string>
|
||||
<string name="mode_zram_unsupported">Unavailable: this device has no zram or swap, or its kernel is older than 5.4.</string>
|
||||
<string name="mode_suspend_note">Auto pauses in the background and resumes when shown. Manual waits for Resume. Never keeps running.</string>
|
||||
<string name="mode_startup">Startup</string>
|
||||
<string name="mode_steam_startup">Start Steam with DroidDeck</string>
|
||||
@@ -575,6 +578,33 @@
|
||||
<string name="drawer_cas">Sharpening (CAS)</string>
|
||||
<string name="drawer_cas_level">Sharpening level</string>
|
||||
<string name="drawer_fake_hdr">Fake HDR</string>
|
||||
<string name="cardboard_title">Cardboard VR</string>
|
||||
<string name="cardboard_mode">Cardboard mode</string>
|
||||
<string name="cardboard_mode_hint">Left and right eye views for a phone VR viewer.</string>
|
||||
<string name="cardboard_source">Picture</string>
|
||||
<string name="cardboard_source_screen">Virtual screen</string>
|
||||
<string name="cardboard_source_sbs">Side-by-side 3D</string>
|
||||
<string name="cardboard_viewer">Viewer</string>
|
||||
<string name="cardboard_viewer_v2">Cardboard</string>
|
||||
<string name="cardboard_viewer_v1">Cardboard (2014)</string>
|
||||
<string name="cardboard_viewer_none">No lens</string>
|
||||
<string name="cardboard_ipd">Eye distance</string>
|
||||
<string name="cardboard_screen_width">Screen width</string>
|
||||
<string name="cardboard_screen_distance">Screen distance</string>
|
||||
<string name="cardboard_head_tracking">Head tracking</string>
|
||||
<string name="cardboard_no_sensor">This device has no rotation sensor.</string>
|
||||
<string name="cardboard_recenter">Recenter view</string>
|
||||
<string name="cardboard_recenter_button">Recenter</string>
|
||||
<string name="cardboard_steamvr">SteamVR (experimental)</string>
|
||||
<string name="cardboard_steamvr_install">Install</string>
|
||||
<string name="cardboard_steamvr_install_hint">Downloads Valve\'s ARM64 SteamVR (571 MB).</string>
|
||||
<string name="cardboard_steamvr_installing">Downloading and unpacking SteamVR…</string>
|
||||
<string name="cardboard_steamvr_start">Start</string>
|
||||
<string name="cardboard_steamvr_ready_hint">Runs SteamVR with your head as the headset; the picture switches to side-by-side 3D.</string>
|
||||
<string name="cardboard_steamvr_stop">Stop</string>
|
||||
<string name="cardboard_steamvr_running_hint">SteamVR is running.</string>
|
||||
<string name="cardboard_steamvr_unavailable">Not available in this session.</string>
|
||||
<string name="cardboard_steamvr_failed">SteamVR did not respond; see the session log.</string>
|
||||
<string name="drawer_deband">Debanding</string>
|
||||
<string name="drawer_deband_strength">Debanding strength</string>
|
||||
<string name="drawer_brightness">Brightness</string>
|
||||
@@ -686,6 +716,14 @@
|
||||
<string name="setup_saved_logs">Saved session logs</string>
|
||||
<string name="setup_saved_logs_hint">Keeps the newest %1$d</string>
|
||||
<string name="setup_clear_logs">Clear logs</string>
|
||||
<string name="setup_reset_settings">Reset all settings</string>
|
||||
<string name="setup_reset_settings_hint">Puts every setting back to its default</string>
|
||||
<string name="setup_reset_settings_button">Reset</string>
|
||||
<string name="setup_reset_settings_title">Reset all settings?</string>
|
||||
<string name="setup_reset_settings_body">Display, performance, controller, theme, language and launcher settings go back to their defaults. Your games, Steam sign-in, store accounts, downloaded drivers and storage folders are kept.</string>
|
||||
<string name="setup_reset_settings_profiles">Also reset game profiles (each game\'s Proton, FEX, components and environment, and the Default profile\'s environment)</string>
|
||||
<string name="setup_reset_settings_session_running">Stop the session before resetting settings.</string>
|
||||
<string name="setup_reset_settings_partial">Settings were reset, but some parts could not be. The logs have the details.</string>
|
||||
<string name="setup_offline">Offline mode</string>
|
||||
<string name="setup_sign_in_first">Sign in to Steam first</string>
|
||||
<string name="setup_launcher">Launcher</string>
|
||||
@@ -2144,6 +2182,17 @@
|
||||
<string name="achievements_none">%1$s lists no achievements for this game.</string>
|
||||
<string name="achievements_show_all">Show all %1$d</string>
|
||||
<string name="achievements_dialog_title">Achievements · %1$s</string>
|
||||
<!-- A store game's facts row: the store's own facts, then Metacritic and HowLongToBeat, looked up by name. -->
|
||||
<string name="stores_fact_developer">Developer</string>
|
||||
<string name="stores_fact_publisher">Publisher</string>
|
||||
<string name="stores_fact_released">Released</string>
|
||||
<string name="stores_fact_metacritic" translatable="false">Metacritic</string>
|
||||
<string name="stores_fact_hltb" translatable="false">HowLongToBeat</string>
|
||||
<string name="stores_hltb_main">Main</string>
|
||||
<string name="stores_hltb_extras">+ Extras</string>
|
||||
<string name="stores_hltb_completionist">Completionist</string>
|
||||
<string name="stores_hltb_hours">%1$s h</string>
|
||||
<string name="stores_hltb_minutes">%1$d min</string>
|
||||
<string name="stores_in_steam">✓ In Steam</string>
|
||||
<string name="stores_uninstall">Uninstall</string>
|
||||
<string name="stores_uninstalling">Uninstalling…</string>
|
||||
@@ -2208,6 +2257,9 @@
|
||||
<string name="stores_install_title">Install %1$s:</string>
|
||||
<string name="stores_target_internal">Internal</string>
|
||||
<string name="stores_target_free">%1$s free</string>
|
||||
<string name="stores_target_free_unknown">Free space unknown</string>
|
||||
<string name="stores_storage_insufficient">Not enough free space: need %1$s, only %2$s free</string>
|
||||
<string name="stores_storage_low">Insufficient space (%1$s free, need %2$s)</string>
|
||||
<string name="stores_notification_channel">Store downloads</string>
|
||||
<string name="stores_notification_channel_hint">Shows game download progress and keeps downloads running in the background</string>
|
||||
<string name="stores_notification_one">Downloading</string>
|
||||
@@ -2319,4 +2371,72 @@
|
||||
<string name="gog_achievements_enable_store">Enable GOG achievements in Stores settings</string>
|
||||
<string name="gog_achievements_unavailable">Achievements unavailable; check session logs</string>
|
||||
<string name="achievement_unlocked">Achievement unlocked</string>
|
||||
<string name="touch_paste">Paste</string>
|
||||
<string name="touch_dpad">D-pad</string>
|
||||
<string name="touch_left_stick">Left stick</string>
|
||||
<string name="touch_right_stick">Right stick</string>
|
||||
<string name="touch_menu">Menu</string>
|
||||
<string name="touch_keyboard">Keyboard</string>
|
||||
<string name="touch_dpad_up">D-pad up</string>
|
||||
<string name="touch_dpad_down">D-pad down</string>
|
||||
<string name="touch_dpad_left">D-pad left</string>
|
||||
<string name="touch_dpad_right">D-pad right</string>
|
||||
<string name="touch_title">Touch controls</string>
|
||||
<string name="touch_controller">Touch Controller</string>
|
||||
<string name="touch_mouse">Mouse</string>
|
||||
<string name="touch_on">On</string>
|
||||
<string name="touch_off">Off</string>
|
||||
<string name="touch_speed_slow">Slow</string>
|
||||
<string name="touch_speed_normal">Normal</string>
|
||||
<string name="touch_speed_fast">Fast</string>
|
||||
<string name="touch_edit_layout">Edit layout</string>
|
||||
<string name="touch_droiddeck_menu">DroidDeck menu</string>
|
||||
<string name="touch_drag_hint">Drag controls onto the screen</string>
|
||||
<string name="touch_arrange">Arrange</string>
|
||||
<string name="touch_discard">Discard</string>
|
||||
<string name="touch_saving">Saving…</string>
|
||||
<string name="touch_icon">Icon</string>
|
||||
<string name="touch_narrower">W−</string>
|
||||
<string name="touch_wider">W+</string>
|
||||
<string name="touch_shorter">H−</string>
|
||||
<string name="touch_taller">H+</string>
|
||||
<string name="touch_hide">Hide</string>
|
||||
<string name="touch_color_opacity">Color and opacity…</string>
|
||||
<string name="touch_copy_layout">Copy this layout</string>
|
||||
<string name="touch_layout_copied">Layout copied; paste it into any game\'s touch layout</string>
|
||||
<string name="touch_paste_layout">Paste copied layout</string>
|
||||
<string name="touch_reset_layout">Reset to Steam\'s default</string>
|
||||
<string name="touch_no_binding">This control has no binding in Steam to put an icon on</string>
|
||||
<string name="touch_icon_for">Icon for %1$s</string>
|
||||
<string name="touch_layout_color">Touch layout color</string>
|
||||
<string name="touch_done">Done</string>
|
||||
<string name="touch_save_failed">Could not save the touch layout</string>
|
||||
<string name="touch_saved">Touch layout saved to Steam</string>
|
||||
<string name="touch_app_id">App %1$d</string>
|
||||
<string name="touch_label_hint">Label (optional)</string>
|
||||
<string name="touch_icons_missing">Steam\'s icons were not found</string>
|
||||
<plurals name="touch_icons_found">
|
||||
<item quantity="one">%1$d icon from Steam</item>
|
||||
<item quantity="other">%1$d icons from Steam</item>
|
||||
</plurals>
|
||||
<string name="touch_icon_color">Icon color</string>
|
||||
<string name="touch_button_color">Button color</string>
|
||||
<string name="touch_no_icon">No icon</string>
|
||||
|
||||
<string name="stores_sync_sign_in">Checking sign-in…</string>
|
||||
<string name="stores_sync_library">Fetching your library…</string>
|
||||
<string name="stores_sync_game_list">Fetching game list…</string>
|
||||
<string name="stores_sync_details">Loading game details… (%1$d/%2$d)</string>
|
||||
<plurals name="stores_sync_games">
|
||||
<item quantity="one">Syncing %1$d game…</item>
|
||||
<item quantity="other">Syncing %1$d games…</item>
|
||||
</plurals>
|
||||
<string name="stores_sync_progress">Syncing… %1$d/%2$d</string>
|
||||
<string name="stores_sync_cover_art">Fetching cover art…</string>
|
||||
<string name="stores_sync_failed">Sync failed</string>
|
||||
<string name="stores_sync_no_games">No games found in your %1$s library</string>
|
||||
<string name="stores_sync_amazon_no_answer">Amazon Games did not answer for your library: refresh, or sign in again</string>
|
||||
<string name="stores_sync_gog_unreachable">Couldn\'t reach GOG</string>
|
||||
<string name="stores_sync_gog_unreadable">Could not read your GOG library</string>
|
||||
<string name="stores_registering">Registering with Steam…</string>
|
||||
</resources>
|
||||
@@ -3,9 +3,33 @@
|
||||
AppLanguage.supported and the values-* folders. -->
|
||||
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<locale android:name="en" />
|
||||
<locale android:name="id" />
|
||||
<locale android:name="ms" />
|
||||
<locale android:name="cs" />
|
||||
<locale android:name="da" />
|
||||
<locale android:name="de" />
|
||||
<locale android:name="es" />
|
||||
<locale android:name="es-419" />
|
||||
<locale android:name="fr" />
|
||||
<locale android:name="it" />
|
||||
<locale android:name="hu" />
|
||||
<locale android:name="nl" />
|
||||
<locale android:name="nb" />
|
||||
<locale android:name="pl" />
|
||||
<locale android:name="pt-BR" />
|
||||
<locale android:name="pt-PT" />
|
||||
<locale android:name="ro" />
|
||||
<locale android:name="fi" />
|
||||
<locale android:name="sv" />
|
||||
<locale android:name="vi" />
|
||||
<locale android:name="tr" />
|
||||
<locale android:name="el" />
|
||||
<locale android:name="bg" />
|
||||
<locale android:name="ru" />
|
||||
<locale android:name="uk" />
|
||||
<locale android:name="ar" />
|
||||
<locale android:name="hi" />
|
||||
<locale android:name="th" />
|
||||
<locale android:name="ja" />
|
||||
<locale android:name="ko" />
|
||||
<locale android:name="zh-CN" />
|
||||
|
||||
@@ -112,7 +112,12 @@ On-disk protocol (what a resumed run, by either engine, relies on): a file is as
|
||||
|
||||
## `com.droiddeck.launcher.stores.epic.EpicNative`
|
||||
|
||||
Two runs make up the native half of an Epic install:
|
||||
The manager's default Epic install is the **stream** run (`nativeStream`, below): the chunks
|
||||
are fetched in parallel and written straight into staged files as they arrive. The older batch
|
||||
pair below (fetch everything into a cache, then assemble) stays for A/B benchmarks (the hidden
|
||||
`storesEpicMode=batch` preference).
|
||||
|
||||
Two runs make up the native half of a batch Epic install:
|
||||
|
||||
1. **Fetch** (`nativeStart`): fills the chunk cache with verified, decompressed chunks for the
|
||||
files the manager says are pending. The Kotlin manager still fetches and parses the manifest
|
||||
@@ -224,6 +229,50 @@ Bannerlator's `BlEpicDownload.run(...)` wraps `nativeStart` in a blocking call t
|
||||
`onComplete`, then `nativeRelease` in `finally`. The same wrapper shape fits `nativeAssemble`
|
||||
(cancel is honoured between files; a multi-GB file finishes before the run stops).
|
||||
|
||||
### `nativeStream` — the adaptive install
|
||||
|
||||
| Method | JNI signature | Symbol |
|
||||
|---|---|---|
|
||||
| `nativeStream(...)`: Long | `([BLjava/lang/String;Ljava/lang/String;[Ljava/lang/String;[IJJLjava/lang/String;IILjava/lang/Object;)J` (last parameter is the listener) | `Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStream` |
|
||||
|
||||
```kotlin
|
||||
@JvmStatic private external fun nativeStream(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>,
|
||||
pendingFileIdx: IntArray, expectedBytes: Long, cacheBudget: Long, caBundlePath: String,
|
||||
maxWorkers: Int, processWorkers: Int, listener: StreamListener,
|
||||
): Long
|
||||
```
|
||||
|
||||
Parameters as `nativeStart`, except `expectedBytes` (the manager's `Σ fileSize` of the pending
|
||||
files, `-1` = no cross-check; no chunk count) and `cacheBudget` (the most bytes of shared chunks
|
||||
the cache may hold; the manager sizes it from free space, `0` = never cache, refetch instead).
|
||||
`chunkCacheDir` is `""` (`<installDir>/.chunks`) or a scratch directory; the manager falls back to
|
||||
`""` for a card install when internal storage cannot hold the budget.
|
||||
|
||||
What the run does (`epic/stream.rs`): a chunk one file part uses is decompressed, verified and
|
||||
written at the part's offset into that file's unique sibling `.droiddeck-epic-*.stage` file; a
|
||||
chunk several parts use is also kept in the cache, decompressed, as `<GUID>` (a later copy after
|
||||
an eviction as `<GUID>.<n>`) and deleted after its last covered part. The plan evicts by furthest
|
||||
next use when the budget would be exceeded and fetches the evicted chunk again later. Each file,
|
||||
once complete: synced, size and SHA-1 checked, `onBeforeReplace()` once for the whole run, then
|
||||
renamed over its destination. Cancel or failure removes every unfinished stage file before
|
||||
`onComplete`, leaves the destinations and the cache; success removes the cache directory.
|
||||
|
||||
Planning runs on the calling thread and also prepares the cache (keeps verified chunks this
|
||||
install needs, deletes everything else, as the Java writer does). A refusal returns `0` after a
|
||||
synchronous `onComplete(false, reason, 0)`; nothing was fetched or written, and the manager runs
|
||||
its bounded Java writer.
|
||||
|
||||
| `StreamListener` method | JNI signature | When |
|
||||
|---|---|---|
|
||||
| `onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long)` | `(JJIIJ)V` | after written parts (at most every 50 ms) and after every finished file; `filesBytes` = sizes of the files swapped in |
|
||||
| `onLog(line: String)` | `(Ljava/lang/String;)V` | engine lines: `stream-plan …`, the fetch core's lines, `stream-summary mode=adaptive …` (peak cache, peak staging, refetches, direct vs cached bytes) |
|
||||
| `onBeforeReplace(): Boolean` | `()Z` | once, before the first file replaces its destination; `false` or a throw fails the run with nothing replaced |
|
||||
| `onComplete(success: Boolean, error: String, bytes: Long)` | `(ZLjava/lang/String;J)V` | terminal, exactly once; `bytes` = file bytes written; `error` = `"cancelled"` on cancel |
|
||||
|
||||
Unlike the batch runs, the Kotlin wrapper (`EpicNative.stream`) waits for `onComplete` after a
|
||||
cancel without a time limit: the stage-file cleanup must be finished before the manager returns.
|
||||
|
||||
## `com.droiddeck.launcher.stores.amazon.AmazonNative`
|
||||
|
||||
The file-fetch pool of an Amazon Games install: one streamed HTTP GET per manifest file, SHA-256
|
||||
|
||||
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user