mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
40358e3b02 | ||
|
|
3cc5787d99 | ||
|
|
d8b05a8b30 | ||
|
|
525843c56c | ||
|
|
fa17d909ce | ||
|
|
5d276ab461 | ||
|
|
0859268591 | ||
|
|
20b0358162 | ||
|
|
65ebefc38f | ||
|
|
db12b8a1ad | ||
|
|
c0abf31a6b | ||
|
|
47950e2c1a | ||
|
|
8bb951ff50 | ||
|
|
9cb53e352c | ||
|
|
edabc44ff2 | ||
|
|
5115cad583 | ||
|
|
de75e6bdec | ||
|
|
b26934e914 | ||
|
|
60df9795dd | ||
|
|
cae6c78403 | ||
|
|
34ac8e2e72 | ||
|
|
cfaa57433e | ||
|
|
1d3487bf3b | ||
|
|
9d5a8c8e38 | ||
|
|
caf0d6e77b | ||
|
|
a4337db148 | ||
|
|
7e60e36195 | ||
|
|
db4c0b83db | ||
|
|
b06c3bb03c | ||
|
|
3e29f2084b | ||
|
|
28376a5639 | ||
|
|
ab99c1a3b3 | ||
|
|
049ded1812 | ||
|
|
ef1c208ed7 | ||
|
|
27171d8ffd | ||
|
|
cc63b40387 | ||
|
|
89ef2f1e90 | ||
|
|
b08d8e8e19 | ||
|
|
2dc74f7574 | ||
|
|
0dea571c63 | ||
|
|
5f088283af | ||
|
|
281a64f6c5 |
No files matched your search
@@ -25,6 +25,7 @@
|
||||
#include <gnu/lib-names.h>
|
||||
#endif
|
||||
#include <fcntl.h>
|
||||
#include <linux/futex.h>
|
||||
#include <linux/input.h>
|
||||
#include <linux/joystick.h>
|
||||
#include <linux/uinput.h>
|
||||
@@ -711,6 +712,19 @@ ring_header_is_valid(const FakeInputRingHeader *ring) {
|
||||
ring->capacity == FAKE_INPUT_RING_CAPACITY;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int ring_wait(const FakeInputRingHeader *ring, uint64_t seen, long ns) {
|
||||
struct timespec wait = {0, ns};
|
||||
if (syscall(SYS_futex, &ring->write_seq, FUTEX_WAIT, static_cast<uint32_t>(seen), &wait, nullptr, 0) == 0 ||
|
||||
errno == EAGAIN || errno == ETIMEDOUT)
|
||||
return 0;
|
||||
if (errno == EINTR) return -1;
|
||||
return nanosleep(&wait, nullptr);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void ring_wake(const FakeInputRingHeader *ring) {
|
||||
syscall(SYS_futex, &ring->write_seq, FUTEX_WAKE, INT_MAX, nullptr, nullptr, 0);
|
||||
}
|
||||
|
||||
struct SnapshotState {
|
||||
uint64_t sequence = 0;
|
||||
uint64_t write_seq = 0;
|
||||
@@ -1167,6 +1181,7 @@ __attribute__((visibility("hidden"))) static void flush_uinput(UinputWriter &w)
|
||||
__atomic_thread_fence(__ATOMIC_RELEASE);
|
||||
__atomic_store_n(&ring->snapshot_seq, sequence + 2, __ATOMIC_RELEASE);
|
||||
__atomic_store_n(&ring->write_seq, write_seq, __ATOMIC_RELEASE);
|
||||
ring_wake(ring);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static ssize_t
|
||||
@@ -1540,6 +1555,12 @@ __attribute__((visibility("hidden"))) static void sleep_us(int us) {
|
||||
nanosleep(&interval, nullptr);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void
|
||||
report_wait(const FakeInputRingHeader *ring, bool fresh, uint64_t seen, int us) {
|
||||
if (fresh) ring_wait(ring, seen, us * 1000L);
|
||||
else sleep_us(us);
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
|
||||
struct timespec now;
|
||||
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||
@@ -1712,7 +1733,8 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
|
||||
int32_t axes[8] = {};
|
||||
DeckExtras extras;
|
||||
while (live_pad_type() == PAD_TYPE_DECK) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -1722,7 +1744,7 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
|
||||
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
|
||||
errno != EAGAIN && errno != EWOULDBLOCK)
|
||||
break;
|
||||
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -1828,7 +1850,8 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
||||
SonyTouch touch;
|
||||
const uint64_t start_us = monotonic_us();
|
||||
while (live_pad_type() == type) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -1838,7 +1861,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
||||
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
|
||||
errno != EAGAIN && errno != EWOULDBLOCK)
|
||||
break;
|
||||
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -2037,7 +2060,8 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
||||
DeckExtras extras;
|
||||
const uint64_t start_us = monotonic_us();
|
||||
while (live_pad_type() == PAD_TYPE_STEAM) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -2048,7 +2072,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
||||
if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 &&
|
||||
errno != EAGAIN && errno != EWOULDBLOCK)
|
||||
break;
|
||||
sleep_us(controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -4016,6 +4040,7 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
|
||||
errno = ENODEV;
|
||||
return -1;
|
||||
}
|
||||
bool idle = false;
|
||||
for (int attempt = 0; attempt < 8; ++attempt) {
|
||||
size_t requested = count / sizeof(struct input_event);
|
||||
if (fake.keyframe_remaining == 0) {
|
||||
@@ -4037,7 +4062,10 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
|
||||
capture_keyframe(fake, snap);
|
||||
} else {
|
||||
size_t events = std::min<uint64_t>(requested, snap.write_seq - fake.read_seq);
|
||||
if (events == 0) break;
|
||||
if (events == 0) {
|
||||
idle = true;
|
||||
break;
|
||||
}
|
||||
const uint8_t *ring_events = reinterpret_cast<const uint8_t *>(fake.ring) +
|
||||
FAKE_INPUT_RING_HEADER_SIZE;
|
||||
std::vector<struct input_event> input_events(events);
|
||||
@@ -4083,9 +4111,14 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
|
||||
errno = EAGAIN;
|
||||
return -1;
|
||||
}
|
||||
const FakeInputRingHeader *ring = fake.ring;
|
||||
uint64_t seen = fake.read_seq;
|
||||
guard.unlock();
|
||||
#ifdef __GLIBC__
|
||||
pthread_testcancel();
|
||||
#endif
|
||||
struct timespec sleep_time = {0, backoff_ns};
|
||||
int result = nanosleep(&sleep_time, nullptr);
|
||||
int result = idle ? ring_wait(ring, seen, backoff_ns) : nanosleep(&sleep_time, nullptr);
|
||||
guard.lock();
|
||||
if (result < 0) return -1;
|
||||
if (low_latency(LATENCY_CONTROLLER)) backoff_ns = kLowLatencyRingWaitUs * 1000;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
#include <errno.h>
|
||||
#include <jni.h>
|
||||
#include <limits.h>
|
||||
#include <linux/futex.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -11,6 +14,13 @@ Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env,
|
||||
atomic_thread_fence(memory_order_release);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_input_FakeInputWriter_nativeWake(JNIEnv *env, jclass clazz, jobject buffer, jint offset) {
|
||||
(void)clazz;
|
||||
uint8_t *base = (*env)->GetDirectBufferAddress(env, buffer);
|
||||
if (base) syscall(SYS_futex, base + offset, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass clazz, jint tgid, jint tid, jint signal) {
|
||||
(void)env;
|
||||
|
||||
@@ -133,6 +133,24 @@ static void objects_destroy(void) {
|
||||
g_dsl = VK_NULL_HANDLE; g_sampler = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
void blendp_destroy(void) {
|
||||
if (g_dev) {
|
||||
for (int i = 0; i < NSRC; i++) src_release(i);
|
||||
for (int i = 0; i < NDST; i++) dst_release(i);
|
||||
for (int i = 0; i < NFMT; i++) {
|
||||
if (g_out[i].pipe) g_vk.DestroyPipeline(g_dev, g_out[i].pipe, NULL);
|
||||
if (g_out[i].rp) g_vk.DestroyRenderPass(g_dev, g_out[i].rp, NULL);
|
||||
}
|
||||
objects_destroy();
|
||||
}
|
||||
memset(g_src, 0, sizeof(g_src));
|
||||
memset(g_dst, 0, sizeof(g_dst));
|
||||
memset(g_out, 0, sizeof(g_out));
|
||||
g_ready = 0;
|
||||
g_frame = 1;
|
||||
g_dev = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
static int objects_ensure(void) {
|
||||
if (g_ready) return g_ready == 1 ? 0 : -1;
|
||||
g_ready = -1;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
void blendp_bind_device(VkDevice dev);
|
||||
void blendp_destroy(void);
|
||||
void blendp_forget_image(VkImage img);
|
||||
void blendp_begin_frame(void);
|
||||
|
||||
|
||||
@@ -311,6 +311,16 @@ static void objects_destroy(void) {
|
||||
g_dsl = VK_NULL_HANDLE; g_sampler = VK_NULL_HANDLE; g_rp = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
void vkp_cardboard_destroy(void) {
|
||||
if (g_dev) objects_destroy();
|
||||
g_dev = VK_NULL_HANDLE;
|
||||
g_ready = 0;
|
||||
memset(&g_t, 0, sizeof(g_t));
|
||||
memset(g_src, 0, sizeof(g_src));
|
||||
g_nsrc = 0;
|
||||
memset(&g_mp, 0, sizeof(g_mp));
|
||||
}
|
||||
|
||||
static int objects_ensure(void) {
|
||||
if (g_ready) return g_ready == 1 ? 0 : -1;
|
||||
if (!g_dev || !g_vk.CreateGraphicsPipelines) goto fail;
|
||||
|
||||
@@ -26,6 +26,7 @@ void vkp_cardboard_set_pose_file(const char *path);
|
||||
void vkp_cardboard_set_render_height(int height);
|
||||
|
||||
void vkp_cardboard_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops);
|
||||
void vkp_cardboard_destroy(void);
|
||||
int vkp_cardboard_active(void);
|
||||
int vkp_cardboard_source(void);
|
||||
int vkp_cardboard_pose_changed(void);
|
||||
|
||||
@@ -194,7 +194,31 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f
|
||||
fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable");
|
||||
}
|
||||
|
||||
void vkp_framegen_device_lost(void) { atomic_store(&g_dev_lost, 1); }
|
||||
void vkp_framegen_device_lost(void) {
|
||||
atomic_store(&g_dev_lost, 1);
|
||||
atomic_store(&g_dev_ready, 0);
|
||||
fge_device_lost();
|
||||
if (g_dev) {
|
||||
for (uint32_t i = 0; i < g_ring_n; i++) {
|
||||
if (g_ring[i].view && vk.DestroyImageView) vk.DestroyImageView(g_dev, g_ring[i].view, NULL);
|
||||
if (g_ring[i].img && vk.DestroyImage) vk.DestroyImage(g_dev, g_ring[i].img, NULL);
|
||||
if (g_ring[i].mem && vk.FreeMemory) vk.FreeMemory(g_dev, g_ring[i].mem, NULL);
|
||||
}
|
||||
}
|
||||
memset(g_ring, 0, sizeof(g_ring));
|
||||
g_ring_n = g_ring_w = g_ring_h = 0;
|
||||
g_ring_fmt = VK_FORMAT_UNDEFINED;
|
||||
g_engine_ok = 0;
|
||||
g_engine_kind = -1;
|
||||
g_engine_cache_gen = -1;
|
||||
g_built_w = g_built_h = 0;
|
||||
g_built_fmt = VK_FORMAT_UNDEFINED;
|
||||
g_planned = 0;
|
||||
memset(&vk, 0, sizeof(vk));
|
||||
g_dev = VK_NULL_HANDLE;
|
||||
g_queue = VK_NULL_HANDLE;
|
||||
g_qfam = 0;
|
||||
}
|
||||
|
||||
|
||||
static void destroy_ring(void) {
|
||||
|
||||
@@ -126,6 +126,23 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica
|
||||
(int)g_caps.storageOnSwapchainFormat);
|
||||
}
|
||||
|
||||
void fge_device_lost(void) {
|
||||
g_lsfg.reset();
|
||||
g_ddfg.reset();
|
||||
g_kind = -1;
|
||||
g_dev = VK_NULL_HANDLE;
|
||||
g_queue = VK_NULL_HANDLE;
|
||||
g_pd = VK_NULL_HANDLE;
|
||||
g_qfam = 0;
|
||||
g_ready = false;
|
||||
g_probed = false;
|
||||
g_table = {};
|
||||
g_caps = {};
|
||||
g_v12 = {};
|
||||
g_f2 = {};
|
||||
g_build[0] = 0;
|
||||
}
|
||||
|
||||
int fge_caps_ok(int kind) {
|
||||
if (!g_ready) return 0;
|
||||
if (kind == 1) return g_caps.storageOnSwapchainFormat ? 1 : 0;
|
||||
|
||||
@@ -12,6 +12,7 @@ extern "C" {
|
||||
|
||||
const void *fge_probe(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysicalDevice pd,
|
||||
VkFormat ring_fmt);
|
||||
void fge_device_lost(void);
|
||||
void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysicalDevice pd,
|
||||
VkDevice dev, VkQueue queue, uint32_t qfam, int features_enabled);
|
||||
int fge_caps_ok(int kind);
|
||||
|
||||
@@ -9,6 +9,7 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica
|
||||
VkDevice dev, VkQueue queue, uint32_t qfam, int features_enabled) {
|
||||
(void)gipa; (void)inst; (void)pd; (void)dev; (void)queue; (void)qfam; (void)features_enabled;
|
||||
}
|
||||
void fge_device_lost(void) {}
|
||||
int fge_caps_ok(int kind) { (void)kind; return 0; }
|
||||
const char *fge_caps_reason(void) { return "frame-generation engines not built into this compositor"; }
|
||||
int fge_format_ok(VkFormat fmt) { (void)fmt; return 0; }
|
||||
|
||||
@@ -73,8 +73,19 @@ void vkp_gpu_busy_device(VkPhysicalDevice pd, VkDevice dev, uint32_t family) {
|
||||
}
|
||||
|
||||
void vkp_gpu_busy_device_lost(void) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
atomic_store(&g_lost, 1);
|
||||
atomic_store(&g_timing, 0);
|
||||
if (g_v.device) {
|
||||
gpuload_ring_release(&g_ring, &g_v);
|
||||
g_ring.state = 0;
|
||||
}
|
||||
if (g_vk.QueueSubmit == timed_submit && g_submit) g_vk.QueueSubmit = g_submit;
|
||||
g_submit = NULL;
|
||||
memset(&g_v, 0, sizeof(g_v));
|
||||
g_family = g_bits = 0;
|
||||
g_was_on = 0;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeGpuBusyNs(JNIEnv *env, jclass cls) {
|
||||
|
||||
@@ -15,9 +15,9 @@
|
||||
X(GetPhysicalDeviceImageFormatProperties2) X(GetPhysicalDeviceProperties2)
|
||||
|
||||
#define VK_DEVICE_FUNCS(X) \
|
||||
X(GetDeviceQueue) X(CreateSwapchainKHR) X(DestroySwapchainKHR) X(GetSwapchainImagesKHR) \
|
||||
X(CreateCommandPool) X(AllocateCommandBuffers) X(CreateSemaphore) X(CreateFence) \
|
||||
X(DeviceWaitIdle) X(CreateImage) X(GetImageMemoryRequirements) X(AllocateMemory) \
|
||||
X(DestroyDevice) X(GetDeviceQueue) X(CreateSwapchainKHR) X(DestroySwapchainKHR) X(GetSwapchainImagesKHR) \
|
||||
X(CreateCommandPool) X(DestroyCommandPool) X(AllocateCommandBuffers) X(CreateSemaphore) X(CreateFence) \
|
||||
X(DeviceWaitIdle) X(DestroyFence) X(CreateImage) X(GetImageMemoryRequirements) X(AllocateMemory) \
|
||||
X(BindImageMemory) X(DestroyImage) X(FreeMemory) X(AcquireNextImageKHR) \
|
||||
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
|
||||
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
|
||||
|
||||
@@ -31,6 +31,15 @@
|
||||
#define LOGE(...) droiddeck_log("error", __VA_ARGS__)
|
||||
#define MOD_INVALID VKP_MOD_INVALID
|
||||
|
||||
enum vkp_image_source {
|
||||
VKP_IMAGE_SOURCE_NONE = 0,
|
||||
VKP_IMAGE_SOURCE_DMABUF,
|
||||
VKP_IMAGE_SOURCE_AHB_WLEGL,
|
||||
VKP_IMAGE_SOURCE_AHB_SOURCE,
|
||||
VKP_IMAGE_SOURCE_AHB_TARGET,
|
||||
VKP_IMAGE_SOURCE_SHM
|
||||
};
|
||||
|
||||
struct vkp_image {
|
||||
VkImage image;
|
||||
VkDeviceMemory mem;
|
||||
@@ -47,14 +56,61 @@ struct vkp_image {
|
||||
VkBuffer linear_buf;
|
||||
VkDeviceMemory linear_mem;
|
||||
VkBufferImageCopy linear_copy;
|
||||
enum vkp_image_source source_type;
|
||||
int source_fd;
|
||||
uint32_t source_drm_format, source_stride, source_offset;
|
||||
uint64_t source_modifier;
|
||||
uint8_t *recovery_pixels;
|
||||
struct vkp_image *next;
|
||||
};
|
||||
|
||||
static struct vkp_image *g_client_images;
|
||||
static struct vkp_image *g_rb;
|
||||
static int g_recovery_attempted;
|
||||
|
||||
static void image_register(struct vkp_image *img) {
|
||||
if (!img) return;
|
||||
img->next = g_client_images;
|
||||
g_client_images = img;
|
||||
}
|
||||
|
||||
static void image_unregister(struct vkp_image *img) {
|
||||
struct vkp_image **p = &g_client_images;
|
||||
while (*p && *p != img) p = &(*p)->next;
|
||||
if (*p) *p = img->next;
|
||||
if (img) img->next = NULL;
|
||||
}
|
||||
|
||||
static void image_track_dmabuf(struct vkp_image *img, int fd, uint32_t drm_format,
|
||||
uint64_t modifier, uint32_t stride, uint32_t offset) {
|
||||
img->source_fd = dup(fd);
|
||||
img->source_type = img->source_fd >= 0 ? VKP_IMAGE_SOURCE_DMABUF : VKP_IMAGE_SOURCE_NONE;
|
||||
img->source_drm_format = drm_format;
|
||||
img->source_modifier = modifier;
|
||||
img->source_stride = stride;
|
||||
img->source_offset = offset;
|
||||
image_register(img);
|
||||
if (img->source_type == VKP_IMAGE_SOURCE_NONE)
|
||||
droiddeck_log("gpu", "device recovery unavailable for one DMA-BUF: source FD could not be retained");
|
||||
}
|
||||
|
||||
static void image_track_ahb(struct vkp_image *img, AHardwareBuffer *buffer,
|
||||
enum vkp_image_source source_type) {
|
||||
AHardwareBuffer_acquire(buffer);
|
||||
img->android_buffer = buffer;
|
||||
img->source_type = source_type;
|
||||
image_register(img);
|
||||
}
|
||||
|
||||
static void destroy_image_objects(struct vkp_image *img);
|
||||
|
||||
static ANativeWindow *g_window;
|
||||
static int g_ahb_import;
|
||||
static int g_drm_modifiers;
|
||||
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
|
||||
static int g_allow_driver_fallback;
|
||||
static int g_dev_state;
|
||||
static int dev_init(void);
|
||||
static void device_lost(const char *where);
|
||||
static const char *vk_result_name(VkResult r);
|
||||
|
||||
@@ -518,7 +574,7 @@ static void log_display_driver(void) {
|
||||
g_library_name);
|
||||
}
|
||||
|
||||
static int dev_init(void) {
|
||||
static int dev_init_once(void) {
|
||||
if (g_dev_state != 0) return g_dev_state == 1 ? 0 : -1;
|
||||
|
||||
if (vk_loader_open(g_driver_path, g_library_name, g_native_lib_dir) != 0) {
|
||||
@@ -720,6 +776,189 @@ static int dev_init(void) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void suspend_client_images(void) {
|
||||
for (struct vkp_image *img = g_client_images; img; img = img->next) {
|
||||
if (img->source_type == VKP_IMAGE_SOURCE_SHM && !img->recovery_pixels)
|
||||
img->source_type = VKP_IMAGE_SOURCE_NONE;
|
||||
if (img->map && g_vk.UnmapMemory && g_dev) g_vk.UnmapMemory(g_dev, img->mem);
|
||||
img->map = NULL;
|
||||
destroy_image_objects(img);
|
||||
}
|
||||
}
|
||||
|
||||
static int restore_client_image(struct vkp_image *img) {
|
||||
if (!img || img->source_type == VKP_IMAGE_SOURCE_NONE) return -1;
|
||||
struct vkp_image *replacement = NULL;
|
||||
switch (img->source_type) {
|
||||
case VKP_IMAGE_SOURCE_DMABUF:
|
||||
if (img->source_fd >= 0)
|
||||
replacement = vkp_image_import_dmabuf(img->source_fd, img->source_drm_format, img->source_modifier,
|
||||
img->w, img->h, img->source_stride, img->source_offset,
|
||||
img->blit_dst);
|
||||
break;
|
||||
case VKP_IMAGE_SOURCE_AHB_WLEGL:
|
||||
replacement = vkp_image_from_android_buffer(img->android_buffer);
|
||||
break;
|
||||
case VKP_IMAGE_SOURCE_AHB_SOURCE:
|
||||
replacement = vkp_image_from_ahb(img->android_buffer);
|
||||
break;
|
||||
case VKP_IMAGE_SOURCE_AHB_TARGET:
|
||||
replacement = vkp_image_import_ahb(img->android_buffer, NULL, 0);
|
||||
break;
|
||||
case VKP_IMAGE_SOURCE_SHM:
|
||||
replacement = vkp_image_create_shm(img->w, img->h);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (!replacement) return -1;
|
||||
|
||||
struct vkp_image *next = img->next;
|
||||
const enum vkp_image_source old_type = img->source_type;
|
||||
const int old_fd = img->source_fd;
|
||||
AHardwareBuffer *old_ahb = img->android_buffer;
|
||||
uint8_t *pixels = img->recovery_pixels;
|
||||
image_unregister(replacement);
|
||||
*img = *replacement;
|
||||
img->next = next;
|
||||
free(replacement);
|
||||
if (old_type == VKP_IMAGE_SOURCE_DMABUF && old_fd >= 0) close(old_fd);
|
||||
if (old_ahb) AHardwareBuffer_release(old_ahb);
|
||||
if (old_type == VKP_IMAGE_SOURCE_SHM && pixels && img->map) {
|
||||
const size_t row_bytes = (size_t)img->w * 4;
|
||||
for (int y = 0; y < img->h; y++)
|
||||
memcpy((uint8_t *)img->map + img->offset + (size_t)y * img->row_pitch,
|
||||
pixels + (size_t)y * row_bytes, row_bytes);
|
||||
img->recovery_pixels = pixels;
|
||||
pixels = NULL;
|
||||
}
|
||||
free(pixels);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int restore_client_images(void) {
|
||||
int failed = 0;
|
||||
for (struct vkp_image *img = g_client_images; img; ) {
|
||||
struct vkp_image *next = img->next;
|
||||
if (restore_client_image(img) != 0) {
|
||||
failed++;
|
||||
droiddeck_log("error", "GPU recovery: could not re-import a retained %dx%d client buffer",
|
||||
img->w, img->h);
|
||||
}
|
||||
img = next;
|
||||
}
|
||||
return failed ? -1 : 0;
|
||||
}
|
||||
|
||||
static void release_lost_device(void) {
|
||||
vkp_pass_abort();
|
||||
blendp_destroy();
|
||||
vkp_effects_destroy();
|
||||
hdrc_destroy();
|
||||
vkp_cardboard_destroy();
|
||||
vkp_framegen_device_lost();
|
||||
vkp_gpu_busy_device_lost();
|
||||
suspend_client_images();
|
||||
|
||||
if (g_rb) {
|
||||
vkp_image_destroy(g_rb);
|
||||
g_rb = NULL;
|
||||
}
|
||||
if (g_scene.img) g_vk.DestroyImage(g_dev, g_scene.img, NULL);
|
||||
if (g_scene.mem) g_vk.FreeMemory(g_dev, g_scene.mem, NULL);
|
||||
memset(&g_scene, 0, sizeof(g_scene));
|
||||
struct vkp_img_slot *slots[] = {&g_mixed, &g_hdrscene, &g_fgscene};
|
||||
for (size_t i = 0; i < sizeof(slots) / sizeof(slots[0]); i++) {
|
||||
if (slots[i]->img) g_vk.DestroyImage(g_dev, slots[i]->img, NULL);
|
||||
if (slots[i]->mem) g_vk.FreeMemory(g_dev, slots[i]->mem, NULL);
|
||||
memset(slots[i], 0, sizeof(*slots[i]));
|
||||
}
|
||||
if (g_black_img) g_vk.DestroyImage(g_dev, g_black_img, NULL);
|
||||
if (g_black_mem) g_vk.FreeMemory(g_dev, g_black_mem, NULL);
|
||||
g_black_img = VK_NULL_HANDLE;
|
||||
g_black_mem = VK_NULL_HANDLE;
|
||||
g_black_state = 0;
|
||||
|
||||
for (int i = 0; i < MAX_PRESENTS; i++) {
|
||||
if (g_acqs[i]) g_vk.DestroySemaphore(g_dev, g_acqs[i], NULL);
|
||||
if (g_rnds[i]) g_vk.DestroySemaphore(g_dev, g_rnds[i], NULL);
|
||||
g_acqs[i] = g_rnds[i] = VK_NULL_HANDLE;
|
||||
}
|
||||
if (g_wait_sem) g_vk.DestroySemaphore(g_dev, g_wait_sem, NULL);
|
||||
g_wait_sem = VK_NULL_HANDLE;
|
||||
if (g_fence) g_vk.DestroyFence(g_dev, g_fence, NULL);
|
||||
g_fence = VK_NULL_HANDLE;
|
||||
if (g_pool) g_vk.DestroyCommandPool(g_dev, g_pool, NULL);
|
||||
g_pool = VK_NULL_HANDLE;
|
||||
memset(g_cmds, 0, sizeof(g_cmds));
|
||||
|
||||
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
|
||||
g_swapchain = VK_NULL_HANDLE;
|
||||
free(g_images);
|
||||
g_images = NULL;
|
||||
g_nimg = 0;
|
||||
if (g_surface) g_vk.DestroySurfaceKHR(g_inst, g_surface, NULL);
|
||||
g_surface = VK_NULL_HANDLE;
|
||||
if (g_dev) g_vk.DestroyDevice(g_dev, NULL);
|
||||
g_dev = VK_NULL_HANDLE;
|
||||
if (g_inst) g_vk.DestroyInstance(g_inst, NULL);
|
||||
g_inst = VK_NULL_HANDLE;
|
||||
vk_loader_close();
|
||||
|
||||
g_pd = VK_NULL_HANDLE;
|
||||
g_queue = VK_NULL_HANDLE;
|
||||
g_qfam = 0;
|
||||
memset(&g_memprops, 0, sizeof(g_memprops));
|
||||
memset(&g_map, 0, sizeof(g_map));
|
||||
memset(&g_extent, 0, sizeof(g_extent));
|
||||
memset(&g_caps_extent, 0, sizeof(g_caps_extent));
|
||||
g_surface_transform_known = 0;
|
||||
g_surface_checked_ns = 0;
|
||||
g_ahb_import = 0;
|
||||
g_drm_modifiers = 0;
|
||||
g_colorspace_ext = 0;
|
||||
g_import_sem_fd = NULL;
|
||||
g_ahb_properties = NULL;
|
||||
g_set_hdr_metadata = NULL;
|
||||
g_swap_extra = 0;
|
||||
g_swap_is_hdr = 0;
|
||||
g_swap_fmt = VK_FORMAT_UNDEFINED;
|
||||
g_swap_md_identity = 0;
|
||||
g_swap_retry_at_ns = 0;
|
||||
g_swap_fail_logged = 0;
|
||||
g_base_black = 0;
|
||||
g_dev_state = 0;
|
||||
}
|
||||
|
||||
static int dev_init(void) {
|
||||
if (g_dev_state != -2) return dev_init_once();
|
||||
if (g_recovery_attempted) return -1;
|
||||
g_recovery_attempted = 1;
|
||||
droiddeck_log("gpu", "VK_ERROR_DEVICE_LOST: attempting one in-process compositor recovery");
|
||||
release_lost_device();
|
||||
if (dev_init_once() != 0) {
|
||||
if (g_dev_state == -3) {
|
||||
droiddeck_log("error", "GPU recovery initialization left completion unknown; retaining resources");
|
||||
return -1;
|
||||
}
|
||||
release_lost_device();
|
||||
g_dev_state = -2;
|
||||
droiddeck_log("error", "GPU recovery failed while recreating the Vulkan device; restart the session");
|
||||
set_fault("the display GPU was lost and in-process recovery failed");
|
||||
return -1;
|
||||
}
|
||||
if (restore_client_images() != 0) {
|
||||
release_lost_device();
|
||||
g_dev_state = -2;
|
||||
droiddeck_log("error", "GPU recovery could not restore every client buffer; restart the session");
|
||||
set_fault("the display GPU was lost and some client buffers could not be restored");
|
||||
return -1;
|
||||
}
|
||||
g_recovery_attempted = 0;
|
||||
droiddeck_log("gpu", "Vulkan device and retained client buffers recovered");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int vkp_ready(void) { return dev_init(); }
|
||||
|
||||
static int swap_init_locked(void);
|
||||
@@ -1216,6 +1455,8 @@ struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer) {
|
||||
if (result != VK_SUCCESS) goto fail;
|
||||
AHardwareBuffer_acquire(buffer);
|
||||
img->android_buffer = buffer;
|
||||
img->source_type = VKP_IMAGE_SOURCE_AHB_WLEGL;
|
||||
image_register(img);
|
||||
return img;
|
||||
fail:
|
||||
LOGE("android_wlegl: Vulkan buffer import failed: %s", vk_result_name(result));
|
||||
@@ -1367,6 +1608,7 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
||||
if (linear_size && import_linear_dmabuf(img, fd, &linear_copy, linear_size) == 0) {
|
||||
if (padded_target) droiddeck_log("gpu", "linear layer target %dx%d writes at pitch %u via DMA-BUF",
|
||||
w, h, stride);
|
||||
image_track_dmabuf(img, fd, drm_format, modifier, stride, offset);
|
||||
return img;
|
||||
}
|
||||
if (padded_target) { free(img); return NULL; }
|
||||
@@ -1436,11 +1678,12 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
||||
g_vk.FreeMemory(g_dev, img->mem, NULL); g_vk.DestroyImage(g_dev, img->image, NULL);
|
||||
free(img); return NULL;
|
||||
}
|
||||
image_track_dmabuf(img, fd, drm_format, modifier, stride, offset);
|
||||
return img;
|
||||
}
|
||||
|
||||
void vkp_wait_idle(void) {
|
||||
if (g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
|
||||
if (g_dev_state == 1 && g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
|
||||
}
|
||||
|
||||
struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
|
||||
@@ -1490,6 +1733,7 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
|
||||
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
|
||||
g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return NULL;
|
||||
}
|
||||
image_track_ahb(img, ahb, VKP_IMAGE_SOURCE_AHB_SOURCE);
|
||||
return img;
|
||||
}
|
||||
|
||||
@@ -1585,6 +1829,7 @@ struct vkp_image *vkp_image_import_ahb(struct AHardwareBuffer *ahb, char *info,
|
||||
if (info && info_n)
|
||||
snprintf(info, info_n, "VkFormat %d, %llu bytes, memory type %d of memoryTypeBits %#x", (int)fp.format,
|
||||
(unsigned long long)hp.allocationSize, idx, hp.memoryTypeBits);
|
||||
image_track_ahb(img, ahb, VKP_IMAGE_SOURCE_AHB_TARGET);
|
||||
return img;
|
||||
}
|
||||
|
||||
@@ -1638,13 +1883,34 @@ struct vkp_image *vkp_image_create_shm(int w, int h) {
|
||||
if (g_vk.MapMemory(g_dev, img->mem, 0, req.size, 0, &img->map) != VK_SUCCESS) {
|
||||
vkp_image_destroy(img); return NULL;
|
||||
}
|
||||
img->source_type = VKP_IMAGE_SOURCE_SHM;
|
||||
image_register(img);
|
||||
return img;
|
||||
}
|
||||
|
||||
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride) {
|
||||
if (g_dev_state != 1 || !img || !img->map || !data) return;
|
||||
size_t rowbytes = (size_t)img->w * 4;
|
||||
if (!img || !data || img->w <= 0 || img->h <= 0 || stride <= 0 ||
|
||||
(size_t)img->w > SIZE_MAX / 4)
|
||||
return;
|
||||
|
||||
const size_t full_rowbytes = (size_t)img->w * 4;
|
||||
size_t rowbytes = full_rowbytes;
|
||||
if ((size_t)stride < rowbytes) rowbytes = (size_t)stride;
|
||||
|
||||
if (img->source_type == VKP_IMAGE_SOURCE_SHM && !img->recovery_pixels) {
|
||||
if ((size_t)img->h <= SIZE_MAX / full_rowbytes) {
|
||||
const size_t bytes = full_rowbytes * (size_t)img->h;
|
||||
img->recovery_pixels = calloc(1, bytes);
|
||||
}
|
||||
if (!img->recovery_pixels) img->source_type = VKP_IMAGE_SOURCE_NONE;
|
||||
}
|
||||
if (img->source_type == VKP_IMAGE_SOURCE_SHM && img->recovery_pixels) {
|
||||
for (int y = 0; y < img->h; y++)
|
||||
memcpy(img->recovery_pixels + (size_t)y * full_rowbytes,
|
||||
(const uint8_t *)data + (size_t)y * stride, rowbytes);
|
||||
}
|
||||
|
||||
if (g_dev_state != 1 || !img->map) return;
|
||||
for (int y = 0; y < img->h; y++)
|
||||
memcpy((uint8_t *)img->map + img->offset + (size_t)y * img->row_pitch,
|
||||
(const uint8_t *)data + (size_t)y * stride, rowbytes);
|
||||
@@ -1661,7 +1927,10 @@ void vkp_image_destroy(struct vkp_image *img) {
|
||||
if (img->map) g_vk.UnmapMemory(g_dev, img->mem);
|
||||
destroy_image_objects(img);
|
||||
}
|
||||
image_unregister(img);
|
||||
if (img->source_type == VKP_IMAGE_SOURCE_DMABUF && img->source_fd >= 0) close(img->source_fd);
|
||||
if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
|
||||
free(img->recovery_pixels);
|
||||
free(img);
|
||||
}
|
||||
|
||||
@@ -1925,14 +2194,23 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n,
|
||||
}
|
||||
|
||||
static void device_lost(const char *where) {
|
||||
if (g_dev_state == -2) return;
|
||||
if (g_dev_state == -2 || g_dev_state == -3) return;
|
||||
|
||||
if (g_dev_state == 1) {
|
||||
VkResult idle = g_vk.DeviceWaitIdle ? g_vk.DeviceWaitIdle(g_dev) : VK_ERROR_UNKNOWN;
|
||||
if (idle != VK_SUCCESS && idle != VK_ERROR_DEVICE_LOST) {
|
||||
quarantine_pending_work(idle, "device-loss idle");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
g_dev_state = -2;
|
||||
g_base_black = 0;
|
||||
vkp_framegen_device_lost();
|
||||
vkp_gpu_busy_device_lost();
|
||||
droiddeck_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
|
||||
"restart the session", where);
|
||||
set_fault("the display GPU was lost (VK_ERROR_DEVICE_LOST in %s)", where);
|
||||
droiddeck_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor will try one in-process recovery",
|
||||
where);
|
||||
set_fault("the display GPU was lost (VK_ERROR_DEVICE_LOST in %s); recovery pending", where);
|
||||
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
|
||||
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
|
||||
g_swapchain = VK_NULL_HANDLE;
|
||||
@@ -2157,11 +2435,10 @@ static void send_hdr_metadata(const struct droiddeck_color *c) {
|
||||
static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
|
||||
const struct vkp_hdr_frame *hf, int *how) {
|
||||
if (how) *how = 0;
|
||||
if (g_dev_state < 0) return -1;
|
||||
if (g_dev_state == -1 || g_dev_state == -3) return -1;
|
||||
vkp_apply_window_request();
|
||||
sc_layer_hide_base();
|
||||
check_surface_changed();
|
||||
if (g_dev_state == -2) return -1;
|
||||
if (dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
|
||||
if (g_swapchain && vkp_framegen_extra_images() != g_swap_extra) {
|
||||
@@ -2506,7 +2783,7 @@ void vkp_signal_first_frame(void) {
|
||||
}
|
||||
|
||||
int vkp_update_map(int scene_w, int scene_h) {
|
||||
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
if (dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
if (vkp_quest_layer_presentation()) {
|
||||
int w = ANativeWindow_getWidth(g_window), h = ANativeWindow_getHeight(g_window);
|
||||
if (w <= 0 || h <= 0) return -1;
|
||||
@@ -2580,7 +2857,7 @@ static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_la
|
||||
}
|
||||
|
||||
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
|
||||
if (!src || src->blit_dst || !dst || !dst->blit_dst || dev_init() != 0) {
|
||||
if (wait_fd >= 0) close(wait_fd);
|
||||
return -1;
|
||||
}
|
||||
@@ -2643,11 +2920,9 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
|
||||
|
||||
|
||||
static struct vkp_image *g_rb;
|
||||
|
||||
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
|
||||
if (!src || src->blit_dst || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
|
||||
g_dev_state == -2 || dev_init() != 0)
|
||||
dev_init() != 0)
|
||||
return -1;
|
||||
if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; }
|
||||
if (!g_rb) {
|
||||
|
||||
@@ -6960,9 +6960,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
|
||||
if (runtimeRemovalBlocked) return
|
||||
if (!hasFocus) {
|
||||
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
|
||||
if (::touchpad.isInitialized) touchpad.cancel()
|
||||
if (::scrollTouch.isInitialized) scrollTouch.cancel()
|
||||
cancelTouchGestures()
|
||||
releaseHeldGuestInput()
|
||||
}
|
||||
if (hasFocus && !pipUi) {
|
||||
|
||||
@@ -233,14 +233,14 @@ object AddedGames {
|
||||
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
|
||||
if (folder.path in removed) continue
|
||||
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
|
||||
for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true)
|
||||
timed(folder) { for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true) }
|
||||
}
|
||||
}
|
||||
for (entry in AddedExes.list(context)) {
|
||||
val folder = File(entry.folder)
|
||||
if (folder.path in removed || !folder.isDirectory) continue
|
||||
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
|
||||
scanGame(context, folder, out, single = entry, reuse = true)
|
||||
timed(folder) { scanGame(context, folder, out, single = entry, reuse = true) }
|
||||
}
|
||||
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
|
||||
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out, reuse = true)
|
||||
@@ -250,6 +250,15 @@ object AddedGames {
|
||||
return out.distinctBy { it.folder.canonicalPath }
|
||||
}
|
||||
|
||||
private const val SLOW_FOLDER_MS = 1_000L
|
||||
|
||||
private inline fun timed(folder: File, block: () -> Unit) {
|
||||
val began = android.os.SystemClock.elapsedRealtime()
|
||||
block()
|
||||
val took = android.os.SystemClock.elapsedRealtime() - began
|
||||
if (took >= SLOW_FOLDER_MS) Log.i(TAG, "games: scanning ${folder.path} took ${took}ms")
|
||||
}
|
||||
|
||||
fun single(context: Context, folderPath: String, reuse: Boolean = false): Game? {
|
||||
val folder = File(folderPath)
|
||||
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
|
||||
@@ -564,8 +573,10 @@ object AddedGames {
|
||||
|
||||
class Listed(val appId: Long, val name: String, val launchOptions: String)
|
||||
|
||||
fun listingFile(context: Context): File = File(context.filesDir, "session/added-games.json")
|
||||
|
||||
fun listed(context: Context): List<Listed>? = runCatching {
|
||||
val file = File(context.filesDir, "session/added-games.json")
|
||||
val file = listingFile(context)
|
||||
if (!file.isFile) return null
|
||||
val entries = org.json.JSONArray(file.readText())
|
||||
(0 until entries.length()).mapNotNull { i ->
|
||||
@@ -575,7 +586,7 @@ object AddedGames {
|
||||
|
||||
fun writeListing(context: Context, games: List<Game>,
|
||||
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
|
||||
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
|
||||
val file = listingFile(context).apply { parentFile?.mkdirs() }
|
||||
val json = StringBuilder("[")
|
||||
games.forEachIndexed { i, g ->
|
||||
if (i > 0) json.append(',')
|
||||
@@ -596,10 +607,24 @@ object AddedGames {
|
||||
if (games.isNotEmpty() || i > 0) json.append(',')
|
||||
json.append(entry.toString())
|
||||
}
|
||||
file.writeText(json.append(']').toString())
|
||||
val text = json.append(']').toString()
|
||||
synchronized(listing) {
|
||||
val partial = File(file.parentFile, file.name + ".part")
|
||||
try {
|
||||
partial.writeText(text)
|
||||
java.nio.file.Files.move(partial.toPath(), file.toPath(),
|
||||
java.nio.file.StandardCopyOption.ATOMIC_MOVE, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
} catch (e: java.io.IOException) {
|
||||
Log.w(TAG, "games: listing not replaced: ${e.message}")
|
||||
partial.delete()
|
||||
if (!file.isFile) file.writeText(text)
|
||||
}
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
private val listing = Any()
|
||||
|
||||
private fun artGuestPath(context: Context, file: File): String? {
|
||||
val files = context.filesDir.absolutePath
|
||||
if (file.absolutePath.startsWith("$files/")) return file.absolutePath
|
||||
|
||||
@@ -1,17 +1,31 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.SteamLiveShortcuts
|
||||
import java.io.File
|
||||
import java.util.concurrent.Callable
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
object AddedGamesPublisher {
|
||||
private const val TAG = "AddedGamesPublisher"
|
||||
private const val CLIENT_WAIT_MS = 600_000L
|
||||
private const val POLL_MS = 1_000L
|
||||
private const val RETRY_MS = 5_000L
|
||||
|
||||
@VisibleForTesting
|
||||
@Volatile
|
||||
internal var now = false
|
||||
|
||||
@VisibleForTesting
|
||||
@Volatile
|
||||
internal var live: (Context, List<AddedGames.Game>, (AddedGames.Game) -> Boolean) -> Boolean = SteamLiveShortcuts::sync
|
||||
|
||||
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "added-games-publish") }
|
||||
|
||||
fun later(context: Context, live: () -> Unit = {}) {
|
||||
@@ -23,10 +37,56 @@ object AddedGamesPublisher {
|
||||
if (now) work.run() else worker.execute(work)
|
||||
}
|
||||
|
||||
fun republish(context: Context) {
|
||||
fun republish(context: Context): List<AddedGames.Game> {
|
||||
val games = AddedGames.scan(context)
|
||||
AddedGames.writeListing(context, games)
|
||||
val arch = com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(context)
|
||||
val arch = SessionPrefs.activeSteamClientArch(context)
|
||||
LibraryCache.save(context, Library.launchableGames(context, added = games, arch = arch), arch == "x86_64")
|
||||
return games
|
||||
}
|
||||
|
||||
fun sessionListing(context: Context): File {
|
||||
val app = context.applicationContext
|
||||
val started = AddedGames.listed(app)?.map { it.appId }?.toSet()
|
||||
?: return AddedGames.writeListing(app, AddedGames.scan(app).also { log(it) })
|
||||
val session = SessionState.sessionId
|
||||
val work = Runnable {
|
||||
try {
|
||||
val began = SystemClock.elapsedRealtime()
|
||||
val games = serial { republish(app) }
|
||||
Log.i(TAG, "session refresh: ${games.size} game(s) in ${SystemClock.elapsedRealtime() - began} ms")
|
||||
log(games)
|
||||
val fresh = games.filter { (it.appId and 0xFFFFFFFFL) !in started }
|
||||
if (fresh.isNotEmpty()) deliver(app, session, fresh)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "session refresh: ${e.message}")
|
||||
}
|
||||
}
|
||||
if (now) work.run() else Thread(work, "added-games-refresh").apply { priority = Thread.MIN_PRIORITY }.start()
|
||||
return AddedGames.listingFile(app)
|
||||
}
|
||||
|
||||
internal fun log(games: List<AddedGames.Game>) {
|
||||
if (games.isNotEmpty()) Log.i(TAG, "added games: " + games.joinToString { "${it.name} (${it.exe.name})" })
|
||||
}
|
||||
|
||||
private fun deliver(app: Context, session: String?, games: List<AddedGames.Game>) {
|
||||
val until = SystemClock.uptimeMillis() + CLIENT_WAIT_MS
|
||||
while (current(session)) {
|
||||
val ready = SessionState.phase == SessionPhase.READY
|
||||
if (ready && serial { !current(session) || (SessionState.phase == SessionPhase.READY && syncUnremoved(app, games)) }) return
|
||||
if (now || SystemClock.uptimeMillis() >= until) return
|
||||
Thread.sleep(if (ready) RETRY_MS else POLL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
private fun current(session: String?): Boolean =
|
||||
SessionState.running && !SessionState.stopRequested && SessionState.sessionId == session
|
||||
|
||||
private fun syncUnremoved(app: Context, games: List<AddedGames.Game>): Boolean {
|
||||
val removed = SessionPrefs.removedAddedGames(app).toSet()
|
||||
return live(app, games) { it.folder.path !in removed }
|
||||
}
|
||||
|
||||
private fun <T> serial(block: () -> T): T = if (now) block() else worker.submit(Callable { block() }).get()
|
||||
}
|
||||
@@ -51,11 +51,12 @@ object GameExePicker {
|
||||
val entries = dir.listFiles()?.sortedBy { it.name.lowercase() } ?: continue
|
||||
for (f in entries) {
|
||||
if (visited >= WALK_BUDGET) break@walk
|
||||
if (isLink(f)) continue
|
||||
if (f.isDirectory) {
|
||||
val attrs = attributes(f) ?: continue
|
||||
if (attrs.isSymbolicLink) continue
|
||||
if (attrs.isDirectory) {
|
||||
visited++
|
||||
if (depth < MAX_DEPTH && !skipDir(f, f.relativeTo(folder).invariantSeparatorsPath)) next.add(f)
|
||||
} else if (f.isFile && f.name.endsWith(".exe", ignoreCase = true)) {
|
||||
} else if (attrs.isRegularFile && f.name.endsWith(".exe", ignoreCase = true)) {
|
||||
visited++
|
||||
if (!JUNK_EXE_RE.matches(f.nameWithoutExtension)) found.add(f to depth)
|
||||
}
|
||||
@@ -98,7 +99,9 @@ object GameExePicker {
|
||||
return SKIP_PATHS.any { rel == it || rel.endsWith("/$it") }
|
||||
}
|
||||
|
||||
private fun isLink(f: File): Boolean = runCatching { java.nio.file.Files.isSymbolicLink(f.toPath()) }.getOrDefault(false)
|
||||
private fun attributes(f: File): java.nio.file.attribute.BasicFileAttributes? = runCatching {
|
||||
java.nio.file.Files.readAttributes(f.toPath(), java.nio.file.attribute.BasicFileAttributes::class.java, java.nio.file.LinkOption.NOFOLLOW_LINKS)
|
||||
}.getOrNull()
|
||||
|
||||
private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
|
||||
}
|
||||
@@ -16,7 +16,7 @@ object DeviceInfo {
|
||||
val vk = VulkanInfo.query()
|
||||
val gpu = GpuInfo.detect()
|
||||
return listOf(
|
||||
chip(), gpu(context, gpu), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
|
||||
chip(), gpu(context, gpu), npu(context), cpu(), memory(context), system(), vulkan(context, vk), drivers(context, gpu),
|
||||
).filter { it.rows.isNotEmpty() }
|
||||
}
|
||||
|
||||
@@ -51,6 +51,10 @@ object DeviceInfo {
|
||||
add("Family", read("/sys/devices/soc0/family"))
|
||||
})
|
||||
|
||||
private fun npu(context: Context) = Section("NPU", NpuInfo.rows(
|
||||
NpuInfo.detect(context.applicationInfo.nativeLibraryDir?.let(::File)),
|
||||
))
|
||||
|
||||
private fun gpu(context: Context, gpu: GpuInfo) = Section("GPU", buildList<Pair<String, String>> {
|
||||
add("GPU", gpu.name)
|
||||
add("Family", gpu.family.label(gpu.name))
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import java.io.File
|
||||
|
||||
/** What this device's Qualcomm Hexagon NPU would offer a neural upscaler, and whether the app can reach it. */
|
||||
object NpuInfo {
|
||||
enum class Hexagon(val arch: String, val vtcmMb: Int) {
|
||||
V68("v68", 4), V69("v69", 4), V73("v73", 4), V75("v75", 8), V79("v79", 8), V81("v81", 8),
|
||||
}
|
||||
|
||||
enum class Access { OPEN, BROKERED, NO_NODE, DENIED }
|
||||
|
||||
data class Status(
|
||||
val hexagon: Hexagon?,
|
||||
val node: String?,
|
||||
val access: Access,
|
||||
val qnnRuntime: Boolean,
|
||||
) {
|
||||
val usable: Boolean get() = hexagon != null && (access == Access.OPEN || access == Access.BROKERED) && qnnRuntime
|
||||
}
|
||||
|
||||
private val BY_MODEL = mapOf(
|
||||
"SM8350" to Hexagon.V68, "SM8450" to Hexagon.V69, "SM8475" to Hexagon.V69,
|
||||
"SM8550" to Hexagon.V73, "QCS8550" to Hexagon.V73, "SM8650" to Hexagon.V75,
|
||||
"SM8750" to Hexagon.V79, "SM8850" to Hexagon.V81,
|
||||
)
|
||||
private val BY_PLATFORM = mapOf(
|
||||
"lahaina" to Hexagon.V68, "taro" to Hexagon.V69, "cape" to Hexagon.V69, "kalama" to Hexagon.V73,
|
||||
"pineapple" to Hexagon.V75, "sun" to Hexagon.V79, "canoe" to Hexagon.V81,
|
||||
)
|
||||
|
||||
// The compute DSP is the one that runs HTP graphs; /dev/adsprpc-smd is the pre-5.x name of the same service.
|
||||
internal val NODES = listOf("/dev/fastrpc-cdsp", "/dev/adsprpc-smd", "/dev/cdsprpc-smd")
|
||||
// Qualcomm's dspservice hands an app a FastRPC fd over binder when the node itself is closed to apps.
|
||||
internal const val DSP_SERVICE_MANIFEST = "/vendor/etc/vintf/manifest/vendor.qti.hardware.dsp-service.xml"
|
||||
internal val QNN_LIBS = listOf("libQnnHtp.so", "libQnnSystem.so")
|
||||
|
||||
fun hexagon(
|
||||
model: String = SocNames.model(),
|
||||
platform: String = GpuInfo.systemProperty("ro.board.platform"),
|
||||
): Hexagon? = BY_MODEL[SocNames.normalizedModel(model)] ?: BY_PLATFORM[platform.trim().lowercase()]
|
||||
|
||||
/** `canWrite` is access(2) for the app's own uid, so it answers for DAC but not SELinux. */
|
||||
internal fun access(nodes: List<File>, broker: File = File(DSP_SERVICE_MANIFEST)): Pair<File?, Access> {
|
||||
val present = nodes.firstOrNull { it.exists() } ?: return null to Access.NO_NODE
|
||||
val access = when {
|
||||
present.canRead() && present.canWrite() -> Access.OPEN
|
||||
broker.exists() -> Access.BROKERED
|
||||
else -> Access.DENIED
|
||||
}
|
||||
return present to access
|
||||
}
|
||||
|
||||
fun detect(nativeLibDir: File?, hexagon: Hexagon? = hexagon()): Status {
|
||||
val (node, access) = access(NODES.map(::File))
|
||||
val qnn = nativeLibDir != null && QNN_LIBS.all { File(nativeLibDir, it).exists() }
|
||||
return Status(hexagon, node?.path, access, qnn)
|
||||
}
|
||||
|
||||
fun rows(status: Status): List<Pair<String, String>> = buildList {
|
||||
add("Hexagon" to (status.hexagon?.let { "${it.arch} (${it.vtcmMb} MB VTCM)" } ?: "not recognised"))
|
||||
add("FastRPC node" to when (status.access) {
|
||||
Access.NO_NODE -> "none found"
|
||||
Access.OPEN -> "${status.node} (app can open it)"
|
||||
Access.BROKERED -> "${status.node} (closed to apps; the DSP service can hand over a descriptor)"
|
||||
Access.DENIED -> "${status.node} (app cannot open it)"
|
||||
})
|
||||
add("QNN runtime" to if (status.qnnRuntime) "bundled" else "not bundled")
|
||||
add("Neural upscaling" to if (status.usable) "possible" else "not available")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.view.MotionEvent
|
||||
import kotlin.math.abs
|
||||
|
||||
@@ -24,6 +25,7 @@ class DirectTouchHold(
|
||||
private var delayMs = 0L
|
||||
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK
|
||||
private var forwarded = false
|
||||
private var forwardedAt = 0L
|
||||
private var held = false
|
||||
private var pressing = false
|
||||
private var upX = 0f
|
||||
@@ -125,8 +127,11 @@ class DirectTouchHold(
|
||||
upX = event.x
|
||||
upY = event.y
|
||||
liftId = event.getPointerId(event.actionIndex)
|
||||
liftPending = true
|
||||
handler.postDelayed(lift, LIFT_MS)
|
||||
val wait = MIN_PRESS_MS - (SystemClock.uptimeMillis() - forwardedAt)
|
||||
if (wait > 0L) {
|
||||
liftPending = true
|
||||
handler.postDelayed(lift, wait)
|
||||
} else lift.run()
|
||||
}
|
||||
MotionEvent.ACTION_CANCEL -> cancel()
|
||||
}
|
||||
@@ -136,9 +141,10 @@ class DirectTouchHold(
|
||||
private fun forwardDown() {
|
||||
touch.down(downId, downX, downY)
|
||||
forwarded = true
|
||||
forwardedAt = SystemClock.uptimeMillis()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val LIFT_MS = 50L
|
||||
const val MIN_PRESS_MS = 50L
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,8 @@ public class FakeInputWriter {
|
||||
|
||||
private static native void nativeStoreFence();
|
||||
|
||||
private static native void nativeWake(ByteBuffer ring, int offset);
|
||||
|
||||
public static void storeFence() {
|
||||
nativeStoreFence();
|
||||
}
|
||||
@@ -455,6 +457,7 @@ public class FakeInputWriter {
|
||||
writeSnapshotLocked(ring);
|
||||
nativeStoreFence();
|
||||
ring.putLong(RING_WRITE_SEQ_OFFSET, writeSeq);
|
||||
nativeWake(ring, RING_WRITE_SEQ_OFFSET);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ object GameEnvironmentStore {
|
||||
private const val TAG = "GameEnvironmentStore"
|
||||
private const val SETTINGS = "game-environment.json"
|
||||
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
|
||||
private const val GAME_CORES_FILE = "root/.config/droiddeck/game-cores"
|
||||
const val DXVK_CONFIG = "dxvkConfig"
|
||||
const val DXVK_CONFIG_GAMES = "dxvkConfigGames"
|
||||
const val GAME_DEBUG_LOGS = "gameDebugLogs"
|
||||
@@ -108,10 +109,12 @@ object GameEnvironmentStore {
|
||||
@Synchronized
|
||||
fun publish(
|
||||
context: Context,
|
||||
config: GameEnvironment.Config = read(context),
|
||||
config: GameEnvironment.Config? = null,
|
||||
gameDebugLogsOverride: Boolean? = null,
|
||||
) {
|
||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
||||
publishGameCores(context)
|
||||
val stored = config ?: read(context)
|
||||
val resolved = stored.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
|
||||
val json = encode(resolved)
|
||||
val dxvk = TextureFiltering.dxvkOptions(
|
||||
SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context),
|
||||
@@ -140,6 +143,26 @@ object GameEnvironmentStore {
|
||||
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun publishGameCores(context: Context) {
|
||||
val file = File(LinuxRuntime.rootDir(context), GAME_CORES_FILE)
|
||||
val pending = File(file.path + ".new")
|
||||
try {
|
||||
check(file.parentFile!!.isDirectory || file.parentFile!!.mkdirs())
|
||||
java.io.FileOutputStream(pending).use {
|
||||
it.write((com.droiddeck.launcher.core.CpuCores.restrictionOrEmpty(SessionPrefs.gameCpus(context)) + "\n").toByteArray(Charsets.UTF_8))
|
||||
it.fd.sync()
|
||||
}
|
||||
java.nio.file.Files.move(
|
||||
pending.toPath(), file.toPath(),
|
||||
java.nio.file.StandardCopyOption.ATOMIC_MOVE, java.nio.file.StandardCopyOption.REPLACE_EXISTING,
|
||||
)
|
||||
} catch (error: Exception) {
|
||||
Log.e(TAG, "Could not update game cores", error)
|
||||
if (!file.delete() && file.exists()) Log.e(TAG, "Could not remove outdated game cores")
|
||||
}
|
||||
}
|
||||
|
||||
private fun write(file: File, text: String) {
|
||||
check(file.parentFile!!.isDirectory || file.parentFile!!.mkdirs())
|
||||
val atomic = AtomicFile(file)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
|
||||
/** Finds the processes a session left running, also once proot is gone and they belong to init. */
|
||||
object GuestLeftovers {
|
||||
private const val MARKER = "DD_DEBUG_DIR="
|
||||
|
||||
fun find(rootfs: String, ended: File?, skip: Set<Int>): Set<Int> {
|
||||
val marker = ended?.let { MARKER + it.path }
|
||||
val parents = HashMap<Int, Int>()
|
||||
val matched = HashSet<Int>()
|
||||
File("/proc").listFiles { f -> f.name.all { it.isDigit() } }?.forEach { proc ->
|
||||
val pid = proc.name.toIntOrNull() ?: return@forEach
|
||||
parentOf(proc)?.let { parents[pid] = it }
|
||||
if (pid in skip) return@forEach
|
||||
val exe = runCatching { File(proc, "exe").canonicalPath }.getOrNull()
|
||||
// proot runs a guest through its loader, which is then the process's executable
|
||||
if (exe?.startsWith(rootfs) == true ||
|
||||
marker != null && carries(runCatching { File(proc, "environ").readBytes() }.getOrNull(), marker)) {
|
||||
matched.add(pid)
|
||||
}
|
||||
}
|
||||
return withDescendants(matched, parents) - skip
|
||||
}
|
||||
|
||||
internal fun carries(environ: ByteArray?, marker: String): Boolean {
|
||||
if (environ == null) return false
|
||||
val wanted = marker.toByteArray()
|
||||
var start = 0
|
||||
while (start < environ.size) {
|
||||
var end = start
|
||||
while (end < environ.size && environ[end] != 0.toByte()) end++
|
||||
if (end - start == wanted.size && (0 until wanted.size).all { environ[start + it] == wanted[it] }) return true
|
||||
start = end + 1
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
internal fun withDescendants(roots: Set<Int>, parents: Map<Int, Int>): Set<Int> {
|
||||
val out = HashSet(roots)
|
||||
var grew = true
|
||||
while (grew) {
|
||||
grew = false
|
||||
for ((pid, ppid) in parents) if (pid > 1 && ppid in out && out.add(pid)) grew = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun parentOf(proc: File): Int? {
|
||||
val stat = runCatching { File(proc, "stat").readText() }.getOrNull() ?: return null
|
||||
return stat.substringAfterLast(") ").split(' ').getOrNull(1)?.toIntOrNull()
|
||||
}
|
||||
}
|
||||
@@ -1008,6 +1008,7 @@ object SessionPrefs {
|
||||
|
||||
fun setGameCpus(context: Context, list: String) {
|
||||
prefs(context).edit().putString("gameCpus", list).apply()
|
||||
GameEnvironmentStore.publishGameCores(context)
|
||||
}
|
||||
|
||||
fun noXalia(context: Context): Boolean = prefs(context).getBoolean("noXalia", true)
|
||||
@@ -1734,6 +1735,7 @@ object SessionPrefs {
|
||||
signal = p.getInt("customThemeSignal", defaults.signal),
|
||||
good = p.getInt("customThemeGood", defaults.good),
|
||||
error = p.getInt("customThemeError", defaults.error),
|
||||
warning = p.getInt("customThemeWarning", defaults.warning),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1754,6 +1756,7 @@ object SessionPrefs {
|
||||
.putInt("customThemeSignal", colors.signal)
|
||||
.putInt("customThemeGood", colors.good)
|
||||
.putInt("customThemeError", colors.error)
|
||||
.putInt("customThemeWarning", colors.warning)
|
||||
.apply()
|
||||
}
|
||||
|
||||
|
||||
@@ -693,12 +693,14 @@ class SessionService : Service() {
|
||||
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
|
||||
}
|
||||
if (steamHere || noSteamGame) {
|
||||
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
|
||||
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
|
||||
val listing = if (steamHere) SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGamesPublisher.sessionListing(this) } else {
|
||||
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
|
||||
com.droiddeck.launcher.frontend.AddedGamesPublisher.log(added)
|
||||
SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
|
||||
}
|
||||
guest.add("DD_ADDED_GAMES=" + listing.path)
|
||||
if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1")
|
||||
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
|
||||
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
|
||||
}
|
||||
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
|
||||
// Proton builds up to 11.12 report X11 text fields under this name.
|
||||
@@ -1886,21 +1888,11 @@ class SessionService : Service() {
|
||||
File(directory, STEAM_GAME_REQUEST + ".tmp").delete()
|
||||
}
|
||||
|
||||
private fun killGuestLeftovers() {
|
||||
val me = android.os.Process.myPid()
|
||||
private fun killGuestLeftovers(ended: File?) {
|
||||
val rootfs = try { File(filesDir, "linuxfs").canonicalPath } catch (e: Exception) { return } + "/"
|
||||
val procs = File("/proc").listFiles { f -> f.name.all { it.isDigit() } } ?: return
|
||||
val spared = OrphanReaper.spared()
|
||||
var killed = 0
|
||||
for (proc in procs) {
|
||||
val pid = proc.name.toIntOrNull() ?: continue
|
||||
if (pid == me || pid in spared) continue
|
||||
val exe = try { File(proc, "exe").canonicalPath } catch (e: Exception) { continue }
|
||||
if (!exe.startsWith(rootfs)) continue
|
||||
android.os.Process.killProcess(pid)
|
||||
killed++
|
||||
}
|
||||
if (killed > 0) Log.w(TAG, "killed $killed guest process(es) proot no longer tracked")
|
||||
val leftovers = GuestLeftovers.find(rootfs, ended, OrphanReaper.spared() + android.os.Process.myPid())
|
||||
leftovers.forEach { android.os.Process.killProcess(it) }
|
||||
if (leftovers.isNotEmpty()) Log.w(TAG, "killed ${leftovers.size} guest process(es) proot no longer tracked")
|
||||
}
|
||||
|
||||
private fun killStragglers() {
|
||||
@@ -2386,7 +2378,7 @@ class SessionService : Service() {
|
||||
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (prootPid > 1) teardown(prootPid)
|
||||
killGuestLeftovers()
|
||||
killGuestLeftovers(ended)
|
||||
pruneSystemVulkanRuntime()
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
if (launcherEnded) importLauncherGames()
|
||||
|
||||
@@ -19,25 +19,33 @@ object SteamLiveShortcuts {
|
||||
private const val EVAL_TIMEOUT_MS = 20_000L
|
||||
private const val THAW_WAIT_MS = 15_000L
|
||||
|
||||
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }) {
|
||||
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }): Boolean {
|
||||
val wanted = games.filter(include)
|
||||
if (wanted.isEmpty() || !clientRunning()) return
|
||||
if (wanted.isEmpty()) return true
|
||||
if (!clientRunning()) return false
|
||||
val list = JSONArray()
|
||||
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL).put("launch", g.launchOptions))
|
||||
val js = """
|
||||
(async () => {
|
||||
const want = ${list};
|
||||
let added = 0;
|
||||
let added = 0, missed = 0;
|
||||
for (const w of want) {
|
||||
if (await ${KNOWN}(w.appid, w.name, w.exe)) continue;
|
||||
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++;
|
||||
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++; else missed++;
|
||||
}
|
||||
return added;
|
||||
return JSON.stringify({ added, missed });
|
||||
})()
|
||||
""".trimIndent()
|
||||
val result = evaluate(context, js) ?: return
|
||||
Log.i(TAG, "live shortcuts: $result added")
|
||||
if (result != "0") StoresState.logLine("Steam: $result shortcut(s) added to the running client")
|
||||
return synced(evaluate(context, js))
|
||||
}
|
||||
|
||||
internal fun synced(result: String?): Boolean {
|
||||
val counts = result?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return false
|
||||
val added = counts.optInt("added")
|
||||
val missed = counts.optInt("missed")
|
||||
Log.i(TAG, "live shortcuts: $added added" + if (missed > 0) ", $missed not added" else "")
|
||||
if (added > 0) StoresState.logLine("Steam: $added shortcut(s) added to the running client")
|
||||
return missed == 0
|
||||
}
|
||||
|
||||
fun ensure(context: Context, name: String, exe: String, dir: String, compat: Boolean, appId: Long? = null): Long? {
|
||||
|
||||
@@ -122,10 +122,16 @@ object StoreInstalls {
|
||||
|
||||
fun discard(context: Context, folder: File, caches: List<File>) {
|
||||
val app = context.applicationContext
|
||||
inBackground(folder) { discardNow(app, folder, caches) }
|
||||
}
|
||||
|
||||
fun deleteLater(dir: File) = inBackground(dir) { deleteTree(dir) }
|
||||
|
||||
private fun inBackground(folder: File, work: () -> Unit) {
|
||||
beginDiscard(folder)
|
||||
val worker = Thread({
|
||||
try {
|
||||
discardNow(app, folder, caches)
|
||||
work()
|
||||
} finally {
|
||||
endDiscard(folder)
|
||||
}
|
||||
|
||||
@@ -318,7 +318,7 @@ object StoresState {
|
||||
val key = "${game.sidecar.store.id}:${game.sidecar.id}"
|
||||
uninstalling[key] = 0f
|
||||
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
|
||||
if (!com.droiddeck.launcher.stores.download.DownloadQueue.holdForRemovalWhenFree(key)) {
|
||||
if (!com.droiddeck.launcher.stores.download.DownloadQueue.stopForRemoval(app, key)) {
|
||||
logLine("kept \"${game.sidecar.title}\": its download or update is still running")
|
||||
main.post { uninstalling.remove(key); onDone() }
|
||||
return@background
|
||||
|
||||
@@ -9,6 +9,7 @@ import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object DownloadQueue {
|
||||
private const val TAG = "StoreDownloads"
|
||||
private const val REMOVAL_WAIT_MS = 30_000L
|
||||
|
||||
interface DownloadJob {
|
||||
fun run(handle: JobHandle): String?
|
||||
@@ -120,17 +121,24 @@ object DownloadQueue {
|
||||
|
||||
fun releaseRemoval(key: String) { synchronized(lock) { removing.remove(key); (lock as Object).notifyAll() } }
|
||||
|
||||
fun holdForRemovalWhenFree(key: String): Boolean = synchronized(lock) {
|
||||
while (true) {
|
||||
val item = items[key]
|
||||
if (item?.entry?.isActive == true || item?.job != null) return@synchronized false
|
||||
if (key !in cleaningUp && key !in removing) break
|
||||
(lock as Object).wait()
|
||||
fun stopForRemoval(context: Context, key: String): Boolean {
|
||||
if (synchronized(lock) { busyLocked(key) }) cancel(context, key)
|
||||
val deadline = android.os.SystemClock.uptimeMillis() + REMOVAL_WAIT_MS
|
||||
return synchronized(lock) {
|
||||
while (true) {
|
||||
val busy = busyLocked(key)
|
||||
if (!busy && key !in cleaningUp && key !in removing) break
|
||||
val left = deadline - android.os.SystemClock.uptimeMillis()
|
||||
if (busy && left <= 0) return@synchronized false
|
||||
(lock as Object).wait(if (busy) left else 0L)
|
||||
}
|
||||
removing.add(key)
|
||||
true
|
||||
}
|
||||
removing.add(key)
|
||||
true
|
||||
}
|
||||
|
||||
private fun busyLocked(key: String): Boolean = items[key].let { it?.entry?.isActive == true || it?.job != null }
|
||||
|
||||
private fun beginCleanup(key: String): Boolean = synchronized(lock) {
|
||||
if (key in removing) return@synchronized false
|
||||
cleaningUp.merge(key, 1, Int::plus)
|
||||
@@ -412,6 +420,7 @@ object DownloadQueue {
|
||||
}
|
||||
item.job = null
|
||||
publishLocked()
|
||||
(lock as Object).notifyAll()
|
||||
}
|
||||
when (item.entry.state) {
|
||||
DownloadState.INSTALLED -> {
|
||||
|
||||
@@ -73,35 +73,72 @@ object EaLaunch {
|
||||
/** Answers the guest's request right before an EA game starts: session, licence and the LSX endpoint. */
|
||||
fun prepare(context: Context, request: JSONObject): JSONObject {
|
||||
val app = context.applicationContext
|
||||
request.optJSONObject("steam")?.let { return prepareSteam(app, request, it) }
|
||||
val id = request.optString("id")
|
||||
val reply = JSONObject().put("ok", false)
|
||||
val (folder, recorded) = installed(app, id) ?: return reply.put("reason", "not-installed")
|
||||
val (folder, recorded) = installed(app, id) ?: return JSONObject().put("ok", false).put("reason", "not-installed")
|
||||
val sidecar = backfill(folder, recorded)
|
||||
runCatching { com.droiddeck.launcher.stores.StoreLaunch.refreshLauncher(folder, sidecar) }
|
||||
File(folder, ENV_FILE).delete()
|
||||
val account = EaAuth.load(app) ?: return reply.put("reason", "signed-out")
|
||||
val access = EaAuth.accessToken(app) ?: return reply.put("reason", "sign-in-expired")
|
||||
val contentId = sidecar.extra["contentId"].orEmpty()
|
||||
val locale = sidecar.extra["locale"].orEmpty().ifEmpty { "en_US" }
|
||||
val core = EaOoa.coreDir(folder, sidecar.exe)
|
||||
val known = (sidecar.extra["contentIds"].orEmpty().split(',') + sidecar.extra["multiplayerId"].orEmpty()).map { it.trim() }.filter { it.isNotEmpty() }.toSet()
|
||||
val game = Started(folder, id, sidecar.extra["contentId"].orEmpty(), known, sidecar.extra["contentIds"].orEmpty().split(','),
|
||||
sidecar.title, sidecar.installVersion, sidecar.extra["locale"].orEmpty().ifEmpty { "en_US" }, sidecar.exe)
|
||||
val (reply, env) = start(app, game, request)
|
||||
if (env != null) {
|
||||
val tmp = File(folder, "$ENV_FILE.tmp")
|
||||
tmp.writeText(env.entries.joinToString("\r\n", postfix = "\r\n") { "${it.key}=${it.value}" })
|
||||
tmp.renameTo(File(folder, ENV_FILE))
|
||||
}
|
||||
return reply
|
||||
}
|
||||
|
||||
private val OFFER = Regex("Origin\\.OFR\\.[0-9]+\\.[0-9]+")
|
||||
private val CONTENT = Regex("[A-Za-z0-9._-]{1,64}")
|
||||
|
||||
/** Steam's copy of an EA game, which Steam would hand to the EA app; the env comes back in the reply. */
|
||||
private fun prepareSteam(app: Context, request: JSONObject, steam: JSONObject): JSONObject {
|
||||
val failed = JSONObject().put("ok", false)
|
||||
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).canonicalFile
|
||||
val folder = File(root, steam.optString("folder").removePrefix("/")).canonicalFile
|
||||
if (!folder.path.startsWith(root.path + File.separator) || !folder.isDirectory) return failed.put("reason", "no-folder")
|
||||
fun strings(name: String, pattern: Regex) = steam.optJSONArray(name)?.let { a -> (0 until a.length()).map { a.optString(it) } }
|
||||
.orEmpty().filter { pattern.matches(it) }.distinct()
|
||||
val offers = strings("offers", OFFER)
|
||||
val contents = strings("contentIds", CONTENT)
|
||||
if (offers.isEmpty() || contents.isEmpty()) return failed.put("reason", "no-offer")
|
||||
val game = Started(folder, offers.first(), contents.first(), contents.toSet(), contents, steam.optString("title").ifEmpty { folder.name },
|
||||
steam.optString("version"), steam.optString("locale").ifEmpty { "en_US" }, steam.optString("exe"))
|
||||
val (reply, env) = start(app, game, request)
|
||||
if (env != null) reply.put("id", game.offerId).put("env", JSONObject(env.toMap()))
|
||||
return reply
|
||||
}
|
||||
|
||||
private class Started(
|
||||
val folder: File, val offerId: String, val contentId: String, val contentIds: Set<String>, val licenceIds: List<String>,
|
||||
val title: String, val version: String, val locale: String, val exe: String,
|
||||
)
|
||||
|
||||
private fun start(app: Context, game: Started, request: JSONObject): Pair<JSONObject, LinkedHashMap<String, String>?> {
|
||||
val reply = JSONObject().put("ok", false)
|
||||
val id = game.offerId
|
||||
val account = EaAuth.load(app) ?: return reply.put("reason", "signed-out") to null
|
||||
val access = EaAuth.accessToken(app) ?: return reply.put("reason", "sign-in-expired") to null
|
||||
val contentId = game.contentId
|
||||
val locale = game.locale
|
||||
val core = EaOoa.coreDir(game.folder, game.exe)
|
||||
val hashVersion = core?.let(EaOoa::activationVersion) ?: 1
|
||||
val hardware = request.optJSONObject("hardware")?.let(EaOoa.Hardware::fromJson)?.takeIf { it.complete(hashVersion) }
|
||||
val legacy = EaOoa.legacyCore(core)
|
||||
|
||||
val lifetime = if (legacy) 14400 else 550
|
||||
val opaque = EaAuth.mint(app, EaAuth.CLIENT_ID, "token", EaAuth.OPAQUE_SCOPES, "OPAQUE", lifetime).orEmpty()
|
||||
val known = (sidecar.extra["contentIds"].orEmpty().split(',') + sidecar.extra["multiplayerId"].orEmpty()).map { it.trim() }.filter { it.isNotEmpty() }.toSet()
|
||||
val lsx = EaLsx.start(app, EaLsx.Game(id, contentId, sidecar.title, sidecar.installVersion, locale, hardware, hashVersion, opaque,
|
||||
System.currentTimeMillis() + (lifetime - 30) * 1000L, known))
|
||||
val lsx = EaLsx.start(app, EaLsx.Game(id, contentId, game.title, game.version, locale, hardware, hashVersion, opaque,
|
||||
System.currentTimeMillis() + (lifetime - 30) * 1000L, game.contentIds))
|
||||
val env = environment(id, contentId, locale, if (legacy && opaque.isNotEmpty()) opaque else access, access, opaque, EaAuth.load(app) ?: account)
|
||||
val tmp = File(folder, "$ENV_FILE.tmp")
|
||||
tmp.writeText(env.entries.joinToString("\r\n", postfix = "\r\n") { "${it.key}=${it.value}" })
|
||||
tmp.renameTo(File(folder, ENV_FILE))
|
||||
|
||||
val licenses = JSONArray()
|
||||
val notes = ArrayList<String>()
|
||||
if (core != null) {
|
||||
val ids = (listOf(contentId) + sidecar.extra["contentIds"].orEmpty().split(',')).map { it.trim() }.filter { it.isNotEmpty() }.distinct()
|
||||
val ids = (listOf(contentId) + game.licenceIds).map { it.trim() }.filter { it.isNotEmpty() }.distinct()
|
||||
if (hardware == null) notes += "no-hardware" else {
|
||||
val hash = EaOoa.machineHash(hardware, hashVersion)
|
||||
for (content in ids) {
|
||||
@@ -125,7 +162,7 @@ object EaLaunch {
|
||||
}
|
||||
val licenseNote = if (core == null) "none-needed" else "v$hashVersion " + notes.joinToString(",")
|
||||
Log.i(TAG, "prepared $id lsx=$lsx legacy=$legacy opaque=${opaque.isNotEmpty()} licence=$licenseNote")
|
||||
return reply.put("ok", true).put("lsx", lsx).put("license", licenseNote).put("licenses", licenses)
|
||||
return reply.put("ok", true).put("lsx", lsx).put("license", licenseNote).put("licenses", licenses) to env
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
@@ -215,7 +216,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
val before = EpicClient.read(app)
|
||||
val needApp = !(before.version == launcher.version && File(state, "app/${launcher.version}/.droiddeck-ready").isFile)
|
||||
val needRuntime = !(before.runtimeVersion == runtime.version && File(state, "runtime/${runtime.version}/.droiddeck-ready").isFile)
|
||||
val dir = EpicClient.downloadsDir(app).apply { mkdirs() }
|
||||
val dir = EpicClient.downloadsDir(app).also { StoreInstalls.awaitDiscard(it) }.apply { mkdirs() }
|
||||
val gles = EpicClientSources.gles()
|
||||
val appPart = if (needApp) Part(listOf(launcher.url), File(dir, "${launcher.version}-${EpicClientSources.LAUNCHER_FILE}"), null, true) else null
|
||||
val desktopParts = if (needApp) EpicClientSources.DESKTOP.map { Part(it.urls, File(dir, it.file), it.sha256, false, it.size) } else emptyList()
|
||||
@@ -265,7 +266,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
runCatching { connection?.disconnect() }
|
||||
if (deleteFiles) EpicClient.downloadsDir(app).deleteRecursively()
|
||||
if (deleteFiles) StoreInstalls.deleteLater(EpicClient.downloadsDir(app))
|
||||
}
|
||||
|
||||
private fun length(url: String): Long {
|
||||
|
||||
@@ -282,7 +282,7 @@ internal object SteamStore {
|
||||
if (key in StoresState.uninstalling) return
|
||||
StoresState.uninstalling[key] = 0f
|
||||
Thread({
|
||||
if (!DownloadQueue.holdForRemovalWhenFree(key)) {
|
||||
if (!DownloadQueue.stopForRemoval(app, key)) {
|
||||
StoresState.logLine("Steam: kept $appId, its download is still running")
|
||||
StoresState.post { StoresState.uninstalling.remove(key); onDone() }
|
||||
return@Thread
|
||||
|
||||
@@ -137,7 +137,7 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
|
||||
delete = deleteFiles
|
||||
val process = child
|
||||
if (process == null) {
|
||||
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteTree(folder)
|
||||
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteLater(folder)
|
||||
else if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.withFrameMillis
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
@@ -99,7 +99,7 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
var vx = speed * 0.8f
|
||||
var vy = -speed * 0.6f
|
||||
while (true) {
|
||||
if (clock.page == Size.Zero) { withFrameMillis { }; continue }
|
||||
if (clock.page == Size.Zero) { withFrameNanos { }; continue }
|
||||
val f = MarkFrame(clock.page, Offset.Zero)
|
||||
if (clock.at == Offset.Unspecified) clock.at = Offset(clock.page.width * 0.64f, clock.page.height * 0.42f)
|
||||
if (Motion.scale == 0f) {
|
||||
@@ -108,8 +108,13 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
clock.wall = 0f
|
||||
return@LaunchedEffect
|
||||
}
|
||||
withFrameMillis { now ->
|
||||
val dt = if (last < 0) 0f else min(50f, (now - last) / Motion.scale)
|
||||
withFrameNanos { nanos ->
|
||||
val scale = Motion.scale
|
||||
if (scale == 0f) return@withFrameNanos
|
||||
val settled = clock.intro >= END && clock.ball >= IMPACT + REVEAL_MS && !clock.poked
|
||||
if (settled && last >= 0 && !IdleFrames.due(nanos)) return@withFrameNanos
|
||||
val now = nanos / 1_000_000L
|
||||
val dt = if (last < 0) 0f else min(50f, (now - last).toFloat()) / scale.coerceAtLeast(0.01f)
|
||||
last = now
|
||||
clock.intro += dt
|
||||
clock.wall += dt
|
||||
@@ -117,34 +122,41 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
val before = clock.ball
|
||||
clock.ball += dt
|
||||
|
||||
var x = clock.at.x + vx * dt / 1000f
|
||||
var y = clock.at.y + vy * dt / 1000f
|
||||
var x = clock.at.x
|
||||
var y = clock.at.y
|
||||
val hw = f.ball
|
||||
val hh = f.ball
|
||||
if (x - hw < 0f) { x = hw; vx = abs(vx) }
|
||||
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
|
||||
if (y - hh < 0f) { y = hh; vy = abs(vy) }
|
||||
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
|
||||
keepOff?.inflate(clearance)?.let { r ->
|
||||
val nearX = x.coerceIn(r.left, r.right)
|
||||
val nearY = y.coerceIn(r.top, r.bottom)
|
||||
val gapX = x - nearX
|
||||
val gapY = y - nearY
|
||||
val gap = hypot(gapX, gapY)
|
||||
if (gap in 0.0001f..f.ball) {
|
||||
val nx = gapX / gap
|
||||
val ny = gapY / gap
|
||||
x = nearX + nx * f.ball
|
||||
y = nearY + ny * f.ball
|
||||
val into = vx * nx + vy * ny
|
||||
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
|
||||
} else if (gap <= 0.0001f) {
|
||||
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
|
||||
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
|
||||
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
|
||||
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
|
||||
var left = dt
|
||||
do {
|
||||
val step = min(50f, left)
|
||||
left -= step
|
||||
x += vx * step / 1000f
|
||||
y += vy * step / 1000f
|
||||
if (x - hw < 0f) { x = hw; vx = abs(vx) }
|
||||
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) }
|
||||
if (y - hh < 0f) { y = hh; vy = abs(vy) }
|
||||
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) }
|
||||
keepOff?.inflate(clearance)?.let { r ->
|
||||
val nearX = x.coerceIn(r.left, r.right)
|
||||
val nearY = y.coerceIn(r.top, r.bottom)
|
||||
val gapX = x - nearX
|
||||
val gapY = y - nearY
|
||||
val gap = hypot(gapX, gapY)
|
||||
if (gap in 0.0001f..f.ball) {
|
||||
val nx = gapX / gap
|
||||
val ny = gapY / gap
|
||||
x = nearX + nx * f.ball
|
||||
y = nearY + ny * f.ball
|
||||
val into = vx * nx + vy * ny
|
||||
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
|
||||
} else if (gap <= 0.0001f) {
|
||||
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
|
||||
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
|
||||
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
|
||||
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
|
||||
}
|
||||
}
|
||||
}
|
||||
} while (left > 0f)
|
||||
clock.at = Offset(x, y)
|
||||
|
||||
if (before < IMPACT && clock.ball >= IMPACT) {
|
||||
|
||||
@@ -96,8 +96,7 @@ import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onPlaced
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
|
||||
|
||||
internal val AttentionAmber = Color(0xFFFFB547)
|
||||
internal val AttentionAmber: Color @Composable get() = LocalPalette.current.warning
|
||||
|
||||
@Composable
|
||||
internal fun BottomBar(
|
||||
@@ -308,7 +307,7 @@ private fun RailItem(
|
||||
}
|
||||
if (badge) Box(
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(top = if (iconOnly) 7.dp else 8.dp, end = if (iconOnly) 9.dp else 18.dp)
|
||||
.size(8.dp).clip(CircleShape).background(AttentionAmber),
|
||||
.size(8.dp).clip(CircleShape).background(pal.warning),
|
||||
)
|
||||
if (count > 0) Text(
|
||||
if (count > 9) "9+" else count.toString(),
|
||||
|
||||
@@ -1254,6 +1254,7 @@ private fun CustomColorRows() {
|
||||
Triple("signal", stringResource(R.string.theme_custom_signal), colors.signal),
|
||||
Triple("good", stringResource(R.string.theme_custom_good), colors.good),
|
||||
Triple("error", stringResource(R.string.theme_custom_error), colors.error),
|
||||
Triple("warning", stringResource(R.string.theme_custom_warning), colors.warning),
|
||||
)
|
||||
|
||||
rows.forEach { (key, label, argb) ->
|
||||
|
||||
@@ -82,7 +82,18 @@ import kotlinx.coroutines.withContext
|
||||
private const val WALL_MIN_GAMES = 4
|
||||
private const val WALL_DISTINCT = 40
|
||||
|
||||
private const val DRIFT_STEP_NS = 15_000_000L
|
||||
private const val IDLE_FRAME_NS = 30_000_000L
|
||||
|
||||
internal object IdleFrames {
|
||||
private var shown = 0L
|
||||
|
||||
fun due(nanos: Long): Boolean {
|
||||
if (nanos == shown) return true
|
||||
if (nanos - shown < IDLE_FRAME_NS) return false
|
||||
shown = nanos
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
|
||||
@@ -281,7 +292,7 @@ internal fun TiltedWall(
|
||||
var shown = 0L
|
||||
while (true) withFrameNanos { now ->
|
||||
if (shown == 0L) shown = now
|
||||
else if (now - shown >= DRIFT_STEP_NS) {
|
||||
else if (IdleFrames.due(now)) {
|
||||
drift.floatValue = ((drift.floatValue + (now - shown) / (period.value * 1_000_000.0 * Motion.scale)) % 1.0).toFloat()
|
||||
shown = now
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ class Palette(
|
||||
val background: Color, val surface: Color, val surfaceVariant: Color, val line: Color, val line2: Color,
|
||||
val onBackground: Color, val onSurfaceVariant: Color,
|
||||
val primary: Color, val primary2: Color, val onPrimary: Color, val signal: Color,
|
||||
val good: Color, val error: Color = Color(0xFFFF8A80),
|
||||
val good: Color, val error: Color = Color(0xFFFF8A80), val warning: Color = Color(0xFFFFB547),
|
||||
)
|
||||
|
||||
data class CustomThemeColors(
|
||||
@@ -54,6 +54,7 @@ data class CustomThemeColors(
|
||||
val signal: Int = 0xFF1A9FFF.toInt(),
|
||||
val good: Int = 0xFF4CD37F.toInt(),
|
||||
val error: Int = 0xFFFF8A80.toInt(),
|
||||
val warning: Int = 0xFFFFB547.toInt(),
|
||||
)
|
||||
|
||||
object Themes {
|
||||
@@ -144,6 +145,7 @@ object Themes {
|
||||
"signal" -> current.copy(signal = color)
|
||||
"good" -> current.copy(good = color)
|
||||
"error" -> current.copy(error = color)
|
||||
"warning" -> current.copy(warning = color)
|
||||
else -> return
|
||||
}
|
||||
setCustomColors(context, updated)
|
||||
@@ -164,6 +166,7 @@ object Themes {
|
||||
signal = Color(colors.signal),
|
||||
good = Color(colors.good),
|
||||
error = Color(colors.error),
|
||||
warning = Color(colors.warning),
|
||||
)
|
||||
|
||||
fun current(context: Context): Palette {
|
||||
@@ -229,7 +232,9 @@ val Palette.onSignal: Color get() = if (signal.luminance() > 0.18f) Color(0xFF03
|
||||
|
||||
@Composable
|
||||
fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, content: @Composable () -> Unit) {
|
||||
val id = theme ?: SessionPrefs.theme(LocalContext.current)
|
||||
val context = LocalContext.current
|
||||
remember(context) { Themes.loadGradient(context) }
|
||||
val id = theme ?: SessionPrefs.theme(context)
|
||||
if (id == Themes.INNER_GAMER) InnerGamerHue(Themes.rgbSpeed)
|
||||
val p = Themes.byId(id)
|
||||
val scheme = darkColorScheme(
|
||||
|
||||
@@ -4299,6 +4299,7 @@
|
||||
<string name="theme_custom_signal">الإبرازات</string>
|
||||
<string name="theme_custom_good">نجاح</string>
|
||||
<string name="theme_custom_error">خطأ</string>
|
||||
<string name="theme_custom_warning">تحذير</string>
|
||||
<string name="hud_only_during_game">عرض HUD أثناء اللعب فقط</string>
|
||||
<string name="hud_only_during_game_hint">إخفاء HUD عند عدم اكتشاف إطارات اللعبة.</string>
|
||||
<string name="steam_store_close_steam">أغلق Steam أولاً</string>
|
||||
|
||||
@@ -4179,6 +4179,7 @@
|
||||
<string name="theme_custom_signal">Destacados</string>
|
||||
<string name="theme_custom_good">Éxito</string>
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="theme_custom_warning">Advertencia</string>
|
||||
<string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string>
|
||||
<string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string>
|
||||
<string name="steam_store_close_steam">Cierra Steam primero</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Акценти</string>
|
||||
<string name="theme_custom_good">Успех</string>
|
||||
<string name="theme_custom_error">Грешка</string>
|
||||
<string name="theme_custom_warning">Предупреждение</string>
|
||||
<string name="hud_only_during_game">Показвай HUD само по време на игра</string>
|
||||
<string name="hud_only_during_game_hint">Скривай HUD, когато не се засичат кадри от играта.</string>
|
||||
<string name="steam_store_close_steam">Първо затворете Steam</string>
|
||||
|
||||
@@ -4219,6 +4219,7 @@
|
||||
<string name="theme_custom_signal">Zvýraznění</string>
|
||||
<string name="theme_custom_good">Úspěch</string>
|
||||
<string name="theme_custom_error">Chyba</string>
|
||||
<string name="theme_custom_warning">Varování</string>
|
||||
<string name="hud_only_during_game">Zobrazovat HUD pouze během hry</string>
|
||||
<string name="hud_only_during_game_hint">Skrýt HUD, když nejsou detekovány snímky hry.</string>
|
||||
<string name="steam_store_close_steam">Nejprve zavřete Steam</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Fremhævninger</string>
|
||||
<string name="theme_custom_good">Succes</string>
|
||||
<string name="theme_custom_error">Fejl</string>
|
||||
<string name="theme_custom_warning">Advarsel</string>
|
||||
<string name="hud_only_during_game">Vis kun HUD under spil</string>
|
||||
<string name="hud_only_during_game_hint">Skjul HUD, når der ikke registreres spilbilleder.</string>
|
||||
<string name="steam_store_close_steam">Luk Steam først</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Hervorhebungen</string>
|
||||
<string name="theme_custom_good">Erfolg</string>
|
||||
<string name="theme_custom_error">Fehler</string>
|
||||
<string name="theme_custom_warning">Warnung</string>
|
||||
<string name="hud_only_during_game">HUD nur während eines Spiels anzeigen</string>
|
||||
<string name="hud_only_during_game_hint">HUD ausblenden, wenn keine Spielframes erkannt werden.</string>
|
||||
<string name="steam_store_close_steam">Schließe zuerst Steam</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Επισημάνσεις</string>
|
||||
<string name="theme_custom_good">Επιτυχία</string>
|
||||
<string name="theme_custom_error">Σφάλμα</string>
|
||||
<string name="theme_custom_warning">Προειδοποίηση</string>
|
||||
<string name="hud_only_during_game">Εμφάνιση HUD μόνο κατά τη διάρκεια παιχνιδιού</string>
|
||||
<string name="hud_only_during_game_hint">Απόκρυψη HUD όταν δεν ανιχνεύονται καρέ παιχνιδιού.</string>
|
||||
<string name="steam_store_close_steam">Κλείστε πρώτα το Steam</string>
|
||||
|
||||
@@ -4179,6 +4179,7 @@
|
||||
<string name="theme_custom_signal">Destacados</string>
|
||||
<string name="theme_custom_good">Éxito</string>
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="theme_custom_warning">Advertencia</string>
|
||||
<string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string>
|
||||
<string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string>
|
||||
<string name="steam_store_close_steam">Cierra Steam primero</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Korostukset</string>
|
||||
<string name="theme_custom_good">Onnistuminen</string>
|
||||
<string name="theme_custom_error">Virhe</string>
|
||||
<string name="theme_custom_warning">Varoitus</string>
|
||||
<string name="hud_only_during_game">Näytä HUD vain pelin aikana</string>
|
||||
<string name="hud_only_during_game_hint">Piilota HUD, kun pelin ruutuja ei havaita.</string>
|
||||
<string name="steam_store_close_steam">Sulje Steam ensin</string>
|
||||
|
||||
@@ -4178,6 +4178,7 @@
|
||||
<string name="theme_custom_signal">Mises en évidence</string>
|
||||
<string name="theme_custom_good">Succès</string>
|
||||
<string name="theme_custom_error">Erreur</string>
|
||||
<string name="theme_custom_warning">Avertissement</string>
|
||||
<string name="hud_only_during_game">Afficher le HUD uniquement pendant une partie</string>
|
||||
<string name="hud_only_during_game_hint">Masquer le HUD lorsqu’aucune image du jeu n’est détectée.</string>
|
||||
<string name="steam_store_close_steam">Fermez d\'abord Steam</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">हाइलाइट</string>
|
||||
<string name="theme_custom_good">सफलता</string>
|
||||
<string name="theme_custom_error">त्रुटि</string>
|
||||
<string name="theme_custom_warning">चेतावनी</string>
|
||||
<string name="hud_only_during_game">HUD केवल गेम के दौरान दिखाएँ</string>
|
||||
<string name="hud_only_during_game_hint">गेम के फ़्रेम का पता न चलने पर HUD छिपाएँ।</string>
|
||||
<string name="steam_store_close_steam">पहले Steam बंद करें</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Kiemelések</string>
|
||||
<string name="theme_custom_good">Siker</string>
|
||||
<string name="theme_custom_error">Hiba</string>
|
||||
<string name="theme_custom_warning">Figyelmeztetés</string>
|
||||
<string name="hud_only_during_game">HUD megjelenítése csak játék közben</string>
|
||||
<string name="hud_only_during_game_hint">HUD elrejtése, ha nem észlelhetők játék képkockái.</string>
|
||||
<string name="steam_store_close_steam">Előbb zárd be a Steamet</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">Sorotan</string>
|
||||
<string name="theme_custom_good">Berhasil</string>
|
||||
<string name="theme_custom_error">Kesalahan</string>
|
||||
<string name="theme_custom_warning">Peringatan</string>
|
||||
<string name="hud_only_during_game">Tampilkan HUD hanya saat bermain</string>
|
||||
<string name="hud_only_during_game_hint">Sembunyikan HUD saat tidak ada frame game yang terdeteksi.</string>
|
||||
<string name="steam_store_close_steam">Tutup Steam terlebih dahulu</string>
|
||||
|
||||
@@ -4178,6 +4178,7 @@
|
||||
<string name="theme_custom_signal">Evidenziazioni</string>
|
||||
<string name="theme_custom_good">Successo</string>
|
||||
<string name="theme_custom_error">Errore</string>
|
||||
<string name="theme_custom_warning">Avviso</string>
|
||||
<string name="hud_only_during_game">Mostra l’HUD solo durante il gioco</string>
|
||||
<string name="hud_only_during_game_hint">Nascondi l’HUD quando non vengono rilevati fotogrammi del gioco.</string>
|
||||
<string name="steam_store_close_steam">Chiudi prima Steam</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">強調表示</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">エラー</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">ゲーム中のみHUDを表示</string>
|
||||
<string name="hud_only_during_game_hint">ゲームのフレームが検出されないときはHUDを非表示にする。</string>
|
||||
<string name="steam_store_close_steam">先に Steam を閉じてください</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">강조 표시</string>
|
||||
<string name="theme_custom_good">성공</string>
|
||||
<string name="theme_custom_error">오류</string>
|
||||
<string name="theme_custom_warning">경고</string>
|
||||
<string name="hud_only_during_game">게임 중에만 HUD 표시</string>
|
||||
<string name="hud_only_during_game_hint">게임 프레임이 감지되지 않으면 HUD 숨기기.</string>
|
||||
<string name="steam_store_close_steam">먼저 Steam을 닫으세요</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">Sorotan</string>
|
||||
<string name="theme_custom_good">Berjaya</string>
|
||||
<string name="theme_custom_error">Ralat</string>
|
||||
<string name="theme_custom_warning">Amaran</string>
|
||||
<string name="hud_only_during_game">Paparkan HUD hanya semasa bermain</string>
|
||||
<string name="hud_only_during_game_hint">Sembunyikan HUD apabila bingkai permainan tidak dikesan.</string>
|
||||
<string name="steam_store_close_steam">Tutup Steam dahulu</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Uthevinger</string>
|
||||
<string name="theme_custom_good">Suksess</string>
|
||||
<string name="theme_custom_error">Feil</string>
|
||||
<string name="theme_custom_warning">Advarsel</string>
|
||||
<string name="hud_only_during_game">Vis HUD bare mens du spiller</string>
|
||||
<string name="hud_only_during_game_hint">Skjul HUD når ingen spillbilder registreres.</string>
|
||||
<string name="steam_store_close_steam">Lukk Steam først</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Accenten</string>
|
||||
<string name="theme_custom_good">Geslaagd</string>
|
||||
<string name="theme_custom_error">Fout</string>
|
||||
<string name="theme_custom_warning">Waarschuwing</string>
|
||||
<string name="hud_only_during_game">HUD alleen tijdens een game weergeven</string>
|
||||
<string name="hud_only_during_game_hint">Verberg de HUD wanneer er geen gameframes worden gedetecteerd.</string>
|
||||
<string name="steam_store_close_steam">Sluit eerst Steam</string>
|
||||
|
||||
@@ -4219,6 +4219,7 @@
|
||||
<string name="theme_custom_signal">Wyróżnienia</string>
|
||||
<string name="theme_custom_good">Sukces</string>
|
||||
<string name="theme_custom_error">Błąd</string>
|
||||
<string name="theme_custom_warning">Ostrzeżenie</string>
|
||||
<string name="hud_only_during_game">Pokazuj HUD tylko podczas gry</string>
|
||||
<string name="hud_only_during_game_hint">Ukryj HUD, gdy nie wykryto klatek gry.</string>
|
||||
<string name="steam_store_close_steam">Najpierw zamknij Steam</string>
|
||||
|
||||
@@ -1812,6 +1812,7 @@
|
||||
<string name="theme_custom_signal">Destaques e indicadores</string>
|
||||
<string name="theme_custom_good">Sucesso</string>
|
||||
<string name="theme_custom_error">Erro</string>
|
||||
<string name="theme_custom_warning">Aviso</string>
|
||||
<string name="pckb_key_esc">Esc</string>
|
||||
<string name="pckb_key_ins">Ins</string>
|
||||
<string name="pckb_key_del">Del</string>
|
||||
|
||||
@@ -1820,6 +1820,7 @@
|
||||
<string name="theme_custom_signal">Destaques e indicadores</string>
|
||||
<string name="theme_custom_good">Sucesso</string>
|
||||
<string name="theme_custom_error">Erro</string>
|
||||
<string name="theme_custom_warning">Aviso</string>
|
||||
<string name="pckb_key_esc">Esc</string>
|
||||
<string name="pckb_key_ins">Ins</string>
|
||||
<string name="pckb_key_del">Del</string>
|
||||
|
||||
@@ -4179,6 +4179,7 @@
|
||||
<string name="theme_custom_signal">Evidențieri</string>
|
||||
<string name="theme_custom_good">Succes</string>
|
||||
<string name="theme_custom_error">Eroare</string>
|
||||
<string name="theme_custom_warning">Avertisment</string>
|
||||
<string name="hud_only_during_game">Afișează HUD-ul doar în timpul jocului</string>
|
||||
<string name="hud_only_during_game_hint">Ascunde HUD-ul când nu sunt detectate cadre ale jocului.</string>
|
||||
<string name="steam_store_close_steam">Închide mai întâi Steam</string>
|
||||
|
||||
@@ -4220,6 +4220,7 @@
|
||||
<string name="theme_custom_signal">Выделения</string>
|
||||
<string name="theme_custom_good">Успех</string>
|
||||
<string name="theme_custom_error">Ошибка</string>
|
||||
<string name="theme_custom_warning">Предупреждение</string>
|
||||
<string name="hud_only_during_game">Показывать HUD только во время игры</string>
|
||||
<string name="hud_only_during_game_hint">Скрывать HUD, когда кадры игры не обнаруживаются.</string>
|
||||
<string name="steam_store_close_steam">Сначала закройте Steam</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Markeringar</string>
|
||||
<string name="theme_custom_good">Lyckades</string>
|
||||
<string name="theme_custom_error">Fel</string>
|
||||
<string name="theme_custom_warning">Varning</string>
|
||||
<string name="hud_only_during_game">Visa HUD endast under spel</string>
|
||||
<string name="hud_only_during_game_hint">Dölj HUD när inga spelbildrutor upptäcks.</string>
|
||||
<string name="steam_store_close_steam">Stäng Steam först</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">จุดเน้น</string>
|
||||
<string name="theme_custom_good">สำเร็จ</string>
|
||||
<string name="theme_custom_error">ข้อผิดพลาด</string>
|
||||
<string name="theme_custom_warning">คำเตือน</string>
|
||||
<string name="hud_only_during_game">แสดง HUD เฉพาะขณะเล่นเกม</string>
|
||||
<string name="hud_only_during_game_hint">ซ่อน HUD เมื่อไม่พบเฟรมของเกม</string>
|
||||
<string name="steam_store_close_steam">ปิด Steam ก่อน</string>
|
||||
|
||||
@@ -4139,6 +4139,7 @@
|
||||
<string name="theme_custom_signal">Vurgular</string>
|
||||
<string name="theme_custom_good">Başarılı</string>
|
||||
<string name="theme_custom_error">Hata</string>
|
||||
<string name="theme_custom_warning">Uyarı</string>
|
||||
<string name="hud_only_during_game">HUD\'yi yalnızca oyun sırasında göster</string>
|
||||
<string name="hud_only_during_game_hint">Oyun kareleri algılanmadığında HUD\'yi gizle.</string>
|
||||
<string name="steam_store_close_steam">Önce Steam\'i kapatın</string>
|
||||
|
||||
@@ -4219,6 +4219,7 @@
|
||||
<string name="theme_custom_signal">Виділення</string>
|
||||
<string name="theme_custom_good">Успіх</string>
|
||||
<string name="theme_custom_error">Помилка</string>
|
||||
<string name="theme_custom_warning">Попередження</string>
|
||||
<string name="hud_only_during_game">Показувати HUD лише під час гри</string>
|
||||
<string name="hud_only_during_game_hint">Приховувати HUD, коли кадри гри не виявляються.</string>
|
||||
<string name="steam_store_close_steam">Спочатку закрийте Steam</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">Điểm nhấn</string>
|
||||
<string name="theme_custom_good">Thành công</string>
|
||||
<string name="theme_custom_error">Lỗi</string>
|
||||
<string name="theme_custom_warning">Cảnh báo</string>
|
||||
<string name="hud_only_during_game">Chỉ hiển thị HUD khi đang chơi</string>
|
||||
<string name="hud_only_during_game_hint">Ẩn HUD khi không phát hiện khung hình trò chơi.</string>
|
||||
<string name="steam_store_close_steam">Hãy đóng Steam trước</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">高亮</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">错误</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">仅在游戏期间显示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未检测到游戏帧时隐藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">请先关闭 Steam</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">重點標示</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">錯誤</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">只在遊戲期間顯示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">請先關閉 Steam</string>
|
||||
|
||||
@@ -4109,6 +4109,7 @@
|
||||
<string name="theme_custom_signal">醒目標示</string>
|
||||
<string name="theme_custom_good">成功</string>
|
||||
<string name="theme_custom_error">錯誤</string>
|
||||
<string name="theme_custom_warning">警告</string>
|
||||
<string name="hud_only_during_game">僅在遊戲期間顯示 HUD</string>
|
||||
<string name="hud_only_during_game_hint">未偵測到遊戲畫面時隱藏 HUD。</string>
|
||||
<string name="steam_store_close_steam">請先關閉 Steam</string>
|
||||
|
||||
@@ -2028,6 +2028,7 @@
|
||||
<string name="theme_custom_signal">Highlights</string>
|
||||
<string name="theme_custom_good">Success</string>
|
||||
<string name="theme_custom_error">Error</string>
|
||||
<string name="theme_custom_warning">Warning</string>
|
||||
<string name="pckb_key_esc">Esc</string>
|
||||
<string name="pckb_key_ins">Ins</string>
|
||||
<string name="pckb_key_del">Del</string>
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
use std::os::unix::fs::FileExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::Mutex;
|
||||
@@ -18,6 +17,7 @@ use super::net;
|
||||
use super::zip::{self, Entry};
|
||||
use crate::amazon::install::check::{free_bytes, space_problem};
|
||||
use crate::amazon::install::{Events, ReplaceGate, Stop};
|
||||
use crate::grow_write::{holes_supported, is_cancel, GrowFront};
|
||||
use crate::fetch_core::{distinct_host_count, run_fetch, FetchItem, FetchOptions, FetchSink, SinkError};
|
||||
|
||||
pub const LEDGER: &str = ".droiddeck-ea-files";
|
||||
@@ -37,6 +37,7 @@ struct Split {
|
||||
file: Mutex<Option<File>>,
|
||||
received: Vec<AtomicU64>,
|
||||
left: AtomicUsize,
|
||||
front: GrowFront,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -483,9 +484,16 @@ impl Placer<'_> {
|
||||
let old = split.received[part].swap(0, Ordering::Relaxed);
|
||||
self.in_flight.fetch_sub(old, Ordering::Relaxed);
|
||||
}
|
||||
handle
|
||||
.write_all_at(data, start + offset)
|
||||
.map_err(|e| SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path))))?;
|
||||
split
|
||||
.front
|
||||
.write_all_at(handle, start + offset, data, self.stop)
|
||||
.map_err(|e| {
|
||||
if is_cancel(&e) {
|
||||
SinkError::Retry(format!("{}: cancelled", job.path))
|
||||
} else {
|
||||
SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path)))
|
||||
}
|
||||
})?;
|
||||
drop(file);
|
||||
split.received[part].fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
self.in_flight.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
@@ -698,6 +706,7 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
|
||||
let host = origin(&req.url);
|
||||
let works = works(&remote, req.part_bytes);
|
||||
let holes = holes_supported(&req.game_dir);
|
||||
let splits: Vec<Option<Split>> = remote
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -711,6 +720,7 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
file: Mutex::new(None),
|
||||
received: (0..parts).map(|_| AtomicU64::new(0)).collect(),
|
||||
left: AtomicUsize::new(parts),
|
||||
front: GrowFront::new(holes),
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -797,13 +807,13 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
|
||||
return Err(Stop::Failed(message));
|
||||
}
|
||||
if !placed_all {
|
||||
if cancel.load(Ordering::SeqCst) {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
if let Some(error) = outcome.as_ref().and_then(|o| o.error.clone()) {
|
||||
ev.log(&format!("download failed: {error}"));
|
||||
return Err(Stop::Failed("A file failed to download".into()));
|
||||
}
|
||||
if cancel.load(Ordering::SeqCst) {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
return Err(Stop::Failed("The download ended before every file was written".into()));
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,14 @@ fn rejects_third_party_managed_install_before_manifest_parsing() {
|
||||
}
|
||||
}
|
||||
|
||||
fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>) -> String {
|
||||
#[derive(Default)]
|
||||
struct Misses {
|
||||
seen: AtomicUsize,
|
||||
cancel_at: usize,
|
||||
cancel: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>, misses: Arc<Misses>) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let files = Arc::new(files);
|
||||
@@ -30,13 +37,14 @@ fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>) -> String {
|
||||
let Ok(stream) = stream else { continue };
|
||||
let files = Arc::clone(&files);
|
||||
let hits = Arc::clone(&hits);
|
||||
std::thread::spawn(move || answer(stream, &files, &hits));
|
||||
let misses = Arc::clone(&misses);
|
||||
std::thread::spawn(move || answer(stream, &files, &hits, &misses));
|
||||
}
|
||||
});
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &AtomicUsize) {
|
||||
fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &AtomicUsize, misses: &Misses) {
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut first = String::new();
|
||||
if reader.read_line(&mut first).is_err() {
|
||||
@@ -54,7 +62,13 @@ fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &Atomic
|
||||
hits.fetch_add(1, Ordering::Relaxed);
|
||||
let (status, body) = match files.get(&path) {
|
||||
Some(b) => ("200 OK", b.clone()),
|
||||
None => ("404 Not Found", Vec::new()),
|
||||
None => {
|
||||
if misses.seen.fetch_add(1, Ordering::SeqCst) + 1 == misses.cancel_at {
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
misses.cancel.store(true, Ordering::SeqCst);
|
||||
}
|
||||
("404 Not Found", Vec::new())
|
||||
}
|
||||
};
|
||||
let head = format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
|
||||
let _ = stream.write_all(head.as_bytes());
|
||||
@@ -106,6 +120,10 @@ fn pattern(seed: u8, len: usize) -> Vec<u8> {
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
fixture_missing(false, Arc::new(Misses::default()))
|
||||
}
|
||||
|
||||
fn fixture_missing(last_chunk: bool, misses: Arc<Misses>) -> Fixture {
|
||||
let mut c1 = chunk(1, 4096);
|
||||
let mut c2 = chunk(2, 2048);
|
||||
let mut c3 = chunk(3, 1000);
|
||||
@@ -168,10 +186,13 @@ fn fixture() -> Fixture {
|
||||
let mut served = HashMap::new();
|
||||
served.insert("/Builds/x/test.manifest".to_string(), manifest_bytes);
|
||||
for (info, data) in [(&c1, &d1), (&c2, &d2), (&c3, &d3)] {
|
||||
if last_chunk && info.guid == c3.guid {
|
||||
continue;
|
||||
}
|
||||
served.insert(format!("/Builds/x/{}", parsed.chunk_path(info)), encode(data, true));
|
||||
}
|
||||
let hits = Arc::new(AtomicUsize::new(0));
|
||||
let base = serve(served, Arc::clone(&hits));
|
||||
let base = serve(served, Arc::clone(&hits), misses);
|
||||
Fixture {
|
||||
base,
|
||||
hits,
|
||||
@@ -273,6 +294,40 @@ fn a_cancelled_run_reports_cancel() {
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
fn kept_c(fx: &Fixture, game: &Path) -> bool {
|
||||
let c = &fx.expected[1].1;
|
||||
let partial = game.join(staging::DIR_NAME).join(staging::partial_name("b/c.bin", c.len() as u64, Some(Sha1::digest(c).into())));
|
||||
partial.is_file() && staging::list_path(&partial).is_file()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chunk_that_cannot_be_fetched_fails_and_keeps_written_parts() {
|
||||
let misses = Arc::new(Misses::default());
|
||||
let fx = fixture_missing(true, Arc::clone(&misses));
|
||||
let game = temp_game("fetch-fail");
|
||||
let cancel = AtomicBool::new(false);
|
||||
let err = run(&request(&fx, &game), &cancel, &Recorder::default()).unwrap_err();
|
||||
assert!(matches!(&err, Stop::Failed(m) if m.starts_with("Download failed: ")), "{err:?}");
|
||||
assert_eq!(misses.seen.load(Ordering::SeqCst), crate::fetch_core::MAX_ITEM_ATTEMPTS as usize);
|
||||
assert!(kept_c(&fx, &game));
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_during_the_last_fetch_attempt_reports_cancel_and_keeps_written_parts() {
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let last = crate::fetch_core::MAX_ITEM_ATTEMPTS as usize;
|
||||
let misses = Arc::new(Misses { seen: AtomicUsize::new(0), cancel_at: last, cancel: Arc::clone(&cancel) });
|
||||
let fx = fixture_missing(true, Arc::clone(&misses));
|
||||
let game = temp_game("fetch-cancel");
|
||||
let events = Recorder::default();
|
||||
assert_eq!(run(&request(&fx, &game), &cancel, &events).unwrap_err(), Stop::Cancelled);
|
||||
assert_eq!(misses.seen.load(Ordering::SeqCst), last);
|
||||
assert!(events.logs.lock().unwrap().iter().any(|l| l.contains(&format!("failed after {last} attempts"))));
|
||||
assert!(kept_c(&fx, &game));
|
||||
let _ = fs::remove_dir_all(&game);
|
||||
}
|
||||
|
||||
fn place_partial(fx: &Fixture, game: &Path, data: &[u8], list: &str) -> PathBuf {
|
||||
let stage = staging::recover(game).unwrap();
|
||||
let a = &fx.expected[0].1;
|
||||
|
||||
@@ -8,6 +8,7 @@ use std::time::{Duration, Instant};
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
use super::cache;
|
||||
use crate::grow_write::{holes_supported, is_cancel, GrowFront};
|
||||
use super::schedule::{PlanPart, Schedule, NONE};
|
||||
use super::{staging, Events, Stop};
|
||||
use crate::epic::chunk;
|
||||
@@ -80,6 +81,7 @@ struct Coord {
|
||||
struct Engine<'a> {
|
||||
input: &'a EngineInput<'a>,
|
||||
slots: Vec<Mutex<Slot>>,
|
||||
fronts: Vec<GrowFront>,
|
||||
coord: Mutex<Coord>,
|
||||
wake: Condvar,
|
||||
admitted: AtomicUsize,
|
||||
@@ -95,6 +97,17 @@ struct Engine<'a> {
|
||||
total_bytes: u64,
|
||||
}
|
||||
|
||||
enum Halt {
|
||||
Cancelled,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl From<String> for Halt {
|
||||
fn from(message: String) -> Self {
|
||||
Halt::Failed(message)
|
||||
}
|
||||
}
|
||||
|
||||
enum Source<'d> {
|
||||
Memory(&'d [u8]),
|
||||
Cache(PathBuf),
|
||||
@@ -112,6 +125,13 @@ impl<'a> Engine<'a> {
|
||||
message
|
||||
}
|
||||
|
||||
fn sink_error(&self, halt: Halt) -> SinkError {
|
||||
match halt {
|
||||
Halt::Cancelled => SinkError::Retry("cancelled".into()),
|
||||
Halt::Failed(message) => SinkError::Fatal(self.fail(message)),
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_path(&self, producer: usize) -> PathBuf {
|
||||
let p = &self.input.schedule.producers[producer];
|
||||
let info = &self.input.manifest.chunks[p.chunk as usize];
|
||||
@@ -158,7 +178,7 @@ impl<'a> Engine<'a> {
|
||||
self.input.schedule.producers[fetch[at] as usize].anchor as usize + 1
|
||||
}
|
||||
|
||||
fn write_use(&self, u: usize, source: &Source<'_>) -> Result<(), String> {
|
||||
fn write_use(&self, u: usize, source: &Source<'_>) -> Result<(), Halt> {
|
||||
let schedule = &self.input.schedule;
|
||||
let f = schedule.use_file[u] as usize;
|
||||
let j = u - schedule.file_start[f] as usize;
|
||||
@@ -175,16 +195,22 @@ impl<'a> Engine<'a> {
|
||||
let start = part.chunk_offset as usize;
|
||||
let end = start + part.size as usize;
|
||||
if end > data.len() {
|
||||
return Err(format!("A chunk is too short for {}", file.path));
|
||||
return Err(format!("A chunk is too short for {}", file.path).into());
|
||||
}
|
||||
let piece = &data[start..end];
|
||||
let handle = self.slots[f].lock().expect("slot lock").file.clone();
|
||||
let Some(handle) = handle else {
|
||||
return Err(format!("internal: {} is not open", file.path));
|
||||
return Err(format!("internal: {} is not open", file.path).into());
|
||||
};
|
||||
handle
|
||||
.write_all_at(piece, part.file_offset)
|
||||
.map_err(|e| format!("Could not assemble or atomically replace {}: {e}", file.path))?;
|
||||
self.fronts[f]
|
||||
.write_all_at(&handle, part.file_offset, piece, self.stop)
|
||||
.map_err(|e| {
|
||||
if is_cancel(&e) {
|
||||
Halt::Cancelled
|
||||
} else {
|
||||
Halt::Failed(format!("Could not assemble or atomically replace {}: {e}", file.path))
|
||||
}
|
||||
})?;
|
||||
self.written.fetch_add(piece.len() as u64, Ordering::Relaxed);
|
||||
|
||||
let complete = {
|
||||
@@ -343,14 +369,18 @@ impl<'a> Engine<'a> {
|
||||
}
|
||||
};
|
||||
let Some(f) = candidate else { continue };
|
||||
if let Err(e) = self.admit(f) {
|
||||
self.fail(e);
|
||||
return;
|
||||
match self.admit(f) {
|
||||
Ok(()) => {}
|
||||
Err(Halt::Cancelled) => return,
|
||||
Err(Halt::Failed(e)) => {
|
||||
self.fail(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn admit(&self, f: usize) -> Result<(), String> {
|
||||
fn admit(&self, f: usize) -> Result<(), Halt> {
|
||||
self.open_stage(f)?;
|
||||
let schedule = &self.input.schedule;
|
||||
let file = &self.input.files[f];
|
||||
@@ -415,7 +445,7 @@ impl<'a> Engine<'a> {
|
||||
out
|
||||
};
|
||||
for u in claims {
|
||||
self.write_use(u, &Source::Memory(&data)).map_err(|e| SinkError::Fatal(self.fail(e)))?;
|
||||
self.write_use(u, &Source::Memory(&data)).map_err(|h| self.sink_error(h))?;
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
@@ -446,8 +476,10 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
|
||||
cached[i] = true;
|
||||
}
|
||||
}
|
||||
let holes = holes_supported(&input.stage_dir);
|
||||
let engine = Engine {
|
||||
input,
|
||||
fronts: input.files.iter().map(|_| GrowFront::new(holes)).collect(),
|
||||
slots: input
|
||||
.files
|
||||
.iter()
|
||||
@@ -532,7 +564,7 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
|
||||
}
|
||||
ready
|
||||
};
|
||||
let outcome = std::thread::scope(|scope| {
|
||||
let (outcome, cancelled) = std::thread::scope(|scope| {
|
||||
let admitter = std::thread::Builder::new()
|
||||
.name("epic-admit".into())
|
||||
.spawn_scoped(scope, || {
|
||||
@@ -541,7 +573,7 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
|
||||
});
|
||||
if let Err(e) = admitter {
|
||||
engine.fail(format!("could not start the install thread: {e}"));
|
||||
return None;
|
||||
return (None, false);
|
||||
}
|
||||
let outcome = if items.is_empty() {
|
||||
None
|
||||
@@ -552,11 +584,9 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
|
||||
let mut c = engine.coord.lock().expect("coord lock");
|
||||
c.fetch_done = true;
|
||||
}
|
||||
if outcome.as_ref().is_some_and(|o| !o.ok()) {
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
}
|
||||
let cancelled = settle(outcome.as_ref().is_some_and(|o| !o.ok()), stop);
|
||||
engine.wake.notify_all();
|
||||
outcome
|
||||
(outcome, cancelled)
|
||||
});
|
||||
|
||||
let failure = engine.failure.lock().expect("failure lock").take().filter(|m| !m.is_empty());
|
||||
@@ -593,16 +623,35 @@ fetches={} refetches={} peak_cache_mib={} hosts={}",
|
||||
hosts.join(","),
|
||||
));
|
||||
|
||||
ending(failure, complete, fetch_error, cancelled, stop.load(Ordering::SeqCst))?;
|
||||
Ok(Stats { bytes_written: written, files_written: input.files.len() })
|
||||
}
|
||||
|
||||
fn settle(fetch_failed: bool, stop: &AtomicBool) -> bool {
|
||||
let cancelled = stop.load(Ordering::SeqCst);
|
||||
if fetch_failed {
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
}
|
||||
cancelled
|
||||
}
|
||||
|
||||
fn ending(
|
||||
failure: Option<String>,
|
||||
complete: bool,
|
||||
fetch_error: Option<String>,
|
||||
cancelled: bool,
|
||||
stopped: bool,
|
||||
) -> Result<(), Stop> {
|
||||
if let Some(message) = failure {
|
||||
return Err(Stop::Failed(message));
|
||||
}
|
||||
if complete {
|
||||
return Ok(Stats { bytes_written: written, files_written: input.files.len() });
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(message) = fetch_error {
|
||||
if let Some(message) = fetch_error.filter(|_| !cancelled) {
|
||||
return Err(Stop::Failed(format!("Download failed: {}", tidy_fetch_error(&message))));
|
||||
}
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
if stopped {
|
||||
return Err(Stop::Cancelled);
|
||||
}
|
||||
Err(Stop::Failed("The download ended before every file was written".into()))
|
||||
@@ -704,4 +753,37 @@ mod tests {
|
||||
assert_eq!(fs::read_to_string(staging::list_path(&kept)).unwrap(), "10\n20\n");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn end(fetch_error: Option<&str>, stop: &AtomicBool) -> Result<(), Stop> {
|
||||
let cancelled = settle(fetch_error.is_some(), stop);
|
||||
ending(None, false, fetch_error.map(str::to_string), cancelled, stop.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_during_the_last_fetch_attempt_ends_as_cancelled() {
|
||||
let stop = AtomicBool::new(true);
|
||||
assert!(matches!(end(Some("timed out"), &stop), Err(Stop::Cancelled)));
|
||||
assert!(matches!(end(None, &stop), Err(Stop::Cancelled)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fetch_failure_without_a_cancel_ends_as_failed() {
|
||||
let stop = AtomicBool::new(false);
|
||||
match end(Some("timed out"), &stop) {
|
||||
Err(Stop::Failed(message)) => assert!(message.starts_with("Download failed: ")),
|
||||
_ => panic!("a fetch failure must be reported"),
|
||||
}
|
||||
assert!(stop.load(Ordering::SeqCst));
|
||||
let idle = AtomicBool::new(false);
|
||||
assert!(matches!(end(None, &idle), Err(Stop::Failed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_failure_or_a_finished_install_wins_over_a_cancel() {
|
||||
assert!(matches!(
|
||||
ending(Some("disk full".into()), false, None, true, true),
|
||||
Err(Stop::Failed(message)) if message == "disk full"
|
||||
));
|
||||
assert!(ending(None, true, Some("late".into()), true, true).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io;
|
||||
use std::os::unix::fs::{FileExt, MetadataExt, OpenOptionsExt};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
pub const FILL_STEP: usize = 4 * 1024 * 1024;
|
||||
pub const DIRECT_GAP: u64 = 4 * 1024 * 1024;
|
||||
const PROBE_GAP: u64 = 1024 * 1024;
|
||||
static PROBE_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
const PROBE_PREFIX: &str = ".droiddeck-hole-probe-";
|
||||
|
||||
pub fn is_cancel(err: &io::Error) -> bool {
|
||||
err.kind() == io::ErrorKind::Interrupted
|
||||
}
|
||||
|
||||
pub fn holes_supported(dir: &Path) -> bool {
|
||||
let probe = dir.join(format!(
|
||||
"{PROBE_PREFIX}{}-{}",
|
||||
std::process::id(),
|
||||
PROBE_SEQ.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let Ok(file) = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.custom_flags(libc::O_NOFOLLOW)
|
||||
.open(&probe)
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let written = file.write_all_at(&[0u8], PROBE_GAP - 1);
|
||||
drop(file);
|
||||
let measured = written.and_then(|_| fs::symlink_metadata(&probe));
|
||||
let _ = fs::remove_file(&probe);
|
||||
measured
|
||||
.map(|meta| meta.blocks().saturating_mul(512) < PROBE_GAP)
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub struct GrowFront {
|
||||
holes: bool,
|
||||
size: AtomicU64,
|
||||
known: AtomicBool,
|
||||
fill: Mutex<()>,
|
||||
}
|
||||
|
||||
impl GrowFront {
|
||||
pub fn new(holes: bool) -> Self {
|
||||
GrowFront {
|
||||
holes,
|
||||
size: AtomicU64::new(0),
|
||||
known: AtomicBool::new(false),
|
||||
fill: Mutex::new(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&self) {
|
||||
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.known.store(false, Ordering::Release);
|
||||
self.size.store(0, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn write_all_at(
|
||||
&self,
|
||||
file: &File,
|
||||
offset: u64,
|
||||
data: &[u8],
|
||||
cancel: &AtomicBool,
|
||||
) -> io::Result<()> {
|
||||
let end = offset.saturating_add(data.len() as u64);
|
||||
if self.holes
|
||||
|| (self.known.load(Ordering::Acquire) && end <= self.size.load(Ordering::Acquire))
|
||||
{
|
||||
return file.write_all_at(data, offset);
|
||||
}
|
||||
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut size = self.current(file)?;
|
||||
if offset > size.saturating_add(DIRECT_GAP) {
|
||||
self.fill_to(file, &mut size, offset - DIRECT_GAP, cancel)?;
|
||||
}
|
||||
if let Err(err) = file.write_all_at(data, offset) {
|
||||
self.known.store(false, Ordering::Release);
|
||||
return Err(err);
|
||||
}
|
||||
self.publish(size.max(end));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn extend_to(&self, file: &File, len: u64, cancel: &AtomicBool) -> io::Result<()> {
|
||||
if self.holes {
|
||||
return file.set_len(len);
|
||||
}
|
||||
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut size = self.current(file)?;
|
||||
if size < len {
|
||||
self.fill_to(file, &mut size, len, cancel)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn current(&self, file: &File) -> io::Result<u64> {
|
||||
if self.known.load(Ordering::Acquire) {
|
||||
Ok(self.size.load(Ordering::Acquire))
|
||||
} else {
|
||||
Ok(file.metadata()?.len())
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_to(
|
||||
&self,
|
||||
file: &File,
|
||||
size: &mut u64,
|
||||
target: u64,
|
||||
cancel: &AtomicBool,
|
||||
) -> io::Result<()> {
|
||||
let zeros = vec![0u8; FILL_STEP];
|
||||
while *size < target {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
self.publish(*size);
|
||||
return Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
|
||||
}
|
||||
let step = ((target - *size) as usize).min(FILL_STEP);
|
||||
if let Err(err) = file.write_all_at(&zeros[..step], *size) {
|
||||
self.known.store(false, Ordering::Release);
|
||||
return Err(err);
|
||||
}
|
||||
*size += step as u64;
|
||||
self.publish(*size);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn publish(&self, size: u64) {
|
||||
self.size.store(size, Ordering::Release);
|
||||
self.known.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn temp_dir(tag: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"grow-write-{tag}-{}-{}",
|
||||
std::process::id(),
|
||||
PROBE_SEQ.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn open(path: &Path) -> File {
|
||||
OpenOptions::new()
|
||||
.create(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.truncate(false)
|
||||
.open(path)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn far_write_fills_the_gap_in_bounded_steps_and_keeps_data() {
|
||||
let dir = temp_dir("far");
|
||||
let path = dir.join("f.bin");
|
||||
let file = open(&path);
|
||||
let front = GrowFront::new(false);
|
||||
let cancel = AtomicBool::new(false);
|
||||
front.write_all_at(&file, 0, b"head", &cancel).unwrap();
|
||||
let far = 3 * FILL_STEP as u64 + 123;
|
||||
front.write_all_at(&file, far, b"tail", &cancel).unwrap();
|
||||
front.write_all_at(&file, 100, b"mid", &cancel).unwrap();
|
||||
let bytes = fs::read(&path).unwrap();
|
||||
assert_eq!(bytes.len() as u64, far + 4);
|
||||
assert_eq!(&bytes[0..4], b"head");
|
||||
assert_eq!(&bytes[100..103], b"mid");
|
||||
assert_eq!(&bytes[far as usize..], b"tail");
|
||||
assert!(bytes[103..far as usize].iter().all(|b| *b == 0));
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_stops_a_gap_fill_between_steps() {
|
||||
let dir = temp_dir("cancel");
|
||||
let path = dir.join("f.bin");
|
||||
let file = open(&path);
|
||||
let front = GrowFront::new(false);
|
||||
let cancel = AtomicBool::new(true);
|
||||
let err = front
|
||||
.write_all_at(&file, 8 * FILL_STEP as u64, b"x", &cancel)
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::Interrupted);
|
||||
assert_eq!(fs::metadata(&path).unwrap().len(), 0);
|
||||
cancel.store(false, Ordering::Relaxed);
|
||||
front.write_all_at(&file, 10, b"ok", &cancel).unwrap();
|
||||
assert_eq!(&fs::read(&path).unwrap()[10..], b"ok");
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_writers_never_lose_data_to_the_fill() {
|
||||
let dir = temp_dir("race");
|
||||
let path = dir.join("f.bin");
|
||||
let file = Arc::new(open(&path));
|
||||
let front = Arc::new(GrowFront::new(false));
|
||||
let piece = 64 * 1024u64;
|
||||
let count = 256u64;
|
||||
let mut order: Vec<u64> = (0..count).collect();
|
||||
order.reverse();
|
||||
let lanes: Vec<Vec<u64>> = (0..4)
|
||||
.map(|lane| order.iter().copied().filter(|i| i % 4 == lane).collect())
|
||||
.collect();
|
||||
let handles: Vec<_> = lanes
|
||||
.into_iter()
|
||||
.map(|lane| {
|
||||
let file = Arc::clone(&file);
|
||||
let front = Arc::clone(&front);
|
||||
std::thread::spawn(move || {
|
||||
let cancel = AtomicBool::new(false);
|
||||
for i in lane {
|
||||
let data = vec![(i % 251) as u8 + 1; piece as usize];
|
||||
front.write_all_at(&file, i * piece, &data, &cancel).unwrap();
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for handle in handles {
|
||||
handle.join().unwrap();
|
||||
}
|
||||
let bytes = fs::read(&path).unwrap();
|
||||
assert_eq!(bytes.len() as u64, piece * count);
|
||||
for i in 0..count {
|
||||
let start = (i * piece) as usize;
|
||||
assert!(bytes[start..start + piece as usize]
|
||||
.iter()
|
||||
.all(|b| *b == (i % 251) as u8 + 1));
|
||||
}
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_to_grows_in_steps_and_never_shrinks() {
|
||||
let dir = temp_dir("extend");
|
||||
let path = dir.join("f.bin");
|
||||
let file = open(&path);
|
||||
let front = GrowFront::new(false);
|
||||
let cancel = AtomicBool::new(false);
|
||||
front.write_all_at(&file, 0, b"data", &cancel).unwrap();
|
||||
let len = 2 * FILL_STEP as u64 + 7;
|
||||
front.extend_to(&file, len, &cancel).unwrap();
|
||||
front.extend_to(&file, 2, &cancel).unwrap();
|
||||
let bytes = fs::read(&path).unwrap();
|
||||
assert_eq!(bytes.len() as u64, len);
|
||||
assert_eq!(&bytes[0..4], b"data");
|
||||
assert!(bytes[4..].iter().all(|b| *b == 0));
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hole_capable_storage_writes_directly() {
|
||||
let dir = temp_dir("holes");
|
||||
let path = dir.join("f.bin");
|
||||
let file = open(&path);
|
||||
let front = GrowFront::new(true);
|
||||
let cancel = AtomicBool::new(true);
|
||||
front
|
||||
.write_all_at(&file, 8 * FILL_STEP as u64, b"x", &cancel)
|
||||
.unwrap();
|
||||
assert_eq!(fs::metadata(&path).unwrap().len(), 8 * FILL_STEP as u64 + 1);
|
||||
fs::remove_file(&path).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_leaves_nothing_behind() {
|
||||
let dir = temp_dir("probe");
|
||||
let other = dir.join(format!("{PROBE_PREFIX}game-file"));
|
||||
fs::write(&other, b"kept").unwrap();
|
||||
let _ = holes_supported(&dir);
|
||||
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
|
||||
assert_eq!(fs::read(&other).unwrap(), b"kept");
|
||||
fs::remove_file(&other).unwrap();
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub mod epic;
|
||||
pub mod fetch_core;
|
||||
pub mod fetch_tuning;
|
||||
pub mod gog;
|
||||
pub mod grow_write;
|
||||
pub mod md5_small;
|
||||
pub mod priority;
|
||||
pub mod steam;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//! read back and checked before anything is fetched.
|
||||
|
||||
use crate::fetch_core::{run_fetch, FetchItem, FetchOptions, FetchSink, SinkError};
|
||||
use crate::grow_write::{holes_supported, GrowFront};
|
||||
use crate::steam::cdn;
|
||||
use crate::steam::content_manifest::{ChunkData, ContentManifest};
|
||||
use crate::steam::depot_chunk::{process_depot_chunk, steam_adler_hash};
|
||||
@@ -110,6 +111,7 @@ struct FileSlot {
|
||||
size: u64,
|
||||
path: PathBuf,
|
||||
mode: u32,
|
||||
front: GrowFront,
|
||||
}
|
||||
|
||||
struct DepotFiles {
|
||||
@@ -155,17 +157,23 @@ impl DepotFiles {
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&self, file_idx: usize, offset: u64, data: &[u8]) -> Result<(), String> {
|
||||
fn write(
|
||||
&self,
|
||||
file_idx: usize,
|
||||
offset: u64,
|
||||
data: &[u8],
|
||||
cancel: &AtomicBool,
|
||||
) -> Result<(), String> {
|
||||
let file = self.acquire(file_idx)?;
|
||||
pwrite_all_at(&file, offset, data).map_err(|err| {
|
||||
let slot = &self.slots[file_idx];
|
||||
slot.front.write_all_at(&file, offset, data, cancel).map_err(|err| {
|
||||
format!(
|
||||
"write '{}' at {offset}: {err}",
|
||||
self.slots[file_idx].path.display()
|
||||
)
|
||||
})?;
|
||||
let slot = &self.slots[file_idx];
|
||||
if slot.remaining.fetch_sub(1, Ordering::AcqRel) == 1 {
|
||||
finalize(&file, slot)?;
|
||||
finalize(&file, slot, cancel)?;
|
||||
drop(file);
|
||||
self.release(file_idx);
|
||||
} else if self.open_count.load(Ordering::Relaxed) > MAX_OPEN_FILES {
|
||||
@@ -176,7 +184,7 @@ impl DepotFiles {
|
||||
}
|
||||
|
||||
/// Files with nothing left to fetch (zero chunks, or every chunk already correct on disk).
|
||||
fn finalize_untouched(&self, idx: usize) -> Result<(), String> {
|
||||
fn finalize_untouched(&self, idx: usize, cancel: &AtomicBool) -> Result<(), String> {
|
||||
let slot = &self.slots[idx];
|
||||
make_parent_dirs(&self.root, &slot.path)?;
|
||||
check_file_target(&self.root, &slot.path)?;
|
||||
@@ -188,6 +196,11 @@ impl DepotFiles {
|
||||
.map_err(|err| format!("open '{}': {err}", slot.path.display()))?;
|
||||
set_file_mode(&file, &slot.path, slot.mode)?;
|
||||
let current = file.metadata().map(|m| m.len()).unwrap_or(u64::MAX);
|
||||
if current < slot.size {
|
||||
slot.front
|
||||
.extend_to(&file, slot.size, cancel)
|
||||
.map_err(|err| format!("extend '{}': {err}", slot.path.display()))?;
|
||||
}
|
||||
if current != slot.size {
|
||||
file.set_len(slot.size)
|
||||
.map_err(|err| format!("set_len '{}': {err}", slot.path.display()))?;
|
||||
@@ -196,7 +209,10 @@ impl DepotFiles {
|
||||
}
|
||||
}
|
||||
|
||||
fn finalize(file: &File, slot: &FileSlot) -> Result<(), String> {
|
||||
fn finalize(file: &File, slot: &FileSlot, cancel: &AtomicBool) -> Result<(), String> {
|
||||
slot.front
|
||||
.extend_to(file, slot.size, cancel)
|
||||
.map_err(|err| format!("extend '{}': {err}", slot.path.display()))?;
|
||||
file.set_len(slot.size)
|
||||
.map_err(|err| format!("set_len '{}': {err}", slot.path.display()))?;
|
||||
file.sync_all()
|
||||
@@ -207,6 +223,7 @@ struct ChunkSink<'a> {
|
||||
chunks: &'a [UniqueChunk],
|
||||
files: &'a DepotFiles,
|
||||
depot_key: &'a [u8],
|
||||
cancel: &'a AtomicBool,
|
||||
}
|
||||
|
||||
impl FetchSink for ChunkSink<'_> {
|
||||
@@ -225,7 +242,12 @@ impl FetchSink for ChunkSink<'_> {
|
||||
let mut credited = 0u64;
|
||||
for target in &chunk.targets {
|
||||
self.files
|
||||
.write(target.file_idx as usize, target.offset, &processed.data)
|
||||
.write(
|
||||
target.file_idx as usize,
|
||||
target.offset,
|
||||
&processed.data,
|
||||
self.cancel,
|
||||
)
|
||||
.map_err(SinkError::Fatal)?;
|
||||
credited += processed.data.len() as u64;
|
||||
}
|
||||
@@ -276,6 +298,7 @@ fn prepare(
|
||||
}
|
||||
};
|
||||
|
||||
let holes = holes_supported(&root);
|
||||
let mut slots = Vec::with_capacity(manifest.files.len());
|
||||
let mut existing = Vec::with_capacity(manifest.files.len());
|
||||
for file in &manifest.files {
|
||||
@@ -297,6 +320,7 @@ fn prepare(
|
||||
} else {
|
||||
0o644
|
||||
},
|
||||
front: GrowFront::new(holes),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -354,7 +378,10 @@ fn prepare(
|
||||
continue;
|
||||
}
|
||||
let mut remaining = 0usize;
|
||||
for (chunk_idx, chunk) in file.chunks.iter().enumerate() {
|
||||
let mut by_offset: Vec<usize> = (0..file.chunks.len()).collect();
|
||||
by_offset.sort_by_key(|&idx| file.chunks[idx].offset);
|
||||
for chunk_idx in by_offset {
|
||||
let chunk = &file.chunks[chunk_idx];
|
||||
if verified[file_idx].get(chunk_idx).copied().unwrap_or(false) {
|
||||
bytes_verified += chunk.cb_original as u64;
|
||||
continue;
|
||||
@@ -393,7 +420,13 @@ fn prepare(
|
||||
if is_regular(file.flags, &file.linktarget)
|
||||
&& files.slots[idx].remaining.load(Ordering::Relaxed) == 0
|
||||
{
|
||||
if let Err(err) = files.finalize_untouched(idx) {
|
||||
if let Err(err) = files.finalize_untouched(idx, cancel) {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
return Err(DepotWriteOutcome {
|
||||
cancelled: true,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
return Err(DepotWriteOutcome::fail(err));
|
||||
}
|
||||
}
|
||||
@@ -449,6 +482,7 @@ pub fn write_depot(
|
||||
chunks: &chunks,
|
||||
files: &files,
|
||||
depot_key: request.depot_key,
|
||||
cancel,
|
||||
};
|
||||
let depot_id = manifest.metadata.depot_id;
|
||||
let done_before = AtomicU64::new(bytes_verified);
|
||||
@@ -676,12 +710,6 @@ fn set_file_mode(_file: &File, _path: &Path, _mode: u32) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn pwrite_all_at(file: &File, offset: u64, data: &[u8]) -> std::io::Result<()> {
|
||||
use std::os::unix::fs::FileExt;
|
||||
file.write_all_at(data, offset)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn pread_exact_at(file: &File, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
|
||||
use std::os::unix::fs::FileExt;
|
||||
@@ -766,6 +794,7 @@ mod tests {
|
||||
size: 10,
|
||||
path: path.clone(),
|
||||
mode: 0o644,
|
||||
front: GrowFront::new(true),
|
||||
}];
|
||||
let root = fs::canonicalize(&dir).unwrap();
|
||||
let flags = verify_existing(&manifest, &slots, &[10], &root, 2, &AtomicBool::new(false));
|
||||
@@ -808,6 +837,44 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queues_each_files_chunks_in_offset_order() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"droiddeck_steam_order_{}",
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
let key = [5u8; 32];
|
||||
let manifest = ContentManifest {
|
||||
files: vec![FileMapping {
|
||||
filename: "big.pak".into(),
|
||||
size: 15,
|
||||
chunks: vec![chunk(b"three", 10), chunk(b"first", 0), chunk(b"other", 5)],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let request = DepotWriteRequest {
|
||||
manifest: &manifest,
|
||||
depot_key: &key,
|
||||
servers: &[],
|
||||
target_dir: &dir,
|
||||
ca_bundle_path: "",
|
||||
max_workers: 1,
|
||||
process_workers: 1,
|
||||
};
|
||||
let prepared = prepare(&request, &AtomicBool::new(false)).unwrap();
|
||||
let offsets: Vec<u64> = prepared
|
||||
.chunks
|
||||
.iter()
|
||||
.map(|c| c.targets[0].offset)
|
||||
.collect();
|
||||
assert_eq!(offsets, vec![0, 5, 10]);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_in_place_dedupes_chunks_and_resumes_from_disk() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
@@ -867,6 +934,7 @@ mod tests {
|
||||
chunks: &prepared.chunks,
|
||||
files: &prepared.files,
|
||||
depot_key: &key,
|
||||
cancel: &cancel,
|
||||
};
|
||||
let item = |id: u64| FetchItem {
|
||||
id,
|
||||
@@ -886,6 +954,7 @@ mod tests {
|
||||
chunks: &wrong,
|
||||
files: &prepared.files,
|
||||
depot_key: &key,
|
||||
cancel: &cancel,
|
||||
};
|
||||
assert!(matches!(
|
||||
wrong_sink.process(&item(0), encrypted_chunk(&key, b"HELLO")),
|
||||
|
||||
@@ -145,4 +145,15 @@ class AddedGamesCandidatesTest {
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
|
||||
assertEquals("My Game [Repack]", AddedGames.scan(app).single().name)
|
||||
}
|
||||
|
||||
@Test fun linksAndFoldersNamedLikeAnExeAreNotCandidates() {
|
||||
val elsewhere = tmp.newFolder("Elsewhere")
|
||||
exe(elsewhere, "Other.exe")
|
||||
val game = tmp.newFolder("Linked")
|
||||
exe(game, "bin/Linked.exe")
|
||||
File(game, "Folder.exe").mkdirs()
|
||||
java.nio.file.Files.createSymbolicLink(File(game, "other").toPath(), elsewhere.toPath())
|
||||
java.nio.file.Files.createSymbolicLink(File(game, "Alias.exe").toPath(), File(elsewhere, "Other.exe").toPath())
|
||||
assertEquals(listOf("bin/Linked.exe"), names(game))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.SteamLiveShortcuts
|
||||
import java.io.File
|
||||
import java.util.Collections
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class AddedGamesSessionListingTest {
|
||||
private val app get() = RuntimeEnvironment.getApplication()
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@After fun restore() {
|
||||
AddedGamesPublisher.now = false
|
||||
AddedGamesPublisher.live = SteamLiveShortcuts::sync
|
||||
SessionState.running = false
|
||||
SessionState.stopRequested = false
|
||||
SessionState.sessionId = null
|
||||
SessionState.phase = SessionPhase.IDLE
|
||||
}
|
||||
|
||||
private val stale = """[{"name":"Old","exe":"/root/Games/Old/Old.exe","folder":"/root/Games/Old","dir":"/root/Games/Old","appid":2147483649,"seen":0}]"""
|
||||
|
||||
private fun gamesFolder(vararg names: String): File {
|
||||
val games = tmp.newFolder("PC")
|
||||
for (n in names) File(games, "$n/$n.exe").apply { parentFile!!.mkdirs() }.writeText("game")
|
||||
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
|
||||
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
|
||||
return games
|
||||
}
|
||||
|
||||
private fun session(phase: SessionPhase) {
|
||||
SessionState.sessionId = "session-test"
|
||||
SessionState.stopRequested = false
|
||||
SessionState.phase = phase
|
||||
SessionState.running = true
|
||||
}
|
||||
|
||||
private fun until(what: String, check: () -> Boolean) {
|
||||
val end = System.currentTimeMillis() + 30_000
|
||||
while (!check()) {
|
||||
assertTrue(what, System.currentTimeMillis() < end)
|
||||
Thread.sleep(20)
|
||||
}
|
||||
}
|
||||
|
||||
private fun scanLock(): Any =
|
||||
AddedGames::class.java.getDeclaredField("scanning").apply { isAccessible = true }.get(null)!!
|
||||
|
||||
private fun refreshes() = Thread.getAllStackTraces().keys.filter { it.name == "added-games-refresh" }
|
||||
|
||||
@Test fun aSessionStartsFromTheLastListingWhileTheLibraryScanHoldsTheLock() {
|
||||
gamesFolder("Alpha")
|
||||
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val done = CountDownLatch(1)
|
||||
var returned: File? = null
|
||||
var seen = ""
|
||||
synchronized(scanLock()) {
|
||||
Thread {
|
||||
returned = AddedGamesPublisher.sessionListing(app)
|
||||
seen = listing.readText()
|
||||
done.countDown()
|
||||
}.start()
|
||||
assertTrue("the session start waited for the library scan", done.await(5, TimeUnit.SECONDS))
|
||||
}
|
||||
assertEquals(listing.path, returned!!.path)
|
||||
assertEquals(stale, seen)
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
val fresh = listing.readText()
|
||||
assertTrue(fresh.contains("\"Alpha\""))
|
||||
assertFalse(fresh.contains("\"Old\""))
|
||||
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
|
||||
}
|
||||
|
||||
@Test fun aFirstSessionScansBeforeStarting() {
|
||||
gamesFolder("Alpha")
|
||||
AddedGamesPublisher.now = false
|
||||
val listing = AddedGames.listingFile(app)
|
||||
listing.delete()
|
||||
assertEquals(listing.path, AddedGamesPublisher.sessionListing(app).path)
|
||||
assertTrue(listing.readText().contains("\"Alpha\""))
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
|
||||
}
|
||||
|
||||
@Test fun aListingThatCannotBeReplacedKeepsTheOldOne() {
|
||||
val listing = AddedGames.listingFile(app).apply { parentFile?.mkdirs() }
|
||||
listing.writeText("[]")
|
||||
val blocked = File(listing.parentFile, listing.name + ".part").apply { mkdirs() }
|
||||
gamesFolder("Alpha")
|
||||
AddedGames.writeListing(app, AddedGames.scan(app))
|
||||
assertEquals("[]", listing.readText())
|
||||
assertFalse(blocked.exists())
|
||||
}
|
||||
|
||||
@Test fun anUnreadableListingIsRescannedBeforeStarting() {
|
||||
gamesFolder("Alpha")
|
||||
AddedGamesPublisher.now = false
|
||||
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText("[{\"name\":") }
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
assertTrue(listing.readText().contains("\"Alpha\""))
|
||||
assertTrue(refreshes().isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aGameRemovedWhileTheClientStartsIsNotAddedToIt() {
|
||||
val games = gamesFolder("Alpha", "Beta")
|
||||
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val delivered = Collections.synchronizedList(ArrayList<String>())
|
||||
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
|
||||
session(SessionPhase.STARTING_STEAM)
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
until("the refresh did not write the listing") { listing.readText().contains("\"Beta\"") }
|
||||
SessionPrefs.setAddedGameRemoved(app, File(games, "Beta").path, true)
|
||||
SessionState.phase = SessionPhase.READY
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertEquals(listOf("Alpha"), delivered.toList())
|
||||
}
|
||||
|
||||
@Test fun aDeliveryTheClientRefusesIsRetriedUntilItIsTaken() {
|
||||
gamesFolder("Alpha")
|
||||
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val attempts = Collections.synchronizedList(ArrayList<List<String>>())
|
||||
AddedGamesPublisher.live = { _, found, include -> attempts.add(found.filter(include).map { it.name }); attempts.size > 1 }
|
||||
session(SessionPhase.READY)
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertEquals(listOf(listOf("Alpha"), listOf("Alpha")), attempts.toList())
|
||||
}
|
||||
|
||||
@Test fun anEndedSessionStopsTheRetries() {
|
||||
gamesFolder("Alpha")
|
||||
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val attempts = Collections.synchronizedList(ArrayList<String>())
|
||||
AddedGamesPublisher.live = { _, found, _ -> attempts.addAll(found.map { it.name }); SessionState.running = false; false }
|
||||
session(SessionPhase.READY)
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertEquals(listOf("Alpha"), attempts.toList())
|
||||
}
|
||||
|
||||
@Test fun aDeliveryQueuedForAnEndedSessionIsNotSentToTheNextOne() {
|
||||
gamesFolder("Alpha")
|
||||
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val delivered = Collections.synchronizedList(ArrayList<String>())
|
||||
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
|
||||
session(SessionPhase.READY)
|
||||
val first = CountDownLatch(1)
|
||||
val firstHeld = CountDownLatch(1)
|
||||
val second = CountDownLatch(1)
|
||||
val secondHeld = CountDownLatch(1)
|
||||
AddedGamesPublisher.later(app) { firstHeld.countDown(); first.await() }
|
||||
try {
|
||||
assertTrue(firstHeld.await(30, TimeUnit.SECONDS))
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
val refresh = refreshes().single()
|
||||
until("the refresh did not wait for its scan") { refresh.state == Thread.State.WAITING }
|
||||
AddedGamesPublisher.later(app) { secondHeld.countDown(); second.await() }
|
||||
first.countDown()
|
||||
assertTrue(secondHeld.await(30, TimeUnit.SECONDS))
|
||||
until("the refresh did not queue its delivery") {
|
||||
refresh.state == Thread.State.WAITING && refresh.stackTrace.any { it.methodName == "deliver" }
|
||||
}
|
||||
SessionState.sessionId = "session-next"
|
||||
} finally {
|
||||
first.countDown()
|
||||
second.countDown()
|
||||
}
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertTrue(delivered.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun theRefreshWaitsForEarlierPublicationsBeforeWriting() {
|
||||
gamesFolder("Alpha")
|
||||
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
|
||||
val hold = CountDownLatch(1)
|
||||
val holding = CountDownLatch(1)
|
||||
AddedGamesPublisher.later(app) { holding.countDown(); hold.await() }
|
||||
try {
|
||||
assertTrue(holding.await(30, TimeUnit.SECONDS))
|
||||
AddedGamesPublisher.sessionListing(app)
|
||||
val refresh = refreshes().single()
|
||||
until("the refresh neither finished nor waited") { refresh.state == Thread.State.WAITING || !refresh.isAlive }
|
||||
assertTrue("the refresh wrote while an earlier publication was running", refresh.isAlive)
|
||||
assertEquals(stale, listing.readText())
|
||||
} finally {
|
||||
hold.countDown()
|
||||
}
|
||||
refreshes().forEach { it.join(30_000) }
|
||||
assertTrue(refreshes().isEmpty())
|
||||
assertTrue(listing.readText().contains("\"Alpha\""))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
|
||||
class NpuInfoTest {
|
||||
@get:Rule val tmp = TemporaryFolder()
|
||||
|
||||
@Test fun modelPicksTheHexagonGenerationAndFallsBackToThePlatform() {
|
||||
assertEquals(NpuInfo.Hexagon.V79, NpuInfo.hexagon("SM8750", "sun"))
|
||||
assertEquals(NpuInfo.Hexagon.V81, NpuInfo.hexagon("QTI SM8850", ""))
|
||||
assertEquals(NpuInfo.Hexagon.V73, NpuInfo.hexagon("", "Kalama"))
|
||||
assertNull(NpuInfo.hexagon("MT6989", "mt6989"))
|
||||
}
|
||||
|
||||
@Test fun nodeAccessSeparatesMissingFromDenied() {
|
||||
assertEquals(NpuInfo.Access.NO_NODE, NpuInfo.access(listOf(File(tmp.root, "nope"))).second)
|
||||
val node = tmp.newFile("fastrpc-cdsp")
|
||||
assertEquals(NpuInfo.Access.OPEN, NpuInfo.access(listOf(File(tmp.root, "nope"), node)).second)
|
||||
node.setWritable(false)
|
||||
val absent = File(tmp.root, "no-broker")
|
||||
if (!node.canWrite()) {
|
||||
assertEquals(NpuInfo.Access.DENIED, NpuInfo.access(listOf(node), absent).second)
|
||||
assertEquals(NpuInfo.Access.BROKERED, NpuInfo.access(listOf(node), tmp.newFile("dsp-service.xml")).second)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun usableNeedsChipNodeAndRuntime() {
|
||||
val ok = NpuInfo.Status(NpuInfo.Hexagon.V79, "/dev/fastrpc-cdsp", NpuInfo.Access.OPEN, true)
|
||||
assertTrue(ok.usable)
|
||||
assertTrue(ok.copy(access = NpuInfo.Access.BROKERED).usable)
|
||||
assertFalse(ok.copy(access = NpuInfo.Access.DENIED).usable)
|
||||
assertFalse(ok.copy(qnnRuntime = false).usable)
|
||||
assertFalse(ok.copy(hexagon = null).usable)
|
||||
}
|
||||
|
||||
@Test fun runtimeIsBundledOnlyWhenEveryLibraryIsPresent() {
|
||||
NpuInfo.QNN_LIBS.dropLast(1).forEach { File(tmp.root, it).createNewFile() }
|
||||
assertFalse(NpuInfo.detect(tmp.root, NpuInfo.Hexagon.V79).qnnRuntime)
|
||||
File(tmp.root, NpuInfo.QNN_LIBS.last()).createNewFile()
|
||||
assertTrue(NpuInfo.detect(tmp.root, NpuInfo.Hexagon.V79).qnnRuntime)
|
||||
}
|
||||
}
|
||||
@@ -201,6 +201,25 @@ class DirectTouchHoldTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun aDragLiftsAtOnce() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
touch(MotionEvent.ACTION_MOVE, 80f)
|
||||
advance(80)
|
||||
touches.clear()
|
||||
touch(MotionEvent.ACTION_UP, 80f)
|
||||
assertEquals(listOf("up 0 at 80.0,30.0"), touches)
|
||||
}
|
||||
|
||||
@Test fun aTapStaysPressedLongEnoughToBeSeen() {
|
||||
touch(MotionEvent.ACTION_DOWN)
|
||||
advance(10)
|
||||
touch(MotionEvent.ACTION_UP)
|
||||
advance(49)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
|
||||
advance(1)
|
||||
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
|
||||
}
|
||||
|
||||
private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
|
||||
private fun touch(action: Int, x: Float = 40f): Boolean {
|
||||
val event = MotionEvent.obtain(0, 0, action, x, 30f, 0)
|
||||
|
||||
@@ -36,7 +36,43 @@ class GameEnvironmentStoreTest {
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
|
||||
.remove("logs")
|
||||
.remove("gameDebugLogsEnabled")
|
||||
.remove("gameCpus")
|
||||
.commit()
|
||||
listOf("game-environment.json.new", "game-cores.new").forEach { File(guest.parentFile, it).delete() }
|
||||
}
|
||||
|
||||
@Test fun gameCoresChangedInSettingsReachTheGuestAtOnce() {
|
||||
val live = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck/game-cores")
|
||||
val all = com.droiddeck.launcher.core.CpuCores.all
|
||||
|
||||
SessionPrefs.setGameCpus(context, all.last().toString())
|
||||
assertEquals("${all.last()}\n", live.readText())
|
||||
|
||||
SessionPrefs.setGameCpus(context, com.droiddeck.launcher.core.CpuCores.format(all.toSet()))
|
||||
assertEquals("\n", live.readText())
|
||||
}
|
||||
|
||||
@Config(sdk = [34])
|
||||
@Test fun gameCoresStillReachTheGuestWhenTheRestOfTheEnvironmentCannotBeWritten() {
|
||||
val dir = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck")
|
||||
val last = com.droiddeck.launcher.core.CpuCores.all.last()
|
||||
assertTrue(File(dir, "game-environment.json.new").mkdirs())
|
||||
|
||||
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putString("gameCpus", last.toString()).commit()
|
||||
|
||||
assertTrue(runCatching { GameEnvironmentStore.publish(context) }.isFailure)
|
||||
assertEquals("$last\n", File(dir, "game-cores").readText())
|
||||
}
|
||||
|
||||
@Test fun gameCoresThatCannotBeWrittenLeaveNoOlderValueForTheGuest() {
|
||||
val dir = File(LinuxRuntime.rootDir(context), "root/.config/droiddeck")
|
||||
val all = com.droiddeck.launcher.core.CpuCores.all
|
||||
SessionPrefs.setGameCpus(context, all.last().toString())
|
||||
assertTrue(File(dir, "game-cores.new").mkdirs())
|
||||
|
||||
SessionPrefs.setGameCpus(context, all.first().toString())
|
||||
|
||||
assertFalse(File(dir, "game-cores").exists())
|
||||
}
|
||||
|
||||
@Test fun gameDebugLogsAreOffByDefault() {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class GuestLeftoversTest {
|
||||
private fun environ(vararg entries: String) = entries.joinToString("\u0000", postfix = "\u0000").toByteArray()
|
||||
|
||||
@Test
|
||||
fun aProcessOfTheEndedSessionCarriesItsFolder() {
|
||||
val marker = "DD_DEBUG_DIR=/data/logs/2026-11-28-85-steam"
|
||||
assertTrue(GuestLeftovers.carries(environ("HOME=/home/deck", marker, "TERM=xterm"), marker))
|
||||
assertTrue(GuestLeftovers.carries(environ(marker), marker))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anotherSessionsFolderOrALongerPathIsNotTheEndedSession() {
|
||||
val marker = "DD_DEBUG_DIR=/data/logs/2026-11-28-85-steam"
|
||||
assertFalse(GuestLeftovers.carries(environ("DD_DEBUG_DIR=/data/logs/2026-11-28-86-steam"), marker))
|
||||
assertFalse(GuestLeftovers.carries(environ("$marker-2"), marker))
|
||||
assertFalse(GuestLeftovers.carries(environ("X$marker"), marker))
|
||||
assertFalse(GuestLeftovers.carries(null, marker))
|
||||
assertFalse(GuestLeftovers.carries(ByteArray(0), marker))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whatAMatchedProcessStartedGoesWithIt() {
|
||||
// 10 was proot's child and now belongs to init; 12 cleared its environment; 20 is unrelated
|
||||
val parents = mapOf(10 to 1, 11 to 10, 12 to 11, 13 to 12, 20 to 1, 21 to 20)
|
||||
assertEquals(setOf(10, 11, 12, 13), GuestLeftovers.withDescendants(setOf(10), parents))
|
||||
assertEquals(emptySet<Int>(), GuestLeftovers.withDescendants(emptySet(), parents))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class SteamLiveShortcutsSyncTest {
|
||||
@Test fun everyGameKnownOrAddedIsDelivered() {
|
||||
assertTrue(SteamLiveShortcuts.synced("""{"added":2,"missed":0}"""))
|
||||
assertTrue(SteamLiveShortcuts.synced("""{"added":0,"missed":0}"""))
|
||||
}
|
||||
|
||||
@Test fun aGameTheClientRefusedIsNotDelivered() {
|
||||
assertFalse(SteamLiveShortcuts.synced("""{"added":1,"missed":1}"""))
|
||||
assertFalse(SteamLiveShortcuts.synced("""{"added":0,"missed":3}"""))
|
||||
}
|
||||
|
||||
@Test fun noAnswerIsNotDelivered() {
|
||||
assertFalse(SteamLiveShortcuts.synced(null))
|
||||
assertFalse(SteamLiveShortcuts.synced("1"))
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,34 @@ class DownloadQueueRemovalTest {
|
||||
assertFalse(folder.exists())
|
||||
}
|
||||
|
||||
@Test fun uninstallStopsARunningDownloadThenRemovesTheGame() {
|
||||
val running = CountDownLatch(1)
|
||||
val cancels = AtomicInteger()
|
||||
val entry = DownloadEntry(Store.GOG, "uninstall-while-running", "Running")
|
||||
DownloadQueue.enqueue(app, entry) {
|
||||
object : DownloadQueue.DownloadJob {
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
running.countDown()
|
||||
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(10)
|
||||
while (!handle.isCancelled && System.nanoTime() < until) Thread.sleep(10)
|
||||
return null
|
||||
}
|
||||
override fun cancel(deleteFiles: Boolean) { cancels.incrementAndGet() }
|
||||
}
|
||||
}
|
||||
assertTrue(running.await(5, TimeUnit.SECONDS))
|
||||
val folder = File(app.filesDir, "uninstall-while-running").apply { mkdirs() }
|
||||
File(folder, "game.bin").writeText("x")
|
||||
val game = InstalledStoreGame(StoreGameSidecar(Store.GOG, "uninstall-while-running", "Running", exe = "game.bin"), folder)
|
||||
assertEquals(entry.key, game.key)
|
||||
val done = CountDownLatch(1)
|
||||
StoresState.uninstall(app, game) { done.countDown() }
|
||||
assertTrue(idleUntil { done.count == 0L })
|
||||
assertEquals(1, cancels.get())
|
||||
assertTrue(DownloadQueue.entry(entry.key)?.state.let { it == null || it == DownloadState.CANCELLED })
|
||||
assertFalse(folder.exists())
|
||||
}
|
||||
|
||||
private fun blockDiscards(): CountDownLatch {
|
||||
val release = CountDownLatch(1)
|
||||
StoreInstalls.beforeDiscard = { release.await(5, TimeUnit.SECONDS) }
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class IdleFramesTest {
|
||||
@Test
|
||||
fun idleLoopsDrawThirtyFramesASecondAndShareEachOne() {
|
||||
val start = 5_000_000_000L
|
||||
val frame = 8_333_333L
|
||||
val drawn = (0 until 120).count { IdleFrames.due(start + it * frame) }
|
||||
assertEquals(30, drawn)
|
||||
|
||||
val later = start + 1_000_000_000L
|
||||
assertEquals(listOf(true, true, true), List(3) { IdleFrames.due(later) })
|
||||
assertEquals(listOf(false, false), List(2) { IdleFrames.due(later + frame) })
|
||||
assertEquals(listOf(true, true), List(2) { IdleFrames.due(later + 4 * frame) })
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ EA games install, update and start without the EA app. The research behind it is
|
||||
| Downloads | Rust `src/ea/` in `libdroiddeckstores.so`, `EaInstaller.kt` | A build is one ZIP on EA's CDN. The engine reads its central directory with ranged reads, keeps files whose size and CRC match, and streams every other entry through inflate into place. `.droiddeck-ea-files` records what it placed, so a resume or update does not re-hash those files; files a new build drops are removed. |
|
||||
| Updates | `EaUpdates` in `EaBackend.kt` | The game page compares the installed version with the offer's live `gameVersion` (every 30 minutes at most). Update runs the same install, which only fetches changed files. |
|
||||
| Launch, guest | `droiddeck-store-launch` (`prepare_ea`) | Creates the prefix, reads the machine as Wine reports it (`wmic`, `vol`, `hostname`; cached in `pfx/.droiddeck-ea-hw.json`), writes EA app presence keys and the game's `Install Dir` keys in both registry views, runs the build's Touchup once per installed build, then asks the app for the session and writes any licence files. |
|
||||
| Launch, Steam copy | `prepare_steam_ea` in `droiddeck-store-launch`, the Proton wrapper | Steam starts its EA titles with `steam2ea://`, which only the EA app handles, and the EA app does not install here. When the prefix has no EA app, the hook reads the game's `__Installer/installerdata.xml` and its offers (`__Installer/LOC/Origin.OFR.*.dat`), runs `prepare_ea` with a `steam` request (the app answers with the launch environment instead of a sidecar file), and writes `droiddeck-ea-steam.bat` in the game's compatdata. The wrapper runs that launcher in place of the link. Writing the EA app presence keys also satisfies the install script, so Steam stops running the EA app installer. |
|
||||
| Launch, app | `EaLaunch.kt`, `EaOoa.kt`, `EaLsx.kt` | Answers `ea-prepare`: starts the LSX endpoint on `127.0.0.1:3216`, mints the short-lived opaque token, writes `.droiddeck-ea-env` (read once and deleted by the launcher `.bat`), and for games with a `Core` folder requests an online-activation licence for the machine hash. |
|
||||
| LSX | `EaLsx.kt` | The local endpoint EA's SDK talks to instead of the EA app: challenge, AES session key, config, profile, settings, game info, auth codes for the game's own client ids, licences with Denuvo tokens, entitlements. Friends, presence and the overlay answer empty. |
|
||||
|
||||
@@ -26,6 +27,5 @@ WMI does not expose, so those use `00000000` unless the probe learns it.
|
||||
## Not done yet
|
||||
|
||||
- Cloud saves (`cloudsync.juno.ea.com`).
|
||||
- Steam copies of EA games still install the EA app (#2036).
|
||||
- Pre-DiP games (no `installerdata.xml`) fall back to the exe picker.
|
||||
- Javelin anti-cheat games do not run under Proton.
|
||||
@@ -0,0 +1,129 @@
|
||||
# Neural upscaling on the Hexagon NPU
|
||||
|
||||
Reference: [Winlator-NeuralScale](https://github.com/michaelisomer-cyber/Winlator-NeuralScale), a Winlator fork that
|
||||
runs AMD FSR 4 on the Qualcomm Hexagon HTP through QNN, with GPU (DP4a) FSR 4 / XeSS / FSR 3.1 fallbacks. This note
|
||||
records what carries over to DroidDeck, what does not, and what has been built so far.
|
||||
|
||||
## How the reference works
|
||||
|
||||
A Vulkan layer in the game's process intercepts the game's own upscaler calls (FSR 2/3/4, DLSS through an NGX
|
||||
bridge, XeSS) via replacement DLLs. Those calls hand over colour, depth, motion vectors, exposure and jitter. The
|
||||
layer runs the FSR 4 network (INT8, compiled on the device by `libQnnHtpPrepare.so`) on the NPU, with Vulkan passes
|
||||
before and after it and `AHardwareBuffer` for the hand-off.
|
||||
|
||||
## What carries over, what does not
|
||||
|
||||
| Piece | In DroidDeck |
|
||||
|---|---|
|
||||
| Game-side hook (DLL replacement, NGX/FFX bridges) | The guest runs Steam under FEX and Proton, so the same Windows-side bridge DLLs could apply, but nothing in the repo loads them yet. |
|
||||
| Temporal inputs (depth, motion vectors, jitter) | Only exist inside the guest. The Wayland compositor (`waylandcomp`, where FSR 1 / SGSR / frame generation run) sees a finished colour frame, so FSR 4 cannot run there. A compositor-side network would have to be a spatial-only super-resolution model, a different thing from FSR 4. |
|
||||
| QNN runtime and skel libraries | Qualcomm's, not redistributable here. They would come from the user's own QAIRT SDK or a runtime download. |
|
||||
| FSR 4 weights | AMD's. The reference ships them in its APK; DroidDeck should not copy them without a licence check. |
|
||||
| DP4a GPU path | Independent of the NPU and the most portable part. Needs the same guest-side hook. |
|
||||
|
||||
## Findings: the NPU is reachable from an unprivileged app
|
||||
|
||||
Tested on the Retroid Pocket Duo (SM8750, Hexagon v79) and the AYANEO Pocket FIT Elite (SM8750P, stock, no root).
|
||||
|
||||
**The node is closed, but there is a supported way around it.**
|
||||
|
||||
- `/dev/fastrpc-cdsp` is `0664 system:system` and the two `-secure` nodes are `0644`. A real app uid (checked with
|
||||
`run-as` as uid 10185) fails `access(W_OK)`. This is Qualcomm's own `ueventd` setting, not an OEM quirk.
|
||||
- Qualcomm's `libcdsprpc.so` is not loadable by an app on this firmware: `libcdsprpc.so` and even `libOpenCL.so` fail
|
||||
with "not found" from an app namespace, with or without `<uses-native-library>`, and a copy would need private
|
||||
system libraries (`libutils`, `libhidlbase`, `libcutils`). So QNN stubs that `dlopen("libcdsprpc.so")` fail today.
|
||||
- The vendor AIDL service `vendor.qti.hardware.dsp.IDspService/default` (process `dspservice`, uid `system`) opens
|
||||
the node on behalf of callers. From the app, `AServiceManager_checkService` returns it,
|
||||
`getNewDSPSession(int)` returns an `IDspManager`, and `openSession(DSPDomain)` returns a `FastrpcDev` whose
|
||||
`NativeHandle` carries an open descriptor for `/dev/fastrpc-cdsp`. `readlink` on it gives `/dev/fastrpc-cdsp`.
|
||||
- On that descriptor, from the app: `FASTRPC_IOCTL_GET_DSP_INFO` (`_IOWR('R', 13, ...)`) succeeds and reports
|
||||
unsigned-PD support (attribute 1 = 1). `FASTRPC_IOCTL_INIT_ATTACH` returns `EACCES`, and the kernel logs "untrusted
|
||||
app trying to attach to privileged DSP PD". That is the expected outcome: an app must create an unsigned PD
|
||||
(`INIT_CREATE`) instead of attaching to the root PD.
|
||||
|
||||
Wire format that worked (transaction codes are the AIDL order): `IDspService` 1 = `getNewDSPSession(int)`;
|
||||
`IDspManager` 2 = `openSession`. The `in DSPDomain` argument is written as `[1 (non-null)][size][domain]`; domain 3 is
|
||||
the compute DSP. The reply is `[status][1][size][int][int][NativeHandle: size, fd count, fds, int count]`.
|
||||
`tools/experiments/npu-fastrpc-probe` reproduces all of it; results go to logcat tag `NPUPROBE`.
|
||||
|
||||
### AYN Thor (QCS8550, Hexagon v73, Android 13, release-keys): closed
|
||||
|
||||
- `/dev/adsprpc-smd` is `0664 system:system` and `open(O_RDWR)` from an app gives `EACCES`. There is no
|
||||
`/dev/fastrpc-cdsp`.
|
||||
- There is no `IDspService` here. `checkService` returns null, and SELinux logs a `find` denial for
|
||||
`untrusted_app` on `default_android_service`.
|
||||
- `dlopen("libcdsprpc.so")` fails with "not found" even with `<uses-native-library>` declared.
|
||||
- So no route was found on this device without root. SELinux is enforcing here, which is the case the 8 Elite tests
|
||||
could not cover.
|
||||
|
||||
### How BananaNative's PR (moceure/BananaNative #703) gets in
|
||||
|
||||
It declares `<uses-native-library android:name="libcdsprpc.so" android:required="false"/>`, then
|
||||
`dlopen("libcdsprpc.so")`, `remote_handle_control(4, {domain 3, enable 1})` to request an unsigned PD, and an
|
||||
`ADSP_LIBRARY_PATH` that puts the app's own `adsp` directory first so the DSP can load the HTP skel from the app.
|
||||
That only works on firmware that exposes the vendor library to apps; its logs are from a Xiaomi phone on a v81 SoC.
|
||||
It does not work on the three Qualcomm-reference style builds tried here (Duo, FIT Elite, Thor), where the library is
|
||||
invisible to app namespaces. Useful from it, if the NPU path goes ahead: a process-wide ref-counted QNN HTP runtime
|
||||
shared by two users, zero-copy `AHardwareBuffer` DMA-BUF registration, a thermal power tier (turbo, balanced, low)
|
||||
with hysteresis, and clamping the ADPF target duration to the frame-generated output period so the PowerHAL does not
|
||||
halve a 2x frame-generated game. Its MIT-licensed GLSL for flow, splat and blend is a possible reference for DD-FG.
|
||||
Its QNN graph binaries come from a companion repo; where they derive from is a licence question.
|
||||
|
||||
Caveats:
|
||||
|
||||
- SELinux is permissive on both devices (dev-keys builds). On an enforcing production build, `untrusted_app` may not
|
||||
be allowed to find `IDspService`, and that has not been tried.
|
||||
- Nothing has run on the NPU yet. A descriptor and a capability query are not a graph execution.
|
||||
- The reference fork does not need any of this on devices where the node is world-writable.
|
||||
|
||||
## vk-fsr4 (han39835/vk-fsr4, GPL-3.0): FSR 4 INT8 on the GPU, no NPU
|
||||
|
||||
An implicit Vulkan layer plus a drop-in replacement for AMD's `amd_fidelityfx_upscaler_vk` provider. It runs FSR 4.1.2
|
||||
as INT8 compute shaders on any Vulkan GPU with `shaderInt8` and `shaderIntegerDotProduct` (DP4a), and keeps the
|
||||
cooperative-matrix FP8 path for RDNA 3/4. Aimed at AMD and Linux, but nothing in the INT8 path is vendor specific.
|
||||
|
||||
- **Assets:** 31 MB of precompiled SPIR-V for INT8 (1080, 2160 and 4320 tiers, each in `native` and `ultraperf`) plus
|
||||
quantised weights. The DXIL from AMD's DLL was converted to SPIR-V at build time with `dxil-spirv`, which is not
|
||||
linked into the provider. The tools to repeat that are in the repo (`tools/extract`, `tools/convert`).
|
||||
- **Two entry points.** As an FFX provider, games that already call FSR 3/4 through the FFX API get FSR 4 with the
|
||||
game's own motion vectors, depth and jitter: the exact inputs, and the most robust option. As a layer without the
|
||||
API (`F4_MV=1`), it guesses which descriptor holds the motion vectors by fingerprinting Unreal TSR layouts. The
|
||||
author says other engines "may or may not match", so only the provider mode is worth building on.
|
||||
- **Licence, checked:** the author's claim that the 4.1.2 DLL is MIT licensed holds up. AMD's FidelityFX SDK 2.4.0
|
||||
`license.md` starts with a restrictive default (binary-only redistribution, no reverse engineering) "except as noted
|
||||
below". It then lists the files "subject to" an MIT licence, and that list includes
|
||||
`signedbin/amd_fidelityfx_upscaler_dx12.dll` and `amd_fidelityfx_upscaler_vk.dll`. So the 4.1.x shaders and weights
|
||||
are redistributable with the MIT notice, which removes the AMD half of the earlier licence concern for that version.
|
||||
Which SDK version a given weights file came from still has to be pinned (the repo pins 4.1.2.4555 by SHA-256).
|
||||
Qualcomm's QNN libraries are a separate matter. This is a reading of the licence file, not legal advice.
|
||||
- **Frame generation:** FSR 4.0.2 ML frame generation is bundled but needs RDNA 4 WMMA, so it is not usable here.
|
||||
- **Fit with DroidDeck:** GPL-3.0, same as DroidDeck. The provider route would sit in the guest, in front of
|
||||
vkd3d-proton, where the game's FFX calls arrive. It needs no NPU access, so it works on the Thor.
|
||||
- **Risk to check first:** the INT8 plan marks most passes `require_wave32`. Adreno runs 64 or 128 wide waves, so
|
||||
either the passes can run at those widths or they need the variants the Winlator fork's Adreno path uses
|
||||
(`dvj5411/fsr4vk`). Also unmeasured: INT8 FSR 4 on a handheld GPU may cost more than it saves at 1080p to 4K.
|
||||
|
||||
## Built so far
|
||||
|
||||
- `gpu/NpuInfo.kt`: maps the SoC model or board platform to a Hexagon generation (v68 to v81, with the VTCM size the
|
||||
reference caps `vtcmSizeInMB` to), checks whether the app's uid can open the FastRPC node (or the DSP service that
|
||||
can hand it over), and whether the QNN libraries are bundled. Shown as an "NPU" section in Device info.
|
||||
- `NpuInfoTest`.
|
||||
|
||||
## Next steps, in order
|
||||
|
||||
1. Create an unsigned PD on the brokered descriptor (`INIT_CREATE`, with the DSP-side `fastrpc_shell_unsigned_3`) and
|
||||
invoke one remote call. Qualcomm's open-source userspace library (`quic/fastrpc`, BSD-3) implements this; it would
|
||||
be built as the app's own `libcdsprpc.so`, with the device open replaced by the binder call above. QNN stubs
|
||||
resolve `libcdsprpc.so` from the app's library directory, so they would pick it up unchanged.
|
||||
2. Run a QNN HTP graph with the user's own QAIRT libraries (v79 skel for the 8 Elite) to prove an end-to-end NPU run.
|
||||
3. Check the binder route on an enforcing 8 Elite build and on an 8 Elite Gen 5 device. Thor (v73) has no route at all.
|
||||
4. Decide the hook point. Guest-side (Winlator's approach) is the only one that can run FSR 4; compositor-side
|
||||
limits it to spatial super-resolution.
|
||||
5. GPU-only FSR 4.1.2 INT8 (DP4a) as an FFX provider in the guest (see vk-fsr4), since it needs no NPU access and
|
||||
exercises the same plumbing. First measure: wave size on Adreno, and cost per frame on the Thor.
|
||||
6. Per-architecture QNN cache directories (`v73/`, `v75/`, `v79/`, `v81/`) and a fallback to the GPU path whenever
|
||||
`NpuInfo.usable` is false.
|
||||
7. Pin the exact AMD SDK version for any weights that ship (4.1.2.4555 is MIT per the SDK 2.4.0 licence file), keep
|
||||
the MIT notice with them, and review Qualcomm's QNN licence separately before anything of theirs is bundled or
|
||||
downloaded.
|
||||
@@ -29,6 +29,11 @@ echo "$(date +%H:%M:%S) $verb $EXE ($VERSION, uid $(id -u), DISPLAY ${DISPLAY:-u
|
||||
# Keep Steam's game identity, DroidDeck's input/display/driver/sync settings and its game environment (the names
|
||||
# ../proton lists in DROIDDECK_BIONIC_KEEP); drop the rest of the glibc guest's environment.
|
||||
KEEP=" ${DROIDDECK_BIONIC_KEEP:-} "
|
||||
# The built-in DirectAudio driver reads DroidDeck's AUDIO_DIRECT_* settings (the microphone switch among them) under
|
||||
# the BANNER_ names droiddeck-proton gives them for Proton.
|
||||
for v in $(env | sed -n 's/^\(AUDIO_DIRECT_[A-Za-z0-9_]*\)=.*/\1/p'); do
|
||||
eval "export BANNER_$v=\"\$$v\""
|
||||
done
|
||||
for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
|
||||
case "$KEEP" in *" $v "*) continue ;; esac
|
||||
case "$v" in
|
||||
@@ -36,7 +41,7 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
|
||||
ANDROID_*|BOOTCLASSPATH|DEX2OATBOOTCLASSPATH|SYSTEMSERVERCLASSPATH|EXTERNAL_STORAGE|ASEC_MOUNTPOINT) ;;
|
||||
FAKE_*|SDL_*|DD_WIDTH|DD_HEIGHT|DD_VK_DRIVER|WINEDLLOVERRIDES) ;;
|
||||
DISPLAY|GAMESCOPE_WAYLAND_DISPLAY|FEX_*) ;;
|
||||
TU_DEBUG|MESA_NO_ERROR|DXVK_CONFIG|DXVK_HUD|DROIDDECK_FORCE_SSBS) ;;
|
||||
TU_DEBUG|MESA_NO_ERROR|DXVK_CONFIG|DXVK_HUD|DROIDDECK_FORCE_SSBS|BANNER_AUDIO_DIRECT_*) ;;
|
||||
mesa_glthread|vblank_mode|ZINK_*|GALLIUM_HUD|GALLIUM_THREAD) ;;
|
||||
DD_SYNC|DD_FSYNC_FIRST|DD_SYNC_FALLBACK|PROTON_NO_ESYNC|PROTON_NO_FSYNC|PROTON_NO_NTSYNC|WINEESYNC) ;;
|
||||
PROTON_USE_D7VK) ;;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="dev.probe.npu">
|
||||
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="34"/>
|
||||
<application android:label="npuprobe" android:hasCode="false" android:debuggable="true">
|
||||
<uses-native-library android:name="libcdsprpc.so" android:required="false"/>
|
||||
<activity android:name="android.app.NativeActivity" android:exported="true">
|
||||
<meta-data android:name="android.app.lib_name" android:value="npuprobe"/>
|
||||
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds a Java-less NativeActivity APK that asks the vendor dspservice for a FastRPC fd and probes it.
|
||||
# Usage: build.sh <out.apk>; then: adb install -r out.apk; adb shell am start -n dev.probe.npu/android.app.NativeActivity
|
||||
# Results go to logcat, tag NPUPROBE.
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
out=${1:?out.apk}
|
||||
bt=$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)
|
||||
work=$(mktemp -d "$HOME/.cache/npu-probe-build.XXXXXX")
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
mkdir -p "$work/lib/arm64-v8a"
|
||||
clang=$(ls -d "$NDK"/toolchains/llvm/prebuilt/*/bin)/aarch64-linux-android34-clang
|
||||
"$clang" -shared -fPIC "$here/probe.c" -o "$work/lib/arm64-v8a/libnpuprobe.so" -llog -landroid -lbinder_ndk -ldl
|
||||
"$bt/aapt2" link -o "$work/base.apk" --manifest "$here/AndroidManifest.xml" -I "$ANDROID_HOME/platforms/android-34/android.jar"
|
||||
(cd "$work" && zip -q -u base.apk lib/arm64-v8a/libnpuprobe.so)
|
||||
"$bt/zipalign" -f 4 "$work/base.apk" "$work/aligned.apk"
|
||||
"$bt/apksigner" sign --ks "$HOME/.android/debug.keystore" --ks-pass pass:android --key-pass pass:android \
|
||||
--ks-key-alias androiddebugkey --out "$out" "$work/aligned.apk"
|
||||
@@ -0,0 +1,100 @@
|
||||
#include <android/native_activity.h>
|
||||
#include <android/log.h>
|
||||
#include <android/binder_ibinder.h>
|
||||
#include <android/binder_parcel.h>
|
||||
#include <android/binder_status.h>
|
||||
#include <dlfcn.h>
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <string.h>
|
||||
#include <dlfcn.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#define L(...) do { char b[600]; snprintf(b, sizeof b, __VA_ARGS__); __android_log_write(ANDROID_LOG_INFO, "NPUPROBE", b); } while (0)
|
||||
static void *oc(void *a){return a;} static void od(void *a){} static binder_status_t ot(AIBinder *b, transaction_code_t c, const AParcel *i, AParcel *o){return STATUS_UNKNOWN_TRANSACTION;}
|
||||
|
||||
|
||||
typedef uint32_t remote_handle;
|
||||
/* Route A: what BananaNative does: dlopen the vendor libcdsprpc from the app namespace. */
|
||||
static void route_dlopen(void) {
|
||||
void *h = dlopen("libcdsprpc.so", RTLD_NOW | RTLD_LOCAL);
|
||||
L("A dlopen(libcdsprpc.so) = %s", h ? "ok" : dlerror());
|
||||
if (!h) return;
|
||||
int (*ctl)(int, void *, uint32_t) = dlsym(h, "remote_handle_control");
|
||||
int (*cap)(int, uint32_t, uint32_t *) = dlsym(h, "fastrpc_get_cap");
|
||||
int (*opn)(int, const char *, remote_handle *) = dlsym(h, "remote_handle_open_domain");
|
||||
L("A syms control=%p get_cap=%p open_domain=%p", ctl, cap, opn);
|
||||
if (ctl) { struct { uint32_t domain, enable; } req = {3, 1}; L("A unsigned-pd control r=%d", ctl(4, &req, sizeof req)); }
|
||||
if (cap) for (uint32_t i = 0; i < 3; i++) { uint32_t v = 0xdead; int r = cap(3, i, &v); L("A get_cap(cdsp,%u) r=0x%x v=%u", i, r, v); }
|
||||
if (opn) { remote_handle rh = 0; errno = 0; int r = opn(3, "file:///libhalide_hexagon_remote_skel.so?halide_hexagon_initialize_kernels&_modver=1.0", &rh); L("A open_domain r=0x%x errno=%d", r, errno); }
|
||||
}
|
||||
static void dump_dev(AParcel *r) {
|
||||
int32_t v[16]; int n = 0;
|
||||
int32_t pos = AParcel_getDataPosition(r), size = AParcel_getDataSize(r);
|
||||
L("reply pos=%d size=%d", pos, size);
|
||||
for (int i = 0; i < 12 && AParcel_getDataPosition(r) < size; i++) { int32_t x; if (AParcel_readInt32(r, &x) != STATUS_OK) break; v[n++] = x; L(" int[%d]=%d (0x%x)", i, x, x); }
|
||||
}
|
||||
|
||||
void ANativeActivity_onCreate(ANativeActivity *a, void *s, size_t n) {
|
||||
L("uid=%d", getuid());
|
||||
route_dlopen();
|
||||
{ const char *nodes[] = {"/dev/fastrpc-cdsp", "/dev/adsprpc-smd"};
|
||||
for (int i = 0; i < 2; i++) { int f = open(nodes[i], O_RDWR | O_CLOEXEC); L("direct open(%s) fd=%d errno=%d", nodes[i], f, errno); if (f >= 0) close(f); } }
|
||||
const char *name = "vendor.qti.hardware.dsp.IDspService/default";
|
||||
AIBinder *(*chk)(const char *) = dlsym(RTLD_DEFAULT, "AServiceManager_checkService");
|
||||
L("dlsym checkService=%p", chk);
|
||||
if (!chk) return;
|
||||
AIBinder *svc = chk(name);
|
||||
L("checkService(%s)=%p", name, svc);
|
||||
if (!svc) { L("no service (denied or absent)"); return; }
|
||||
AIBinder_Class *cs = AIBinder_Class_define("vendor.qti.hardware.dsp.IDspService", oc, od, ot);
|
||||
AIBinder_associateClass(svc, cs);
|
||||
AIBinder_Class *cm = AIBinder_Class_define("vendor.qti.hardware.dsp.IDspManager", oc, od, ot);
|
||||
AParcel *in = NULL, *out = NULL;
|
||||
AIBinder_prepareTransaction(svc, &in);
|
||||
AParcel_writeInt32(in, 3);
|
||||
binder_status_t st = AIBinder_transact(svc, 1, &in, &out, 0);
|
||||
AStatus *as = NULL; AIBinder *mgr = NULL;
|
||||
if (st == STATUS_OK) { AParcel_readStatusHeader(out, &as); AParcel_readStrongBinder(out, &mgr); }
|
||||
L("getNewDSPSession: st=%d mgr=%p", st, mgr);
|
||||
if (!mgr) return;
|
||||
AIBinder_associateClass(mgr, cm);
|
||||
int doms[] = {3, 0};
|
||||
for (int di = 0; di < 2; di++) {
|
||||
AParcel *i2 = NULL, *o2 = NULL;
|
||||
AIBinder_prepareTransaction(mgr, &i2);
|
||||
AParcel_writeInt32(i2, 1); /* non-null */
|
||||
int32_t start = AParcel_getDataPosition(i2);
|
||||
AParcel_writeInt32(i2, 0); AParcel_writeInt32(i2, doms[di]);
|
||||
int32_t end = AParcel_getDataPosition(i2);
|
||||
AParcel_setDataPosition(i2, start); AParcel_writeInt32(i2, end - start); AParcel_setDataPosition(i2, end);
|
||||
st = AIBinder_transact(mgr, 2, &i2, &o2, 0);
|
||||
L("openSession(domain %d): st=%d", doms[di], st);
|
||||
if (st != STATUS_OK) continue;
|
||||
AStatus *s2 = NULL; AParcel_readStatusHeader(o2, &s2);
|
||||
L(" ex=%d", s2 ? AStatus_getExceptionCode(s2) : -1);
|
||||
int32_t nn, sz, a1, b1, hsz, nf, ni;
|
||||
AParcel_readInt32(o2, &nn); AParcel_readInt32(o2, &sz); AParcel_readInt32(o2, &a1); AParcel_readInt32(o2, &b1);
|
||||
AParcel_readInt32(o2, &hsz); AParcel_readInt32(o2, &nf);
|
||||
L(" nonnull=%d size=%d a=%d b=%d handleSize=%d nfds=%d", nn, sz, a1, b1, hsz, nf);
|
||||
for (int k = 0; k < nf && k < 4; k++) {
|
||||
int fd = -1; binder_status_t rs = AParcel_readParcelFileDescriptor(o2, &fd);
|
||||
char path[256] = "?"; char lp[64]; snprintf(lp, sizeof lp, "/proc/self/fd/%d", fd); ssize_t r = readlink(lp, path, sizeof path - 1); if (r > 0) path[r] = 0;
|
||||
L(" fd[%d]=%d (rs=%d) -> %s", k, fd, rs, path);
|
||||
if (fd >= 0) {
|
||||
struct { uint32_t domain, attr, cap, rsv[4]; } cap;
|
||||
for (uint32_t at = 0; at < 4; at++) { cap.domain = 3; cap.attr = at; cap.cap = 0xdead; memset(cap.rsv, 0, sizeof cap.rsv); errno = 0;
|
||||
int ir = ioctl(fd, _IOWR('R', 13, cap), &cap); L(" GET_DSP_INFO attr=%u r=%d errno=%d cap=%u", at, ir, errno, cap.cap); }
|
||||
errno = 0; int ar = ioctl(fd, _IO('R', 4)); L(" INIT_ATTACH r=%d errno=%d", ar, errno);
|
||||
uint32_t info = 3; errno = 0; int gr = ioctl(fd, _IOWR('R', 8, uint32_t), &info); L(" GETINFO(R,8) r=%d errno=%d info=%u", gr, errno, info);
|
||||
}
|
||||
}
|
||||
AParcel_readInt32(o2, &ni);
|
||||
L(" nints=%d", ni);
|
||||
}
|
||||
L("done");
|
||||
}
|
||||
@@ -444,3 +444,33 @@ starts there as before, but no motion is sent for it. The fake pointer position
|
||||
With the patch, the Duo starts with only the bottom bar under the parked pointer hovered and controller focus on the
|
||||
first tile (4 of 4 starts), and returns from a game the same way (3 of 3). Making 0100 ignore the X server's initial
|
||||
pointer instead was tried and rejected: the centre motion still arrived, and the header or search bar ended up hovered.
|
||||
|
||||
## 0143 wlserver: only the first finger drives the emulated mouse
|
||||
|
||||
In the Hover, Left, Right, Middle and Trackpad touch click modes every finger warped the X pointer and any finger lifting
|
||||
released the click. With a second finger down the pointer jumped between both fingers on every frame while the button
|
||||
stayed held, so a dragged item followed whichever finger moved last, and lifting the second finger dropped it under the
|
||||
first. The first finger of a gesture now owns the emulated mouse: only it moves the pointer and only its lift releases the
|
||||
click. Fingers that land while it is down are ignored, and so are the others once it lifts, until every finger is up.
|
||||
Touches the click modes never claimed (Passthrough, Disabled, no focused surface) still release a held click when they
|
||||
lift, and the nested pointer (`bAlwaysWarpCursor`) moves the pointer as before. `tools/tests/test_gamescope_touch_click_owner.py`
|
||||
compiles the rule from this patch.
|
||||
|
||||
## 0144 steamcompmgr: motion into the screen edge does not decide the pointer hold
|
||||
|
||||
0133 compares the motion gamescope sends with how the X pointer moves. At the edge of the X screen the pointer cannot move
|
||||
further, so a drawn-cursor game whose pointer sat at an edge while touch or mouse motion pushed outward counted as
|
||||
holding the pointer: the hold stayed on, every such frame restarted the 30 frames needed to release it, and touch drags
|
||||
kept turning into relative motion with no button held. The sent motion is now clamped to what the pointer can reach
|
||||
inside the X screen before it is compared, so motion into an edge counts as no motion. A recentring game is detected as
|
||||
before, since its pointer stays away from the edges. `tools/tests/test_gamescope_pointer_hold_edge.py` compiles the rule
|
||||
from this patch with the 0133 rule.
|
||||
|
||||
## 0145 steamcompmgr: touch-down warps do not decide the pointer hold
|
||||
|
||||
In click mode every touch-down warps the X pointer to the finger. 0133 read that jump as the pointer not following the
|
||||
sent motion, so each new stroke on a drawn-cursor game restarted the 30 following frames needed to release the hold.
|
||||
Short strokes never released it, and taps kept landing at the relative pointer instead of under the finger. wlserver now
|
||||
counts its touch-down warps, and a frame that contains one is left out of the hold decision. Touch drags, mouse motion
|
||||
and mouse warps still count, so a drag on a game that follows the pointer releases the hold and a recentring game is
|
||||
still held. `tools/tests/test_gamescope_pointer_hold_touch_down.py` compiles the rule with the 0133 rule.
|
||||
@@ -0,0 +1,75 @@
|
||||
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
|
||||
index 9740875..cb72051 100644
|
||||
--- a/src/wlserver.cpp
|
||||
+++ b/src/wlserver.cpp
|
||||
@@ -3283,6 +3283,38 @@ static void apply_touchscreen_orientation(GamescopePanelOrientation orientation,
|
||||
*y = ty;
|
||||
}
|
||||
|
||||
+struct TouchClickState
|
||||
+{
|
||||
+ std::set<int> ids;
|
||||
+ int nOwner = -1;
|
||||
+};
|
||||
+
|
||||
+static TouchClickState s_TouchClick;
|
||||
+
|
||||
+static bool touch_click_claim( TouchClickState &state, int nTouchId )
|
||||
+{
|
||||
+ if ( state.ids.empty() )
|
||||
+ state.nOwner = nTouchId;
|
||||
+ state.ids.insert( nTouchId );
|
||||
+ return state.nOwner == nTouchId;
|
||||
+}
|
||||
+
|
||||
+static bool touch_click_drives( const TouchClickState &state, int nTouchId )
|
||||
+{
|
||||
+ return state.nOwner == nTouchId;
|
||||
+}
|
||||
+
|
||||
+static bool touch_click_lift( TouchClickState &state, int nTouchId )
|
||||
+{
|
||||
+ const bool bTracked = state.ids.erase( nTouchId ) > 0;
|
||||
+ if ( state.nOwner == nTouchId )
|
||||
+ {
|
||||
+ state.nOwner = -1;
|
||||
+ return true;
|
||||
+ }
|
||||
+ return !bTracked && state.nOwner < 0;
|
||||
+}
|
||||
+
|
||||
void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool bAlwaysWarpCursor, gamescope::IBackendConnector* connector )
|
||||
{
|
||||
assert( wlserver_is_lock_held() );
|
||||
@@ -3333,9 +3365,10 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool
|
||||
}
|
||||
else if ( eMode == gamescope::TouchClickModes::Trackpad )
|
||||
{
|
||||
- wlserver_mousemotion( trackpad_dx, trackpad_dy, time );
|
||||
+ if ( touch_click_drives( s_TouchClick, touch_id ) )
|
||||
+ wlserver_mousemotion( trackpad_dx, trackpad_dy, time );
|
||||
}
|
||||
- else
|
||||
+ else if ( bAlwaysWarpCursor || touch_click_drives( s_TouchClick, touch_id ) )
|
||||
{
|
||||
g_bPendingTouchMovement = true;
|
||||
|
||||
@@ -3389,7 +3422,7 @@ void wlserver_touchdown( double x, double y, int touch_id, uint32_t time, gamesc
|
||||
{
|
||||
return;
|
||||
}
|
||||
- else
|
||||
+ else if ( touch_click_claim( s_TouchClick, touch_id ) )
|
||||
{
|
||||
g_bPendingTouchMovement = true;
|
||||
|
||||
@@ -3417,7 +3450,8 @@ void wlserver_touchup( int touch_id, uint32_t time )
|
||||
|
||||
// Release whatever the touch pressed even if its surface is gone, or the seat keeps the button down.
|
||||
bool bReleasedAny = false;
|
||||
- for ( int i = 0; i < WLSERVER_BUTTON_COUNT; i++ )
|
||||
+ const bool bClickTouch = touch_click_lift( s_TouchClick, touch_id );
|
||||
+ for ( int i = 0; bClickTouch && i < WLSERVER_BUTTON_COUNT; i++ )
|
||||
{
|
||||
if ( wlserver.button_held[ i ] == true )
|
||||
{
|
||||
@@ -0,0 +1,28 @@
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
index e98d320..85af598 100644
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -3245,6 +3245,11 @@ static bool pointer_hold_step( PointerHold &state, bool bConstrained, double flS
|
||||
return state.bHeld;
|
||||
}
|
||||
|
||||
+static double pointer_reach( int nFrom, double flDelta, int nSize )
|
||||
+{
|
||||
+ return std::clamp( nFrom + flDelta, 0.0, double( std::max( nSize - 1, 0 ) ) ) - nFrom;
|
||||
+}
|
||||
+
|
||||
static bool s_bPointerHeld = false;
|
||||
|
||||
static void update_pointer_hold( global_focus_t *pFocus, bool bConstrained, bool bHinted )
|
||||
@@ -3311,7 +3316,10 @@ static void update_pointer_hold( global_focus_t *pFocus, bool bConstrained, bool
|
||||
|
||||
if ( s_bTracking )
|
||||
{
|
||||
- s_bPointerHeld = pointer_hold_step( s_Hold, true, flDX, flDY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
|
||||
+ const xwayland_ctx_t *pCtx = pFocus->cursor->getCtx();
|
||||
+ const double flReachX = pointer_reach( s_nRootX, flDX, pCtx->root_width );
|
||||
+ const double flReachY = pointer_reach( s_nRootY, flDY, pCtx->root_height );
|
||||
+ s_bPointerHeld = pointer_hold_step( s_Hold, true, flReachX, flReachY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -0,0 +1,73 @@
|
||||
diff --git a/src/wlserver.hpp b/src/wlserver.hpp
|
||||
--- a/src/wlserver.hpp
|
||||
+++ b/src/wlserver.hpp
|
||||
@@ -173,6 +173,7 @@
|
||||
double flFollowDY = 0.0;
|
||||
double flSentDX = 0.0;
|
||||
double flSentDY = 0.0;
|
||||
+ uint64_t ulTouchDownWarps = 0;
|
||||
|
||||
bool button_held[ WLSERVER_BUTTON_COUNT ];
|
||||
std::set <uint32_t> touch_down_ids;
|
||||
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
|
||||
--- a/src/wlserver.cpp
|
||||
+++ b/src/wlserver.cpp
|
||||
@@ -3429,6 +3429,7 @@
|
||||
if ( eMode != gamescope::TouchClickModes::Trackpad )
|
||||
{
|
||||
wlserver_mousewarp( tx, ty, time, false, true );
|
||||
+ wlserver.ulTouchDownWarps++;
|
||||
}
|
||||
|
||||
uint32_t button = TouchClickModeToLinuxButton( eMode );
|
||||
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
|
||||
--- a/src/steamcompmgr.cpp
|
||||
+++ b/src/steamcompmgr.cpp
|
||||
@@ -3263,6 +3263,7 @@
|
||||
static bool s_bHinted = false;
|
||||
static const steamcompmgr_win_t *s_pWindow = nullptr;
|
||||
static const struct wlr_pointer_constraint_v1 *s_pConstraint = nullptr;
|
||||
+ static uint64_t s_ulTouchDownWarps = 0;
|
||||
|
||||
wlserver_lock();
|
||||
const double flX = wlserver.mouse_surface_cursorx;
|
||||
@@ -3272,8 +3273,12 @@
|
||||
const struct wlr_pointer_constraint_v1 *pConstraint = wlserver.GetCursorConstraint();
|
||||
wlserver.flSentDX = 0.0;
|
||||
wlserver.flSentDY = 0.0;
|
||||
+ const uint64_t ulTouchDownWarps = wlserver.ulTouchDownWarps;
|
||||
wlserver_unlock();
|
||||
|
||||
+ const bool bTouchDown = ulTouchDownWarps != s_ulTouchDownWarps;
|
||||
+ s_ulTouchDownWarps = ulTouchDownWarps;
|
||||
+
|
||||
if ( !bConstrained || !pFocus->cursor )
|
||||
{
|
||||
s_bTracking = false;
|
||||
@@ -3314,19 +3319,19 @@
|
||||
int nRootY = 0;
|
||||
pFocus->cursor->QueryRootPosition( &nRootX, &nRootY );
|
||||
|
||||
- if ( s_bTracking )
|
||||
+ if ( !s_bTracking )
|
||||
+ {
|
||||
+ s_Hold = PointerHold{};
|
||||
+ s_Hold.bHeld = bHinted;
|
||||
+ s_bPointerHeld = bHinted;
|
||||
+ }
|
||||
+ else if ( !bTouchDown )
|
||||
{
|
||||
const xwayland_ctx_t *pCtx = pFocus->cursor->getCtx();
|
||||
const double flReachX = pointer_reach( s_nRootX, flDX, pCtx->root_width );
|
||||
const double flReachY = pointer_reach( s_nRootY, flDY, pCtx->root_height );
|
||||
s_bPointerHeld = pointer_hold_step( s_Hold, true, flReachX, flReachY, nRootX - s_nRootX, nRootY - s_nRootY, get_time_in_nanos() );
|
||||
}
|
||||
- else
|
||||
- {
|
||||
- s_Hold = PointerHold{};
|
||||
- s_Hold.bHeld = bHinted;
|
||||
- s_bPointerHeld = bHinted;
|
||||
- }
|
||||
|
||||
s_bTracking = true;
|
||||
s_flSeatX = flX;
|
||||
@@ -10,6 +10,7 @@ export SHELL=/bin/bash
|
||||
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
export QTWEBENGINE_DISABLE_SANDBOX=1
|
||||
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
export KWIN_USE_OVERLAYS=0
|
||||
[ -e /etc/mpv/mpv.conf ] || { mkdir -p /etc/mpv && echo gpu-sw=yes >/etc/mpv/mpv.conf; } 2>/dev/null
|
||||
|
||||
@@ -12,6 +12,7 @@ fi
|
||||
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
export QTWEBENGINE_DISABLE_SANDBOX=1
|
||||
if [ -s /etc/ld.so.preload ]; then
|
||||
preload=$(tr -s '\n' ':' < /etc/ld.so.preload)
|
||||
export LD_PRELOAD="${preload%:}${LD_PRELOAD:+:$LD_PRELOAD}" SHARUN_ALLOW_LD_PRELOAD=1
|
||||
|
||||
@@ -324,6 +324,16 @@ def cloud_on(sidecar):
|
||||
def exited(argv, code=0):
|
||||
found = find_store_game(argv)
|
||||
launch_dir = os.environ.get("DD_LAUNCH_DIR", "")
|
||||
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
|
||||
if found is None and launch_dir and compat_data and steam_ea_link(argv):
|
||||
try:
|
||||
game = str(json.loads((Path(compat_data) / STEAM_EA_STATE).read_text()).get("id") or "")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
game = ""
|
||||
if game:
|
||||
ask(Path(launch_dir) / "stores", {"op": "ea-exited", "store": "ea", "id": game}, timeout=1.0)
|
||||
log("steam ea %s exited" % game)
|
||||
return 0
|
||||
if found is not None and launch_dir and str(found[1].get("store")) == "rockstar":
|
||||
ask(Path(launch_dir) / "stores", {"op": "rockstar-exited", "store": "rockstar", "id": str(found[1].get("id"))}, timeout=1.0)
|
||||
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH")
|
||||
@@ -1552,7 +1562,7 @@ def write_licenses(compat_data, licenses):
|
||||
return written
|
||||
|
||||
|
||||
def prepare_ea(folder, sidecar, compat_data, launch_dir):
|
||||
def prepare_ea(folder, sidecar, compat_data, launch_dir, steam=None):
|
||||
game = str(sidecar.get("id"))
|
||||
proton = os.environ.get("DD_STORE_PROTON", "")
|
||||
made = create_prefix(compat_data, proton)
|
||||
@@ -1561,16 +1571,149 @@ def prepare_ea(folder, sidecar, compat_data, launch_dir):
|
||||
hardware, probe = ea_hardware(compat_data, proton) if ready else ({}, "no-prefix")
|
||||
answer = None
|
||||
if launch_dir:
|
||||
answer = ask(Path(launch_dir) / "stores", {"op": "ea-prepare", "store": "ea", "id": game, "hardware": hardware}, timeout=40.0)
|
||||
request = {"op": "ea-prepare", "store": "ea", "id": game, "hardware": hardware}
|
||||
if steam is not None:
|
||||
request["steam"] = steam
|
||||
answer = ask(Path(launch_dir) / "stores", request, timeout=40.0)
|
||||
sidecar = sidecar_at(Path(folder)) or sidecar
|
||||
log("ea %s prefix=%s stub=%s hardware=%s registry=%s touchup=%s" % (
|
||||
game, made, stub, probe, ea_registry(folder, sidecar, compat_data, proton), ea_touchup(folder, sidecar, compat_data, proton)))
|
||||
if answer is None:
|
||||
log("ea %s session=no reason=%s" % (game, "timeout" if launch_dir else "no-channel"))
|
||||
return
|
||||
return None
|
||||
written = write_licenses(compat_data, answer.get("licenses"))
|
||||
log("ea %s session=%s reason=%s lsx=%s licence=%s files=%d" % (
|
||||
game, "yes" if answer.get("ok") else "no", answer.get("reason", ""), answer.get("lsx"), answer.get("license", ""), written))
|
||||
return answer
|
||||
|
||||
|
||||
STEAM_EA_LINK = re.compile(r"(?i)^steam2ea://launchgame/([0-9]+)")
|
||||
STEAM_EA_LAUNCHER = "droiddeck-ea-steam.bat"
|
||||
STEAM_EA_ENV = ".droiddeck-ea-steam-env"
|
||||
STEAM_EA_STATE = ".droiddeck-ea-steam.json"
|
||||
STEAM_EA_CLIENT = "drive_c/Program Files/Electronic Arts/EA Desktop/EA Desktop/EADesktop.exe"
|
||||
STEAM_EA_OFFER = re.compile(r"^(Origin\.OFR\.[0-9]+\.[0-9]+)\.dat$", re.IGNORECASE)
|
||||
REPLACED = 13
|
||||
|
||||
|
||||
def steam_ea_link(argv):
|
||||
for raw in argv:
|
||||
if STEAM_EA_LINK.match(raw.strip().strip('"')):
|
||||
return raw
|
||||
return None
|
||||
|
||||
|
||||
def ea_manifest(folder):
|
||||
path = find_case(folder, "__Installer/installerdata.xml")
|
||||
if path is None or not path.is_file():
|
||||
return None
|
||||
import xml.etree.ElementTree as ET
|
||||
try:
|
||||
text = decode_output(path.read_bytes()).lstrip("\ufeff")
|
||||
root = ET.fromstring(re.sub(r"^\s*<\?xml[^>]*\?>", "", text))
|
||||
except (OSError, ET.ParseError):
|
||||
return None
|
||||
contents = [e.text.strip() for e in root.iter("contentID") if e.text and e.text.strip()]
|
||||
launchers = []
|
||||
for runtime in root.iter("runtime"):
|
||||
for launcher in runtime.iter("launcher"):
|
||||
path_text = (launcher.findtext("filePath") or "").strip()
|
||||
if path_text:
|
||||
launchers.append((path_text, (launcher.findtext("parameters") or "").strip(), (launcher.findtext("trial") or "0").strip() == "1"))
|
||||
launcher = next((l for l in launchers if not l[2]), launchers[0] if launchers else None)
|
||||
version = root.find("buildMetaData/gameVersion")
|
||||
titles = {e.get("locale"): (e.text or "").strip() for e in root.iter("gameTitle") if e.get("locale")}
|
||||
exe = None
|
||||
if launcher is not None:
|
||||
relative = re.sub(r"^\[[^\]]*\]", "", launcher[0]).replace("{installLocation}", "").lstrip("\\/")
|
||||
exe = find_case(folder, relative)
|
||||
return {
|
||||
"contentIds": contents,
|
||||
"exe": exe if exe is not None and exe.is_file() else None,
|
||||
"parameters": launcher[1] if launcher else "",
|
||||
"version": version.get("version", "") if version is not None else "",
|
||||
"title": titles.get("en_US") or next(iter(titles.values()), "") or Path(folder).name,
|
||||
}
|
||||
|
||||
|
||||
def steam_ea_offers(folder):
|
||||
loc = find_case(folder, "__Installer/LOC")
|
||||
try:
|
||||
names = sorted(p.name for p in loc.iterdir()) if loc is not None and loc.is_dir() else []
|
||||
except OSError:
|
||||
names = []
|
||||
return [m.group(1) for m in map(STEAM_EA_OFFER.match, names) if m]
|
||||
|
||||
|
||||
def batch_text(value):
|
||||
return value.replace("%", "%%").replace('"', "")
|
||||
|
||||
|
||||
def batch_arguments(value):
|
||||
return re.sub(r"[\x00-\x1f]+", " ", value).replace("%", "%%")
|
||||
|
||||
|
||||
def steam_ea_launcher(folder, exe, parameters, compat_data):
|
||||
env = windows_path(str(Path(compat_data) / STEAM_EA_ENV))
|
||||
lines = [
|
||||
"@echo off",
|
||||
"setlocal",
|
||||
"rem Written by DroidDeck: starts Steam's copy of an EA game without the EA app.",
|
||||
'cd /d "%s"' % batch_text(windows_path(str(exe.parent))),
|
||||
'if not exist "%s" goto run' % batch_text(env),
|
||||
'for /f "usebackq tokens=1,* delims==" %%%%a in ("%s") do set "%%%%a=%%%%b"' % batch_text(env),
|
||||
'del "%s"' % batch_text(env),
|
||||
":run",
|
||||
'if exist "%s" start "" "%s"' % (EA_STUB, EA_STUB),
|
||||
'"%s"%s %%*' % (batch_text(windows_path(str(exe))), " " + batch_arguments(parameters) if parameters else ""),
|
||||
'set "DD_RC=%errorlevel%"',
|
||||
"taskkill /f /im Origin.exe >nul 2>&1",
|
||||
"exit /b %DD_RC%",
|
||||
]
|
||||
return "\r\n".join(lines) + "\r\n"
|
||||
|
||||
|
||||
def prepare_steam_ea(argv, compat_data, launch_dir):
|
||||
"""Steam's copies of EA games start through the EA app, which does not install here: start the game itself."""
|
||||
folder = Path(os.environ.get("STEAM_COMPAT_INSTALL_PATH") or os.getcwd())
|
||||
if not compat_data:
|
||||
log("steam ea: no prefix, left to the EA app")
|
||||
return 0
|
||||
if (Path(compat_data) / "pfx" / STEAM_EA_CLIENT).is_file():
|
||||
log("steam ea: the EA app is installed in this prefix, left to it")
|
||||
return 0
|
||||
manifest = ea_manifest(folder)
|
||||
offers = steam_ea_offers(folder)
|
||||
if manifest is None or manifest["exe"] is None or not manifest["contentIds"] or not offers:
|
||||
log("steam ea: %s has no EA manifest, launcher or offer, left to the EA app" % folder)
|
||||
return 0
|
||||
if not launch_dir:
|
||||
log("steam ea: no channel to DroidDeck, left to the EA app")
|
||||
return 0
|
||||
exe = manifest["exe"]
|
||||
sidecar = {"store": "ea", "id": offers[0], "title": manifest["title"],
|
||||
"extra": {"contentIds": ",".join(manifest["contentIds"]), "displayName": manifest["title"], "locale": "en_US"}}
|
||||
steam = {"folder": str(folder), "offers": offers, "contentIds": manifest["contentIds"], "title": manifest["title"],
|
||||
"version": manifest["version"], "locale": "en_US", "exe": str(exe.relative_to(folder))}
|
||||
answer = prepare_ea(folder, sidecar, compat_data, launch_dir, steam)
|
||||
env = answer.get("env") if answer and answer.get("ok") else None
|
||||
if not isinstance(env, dict):
|
||||
log("steam ea: no EA session (%s), left to the EA app" % ((answer or {}).get("reason") or "no answer"))
|
||||
return 0
|
||||
data = Path(compat_data)
|
||||
try:
|
||||
secret = data / (STEAM_EA_ENV + ".tmp")
|
||||
secret.write_bytes("".join("%s=%s\r\n" % (k, v) for k, v in env.items()
|
||||
if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", str(k)) and "\n" not in str(v)).encode())
|
||||
os.chmod(secret, 0o600)
|
||||
os.replace(secret, data / STEAM_EA_ENV)
|
||||
(data / STEAM_EA_LAUNCHER).write_bytes(steam_ea_launcher(folder, exe, manifest["parameters"], compat_data).encode())
|
||||
(data / STEAM_EA_STATE).write_text(json.dumps({"id": str(answer.get("id") or offers[0])}))
|
||||
except OSError as error:
|
||||
log("steam ea: launcher not written (%s), left to the EA app" % type(error).__name__)
|
||||
return 0
|
||||
log("steam ea: %s starts %s directly as %s" % (manifest["title"], exe.name, answer.get("id") or offers[0]))
|
||||
return REPLACED
|
||||
|
||||
|
||||
def gog_support_actions(folder):
|
||||
@@ -1705,6 +1848,8 @@ def main(argv):
|
||||
return RAN if subprocess.call(command) == 0 else RAN_FAILED
|
||||
found = find_store_game(argv)
|
||||
if found is None:
|
||||
if steam_ea_link(argv):
|
||||
return prepare_steam_ea(argv, os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/"), os.environ.get("DD_LAUNCH_DIR", ""))
|
||||
return 0
|
||||
folder, sidecar = found
|
||||
store, game = str(sidecar.get("store")), str(sidecar.get("id"))
|
||||
|
||||
@@ -79,6 +79,10 @@ dd_store_launch() {
|
||||
/usr/local/bin/droiddeck-store-launch "$@"
|
||||
rc=$?
|
||||
[ $rc -eq 10 ] && DD_STORE_EXIT=1
|
||||
if [ $rc -eq 13 ]; then
|
||||
DD_STORE_EXIT=1
|
||||
DD_STORE_REPLACE="${STEAM_COMPAT_DATA_PATH%/}/droiddeck-ea-steam.bat"
|
||||
fi
|
||||
[ $rc -eq 11 ] && exit 0
|
||||
[ $rc -eq 12 ] && exit 1
|
||||
return 0
|
||||
@@ -88,6 +92,13 @@ dd_run() {
|
||||
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "${verb:-}"; then
|
||||
set -- /usr/local/bin/droiddeck-steamvr-game "$@"
|
||||
fi
|
||||
if [ -n "${DD_STORE_REPLACE:-}" ]; then
|
||||
local arg replaced=()
|
||||
for arg in "$@"; do
|
||||
case ${arg,,} in steam2ea://*) replaced+=("$DD_STORE_REPLACE") ;; *) replaced+=("$arg") ;; esac
|
||||
done
|
||||
set -- "${replaced[@]}"
|
||||
fi
|
||||
if [ -n "${DD_STORE_EXIT:-}" ]; then
|
||||
trap : INT TERM HUP
|
||||
"$@"
|
||||
@@ -227,6 +238,14 @@ dd_components() {
|
||||
|
||||
DD_GAME_CPUS_SETUP = """
|
||||
dd_game_cpus() {
|
||||
local live=/root/.config/droiddeck/game-cores cpus rest=
|
||||
if [ -f "$live" ] && { IFS= read -r cpus && ! IFS= read -r rest; } <"$live" 2>/dev/null && [ -z "$rest" ] && [ "$(wc -c <"$live" 2>/dev/null)" = "$((${#cpus} + 1))" ]; then
|
||||
[[ -z $cpus || $cpus =~ ^[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*$ ]] || cpus=${DD_GAME_CPUS:-}
|
||||
if [ -z "$cpus" ] && [ -n "${DD_CLIENT_CPUS:-}" ]; then
|
||||
cpus=$(nproc --all 2>/dev/null) && cpus=0-$((cpus - 1)) || cpus=
|
||||
fi
|
||||
if [ -n "$cpus" ]; then export DD_GAME_CPUS=$cpus; else unset DD_GAME_CPUS; fi
|
||||
fi
|
||||
[ -n "${DD_GAME_CPUS:-}" ] || return 0
|
||||
command -v taskset >/dev/null 2>&1 || return 0
|
||||
DD_TASKSET="taskset -c $DD_GAME_CPUS"
|
||||
|
||||
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user