mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dde16896c6 |
No files matched your search
@@ -25,7 +25,6 @@
|
||||
#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>
|
||||
@@ -712,19 +711,6 @@ 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;
|
||||
@@ -1181,7 +1167,6 @@ __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
|
||||
@@ -1555,12 +1540,6 @@ __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);
|
||||
@@ -1733,8 +1712,7 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg)
|
||||
int32_t axes[8] = {};
|
||||
DeckExtras extras;
|
||||
while (live_pad_type() == PAD_TYPE_DECK) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -1744,7 +1722,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;
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -1850,8 +1828,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
||||
SonyTouch touch;
|
||||
const uint64_t start_us = monotonic_us();
|
||||
while (live_pad_type() == type) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -1861,7 +1838,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;
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
sleep_us(controller_report_interval_us(DECK_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -2060,8 +2037,7 @@ __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) {
|
||||
bool fresh = read_snapshot(self->ring, snap);
|
||||
if (fresh && snap.generation == ring_generation(self->ring)) {
|
||||
if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) {
|
||||
buttons = snap.buttons;
|
||||
memcpy(axes, snap.axes, sizeof(axes));
|
||||
}
|
||||
@@ -2072,7 +2048,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;
|
||||
report_wait(self->ring, fresh, snap.write_seq, controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
|
||||
sleep_us(controller_report_interval_us(TRITON_REPORT_INTERVAL_US));
|
||||
}
|
||||
syscall(SYS_close, self->peer);
|
||||
munmap(self->ring, self->mapping_size);
|
||||
@@ -4040,7 +4016,6 @@ 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) {
|
||||
@@ -4062,10 +4037,7 @@ 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) {
|
||||
idle = true;
|
||||
break;
|
||||
}
|
||||
if (events == 0) 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);
|
||||
@@ -4111,14 +4083,9 @@ 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 = idle ? ring_wait(ring, seen, backoff_ns) : nanosleep(&sleep_time, nullptr);
|
||||
int result = nanosleep(&sleep_time, nullptr);
|
||||
guard.lock();
|
||||
if (result < 0) return -1;
|
||||
if (low_latency(LATENCY_CONTROLLER)) backoff_ns = kLowLatencyRingWaitUs * 1000;
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
#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>
|
||||
|
||||
@@ -14,13 +11,6 @@ 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,24 +133,6 @@ 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,7 +4,6 @@
|
||||
#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,16 +311,6 @@ 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,7 +26,6 @@ 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,31 +194,7 @@ 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);
|
||||
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;
|
||||
}
|
||||
void vkp_framegen_device_lost(void) { atomic_store(&g_dev_lost, 1); }
|
||||
|
||||
|
||||
static void destroy_ring(void) {
|
||||
|
||||
@@ -126,23 +126,6 @@ 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,7 +12,6 @@ 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,7 +9,6 @@ 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,19 +73,8 @@ 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(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(GetDeviceQueue) X(CreateSwapchainKHR) X(DestroySwapchainKHR) X(GetSwapchainImagesKHR) \
|
||||
X(CreateCommandPool) X(AllocateCommandBuffers) X(CreateSemaphore) X(CreateFence) \
|
||||
X(DeviceWaitIdle) 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,15 +31,6 @@
|
||||
#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;
|
||||
@@ -56,61 +47,14 @@ 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);
|
||||
|
||||
@@ -574,7 +518,7 @@ static void log_display_driver(void) {
|
||||
g_library_name);
|
||||
}
|
||||
|
||||
static int dev_init_once(void) {
|
||||
static int dev_init(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) {
|
||||
@@ -776,189 +720,6 @@ static int dev_init_once(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);
|
||||
@@ -1455,8 +1216,6 @@ 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));
|
||||
@@ -1608,7 +1367,6 @@ 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; }
|
||||
@@ -1678,12 +1436,11 @@ 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_state == 1 && g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
|
||||
if (g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
|
||||
}
|
||||
|
||||
struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
|
||||
@@ -1733,7 +1490,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -1829,7 +1585,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -1883,34 +1638,13 @@ 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 (!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 (g_dev_state != 1 || !img || !img->map || !data) return;
|
||||
size_t rowbytes = (size_t)img->w * 4;
|
||||
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);
|
||||
@@ -1927,10 +1661,7 @@ 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);
|
||||
}
|
||||
|
||||
@@ -2194,23 +1925,14 @@ 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 || 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;
|
||||
}
|
||||
}
|
||||
|
||||
if (g_dev_state == -2) 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 will try one in-process recovery",
|
||||
where);
|
||||
set_fault("the display GPU was lost (VK_ERROR_DEVICE_LOST in %s); recovery pending", where);
|
||||
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);
|
||||
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;
|
||||
@@ -2435,10 +2157,11 @@ 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 == -1 || g_dev_state == -3) return -1;
|
||||
if (g_dev_state < 0) 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) {
|
||||
@@ -2783,7 +2506,7 @@ void vkp_signal_first_frame(void) {
|
||||
}
|
||||
|
||||
int vkp_update_map(int scene_w, int scene_h) {
|
||||
if (dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
if (g_dev_state == -2 || 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;
|
||||
@@ -2857,7 +2580,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 || dev_init() != 0) {
|
||||
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
|
||||
if (wait_fd >= 0) close(wait_fd);
|
||||
return -1;
|
||||
}
|
||||
@@ -2920,9 +2643,11 @@ 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 ||
|
||||
dev_init() != 0)
|
||||
g_dev_state == -2 || 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,7 +6960,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
|
||||
if (runtimeRemovalBlocked) return
|
||||
if (!hasFocus) {
|
||||
cancelTouchGestures()
|
||||
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
|
||||
if (::touchpad.isInitialized) touchpad.cancel()
|
||||
if (::scrollTouch.isInitialized) scrollTouch.cancel()
|
||||
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
|
||||
timed(folder) { for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true) }
|
||||
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
|
||||
timed(folder) { scanGame(context, folder, out, single = entry, reuse = true) }
|
||||
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,15 +250,6 @@ 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
|
||||
@@ -573,10 +564,8 @@ 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 = listingFile(context)
|
||||
val file = File(context.filesDir, "session/added-games.json")
|
||||
if (!file.isFile) return null
|
||||
val entries = org.json.JSONArray(file.readText())
|
||||
(0 until entries.length()).mapNotNull { i ->
|
||||
@@ -586,7 +575,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 = listingFile(context).apply { parentFile?.mkdirs() }
|
||||
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
|
||||
val json = StringBuilder("[")
|
||||
games.forEachIndexed { i, g ->
|
||||
if (i > 0) json.append(',')
|
||||
@@ -607,24 +596,10 @@ object AddedGames {
|
||||
if (games.isNotEmpty() || i > 0) json.append(',')
|
||||
json.append(entry.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)
|
||||
}
|
||||
}
|
||||
file.writeText(json.append(']').toString())
|
||||
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,31 +1,17 @@
|
||||
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 = {}) {
|
||||
@@ -37,56 +23,10 @@ object AddedGamesPublisher {
|
||||
if (now) work.run() else worker.execute(work)
|
||||
}
|
||||
|
||||
fun republish(context: Context): List<AddedGames.Game> {
|
||||
fun republish(context: Context) {
|
||||
val games = AddedGames.scan(context)
|
||||
AddedGames.writeListing(context, games)
|
||||
val arch = SessionPrefs.activeSteamClientArch(context)
|
||||
val arch = com.droiddeck.launcher.session.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,12 +51,11 @@ object GameExePicker {
|
||||
val entries = dir.listFiles()?.sortedBy { it.name.lowercase() } ?: continue
|
||||
for (f in entries) {
|
||||
if (visited >= WALK_BUDGET) break@walk
|
||||
val attrs = attributes(f) ?: continue
|
||||
if (attrs.isSymbolicLink) continue
|
||||
if (attrs.isDirectory) {
|
||||
if (isLink(f)) continue
|
||||
if (f.isDirectory) {
|
||||
visited++
|
||||
if (depth < MAX_DEPTH && !skipDir(f, f.relativeTo(folder).invariantSeparatorsPath)) next.add(f)
|
||||
} else if (attrs.isRegularFile && f.name.endsWith(".exe", ignoreCase = true)) {
|
||||
} else if (f.isFile && f.name.endsWith(".exe", ignoreCase = true)) {
|
||||
visited++
|
||||
if (!JUNK_EXE_RE.matches(f.nameWithoutExtension)) found.add(f to depth)
|
||||
}
|
||||
@@ -99,9 +98,7 @@ object GameExePicker {
|
||||
return SKIP_PATHS.any { rel == it || rel.endsWith("/$it") }
|
||||
}
|
||||
|
||||
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 isLink(f: File): Boolean = runCatching { java.nio.file.Files.isSymbolicLink(f.toPath()) }.getOrDefault(false)
|
||||
|
||||
private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
|
||||
}
|
||||
@@ -2,7 +2,6 @@ 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
|
||||
|
||||
@@ -25,7 +24,6 @@ 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
|
||||
@@ -127,11 +125,8 @@ class DirectTouchHold(
|
||||
upX = event.x
|
||||
upY = event.y
|
||||
liftId = event.getPointerId(event.actionIndex)
|
||||
val wait = MIN_PRESS_MS - (SystemClock.uptimeMillis() - forwardedAt)
|
||||
if (wait > 0L) {
|
||||
liftPending = true
|
||||
handler.postDelayed(lift, wait)
|
||||
} else lift.run()
|
||||
liftPending = true
|
||||
handler.postDelayed(lift, LIFT_MS)
|
||||
}
|
||||
MotionEvent.ACTION_CANCEL -> cancel()
|
||||
}
|
||||
@@ -141,10 +136,9 @@ class DirectTouchHold(
|
||||
private fun forwardDown() {
|
||||
touch.down(downId, downX, downY)
|
||||
forwarded = true
|
||||
forwardedAt = SystemClock.uptimeMillis()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MIN_PRESS_MS = 50L
|
||||
const val LIFT_MS = 50L
|
||||
}
|
||||
}
|
||||
@@ -149,8 +149,6 @@ public class FakeInputWriter {
|
||||
|
||||
private static native void nativeStoreFence();
|
||||
|
||||
private static native void nativeWake(ByteBuffer ring, int offset);
|
||||
|
||||
public static void storeFence() {
|
||||
nativeStoreFence();
|
||||
}
|
||||
@@ -457,7 +455,6 @@ public class FakeInputWriter {
|
||||
writeSnapshotLocked(ring);
|
||||
nativeStoreFence();
|
||||
ring.putLong(RING_WRITE_SEQ_OFFSET, writeSeq);
|
||||
nativeWake(ring, RING_WRITE_SEQ_OFFSET);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ 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"
|
||||
@@ -109,12 +108,10 @@ object GameEnvironmentStore {
|
||||
@Synchronized
|
||||
fun publish(
|
||||
context: Context,
|
||||
config: GameEnvironment.Config? = null,
|
||||
config: GameEnvironment.Config = read(context),
|
||||
gameDebugLogsOverride: Boolean? = null,
|
||||
) {
|
||||
publishGameCores(context)
|
||||
val stored = config ?: read(context)
|
||||
val resolved = stored.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + stored.shared)
|
||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
||||
val json = encode(resolved)
|
||||
val dxvk = TextureFiltering.dxvkOptions(
|
||||
SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context),
|
||||
@@ -143,26 +140,6 @@ 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)
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
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,7 +1008,6 @@ 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)
|
||||
@@ -1735,7 +1734,6 @@ 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),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1756,7 +1754,6 @@ object SessionPrefs {
|
||||
.putInt("customThemeSignal", colors.signal)
|
||||
.putInt("customThemeGood", colors.good)
|
||||
.putInt("customThemeError", colors.error)
|
||||
.putInt("customThemeWarning", colors.warning)
|
||||
.apply()
|
||||
}
|
||||
|
||||
|
||||
@@ -693,14 +693,12 @@ class SessionService : Service() {
|
||||
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
|
||||
}
|
||||
if (steamHere || noSteamGame) {
|
||||
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) }
|
||||
}
|
||||
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) }
|
||||
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.
|
||||
@@ -1888,11 +1886,21 @@ class SessionService : Service() {
|
||||
File(directory, STEAM_GAME_REQUEST + ".tmp").delete()
|
||||
}
|
||||
|
||||
private fun killGuestLeftovers(ended: File?) {
|
||||
private fun killGuestLeftovers() {
|
||||
val me = android.os.Process.myPid()
|
||||
val rootfs = try { File(filesDir, "linuxfs").canonicalPath } catch (e: Exception) { return } + "/"
|
||||
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")
|
||||
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")
|
||||
}
|
||||
|
||||
private fun killStragglers() {
|
||||
@@ -2378,7 +2386,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(ended)
|
||||
killGuestLeftovers()
|
||||
pruneSystemVulkanRuntime()
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
if (launcherEnded) importLauncherGames()
|
||||
|
||||
@@ -19,33 +19,25 @@ 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 }): Boolean {
|
||||
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }) {
|
||||
val wanted = games.filter(include)
|
||||
if (wanted.isEmpty()) return true
|
||||
if (!clientRunning()) return false
|
||||
if (wanted.isEmpty() || !clientRunning()) return
|
||||
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, missed = 0;
|
||||
let added = 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++; else missed++;
|
||||
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++;
|
||||
}
|
||||
return JSON.stringify({ added, missed });
|
||||
return added;
|
||||
})()
|
||||
""".trimIndent()
|
||||
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
|
||||
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")
|
||||
}
|
||||
|
||||
fun ensure(context: Context, name: String, exe: String, dir: String, compat: Boolean, appId: Long? = null): Long? {
|
||||
|
||||
@@ -73,72 +73,35 @@ 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 (folder, recorded) = installed(app, id) ?: return JSONObject().put("ok", false).put("reason", "not-installed")
|
||||
val reply = JSONObject().put("ok", false)
|
||||
val (folder, recorded) = installed(app, id) ?: return reply.put("reason", "not-installed")
|
||||
val sidecar = backfill(folder, recorded)
|
||||
runCatching { com.droiddeck.launcher.stores.StoreLaunch.refreshLauncher(folder, sidecar) }
|
||||
File(folder, ENV_FILE).delete()
|
||||
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 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 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 lsx = EaLsx.start(app, EaLsx.Game(id, contentId, game.title, game.version, locale, hardware, hashVersion, opaque,
|
||||
System.currentTimeMillis() + (lifetime - 30) * 1000L, game.contentIds))
|
||||
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 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) + game.licenceIds).map { it.trim() }.filter { it.isNotEmpty() }.distinct()
|
||||
val ids = (listOf(contentId) + sidecar.extra["contentIds"].orEmpty().split(',')).map { it.trim() }.filter { it.isNotEmpty() }.distinct()
|
||||
if (hardware == null) notes += "no-hardware" else {
|
||||
val hash = EaOoa.machineHash(hardware, hashVersion)
|
||||
for (content in ids) {
|
||||
@@ -162,7 +125,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) to env
|
||||
return reply.put("ok", true).put("lsx", lsx).put("license", licenseNote).put("licenses", licenses)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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.withFrameNanos
|
||||
import androidx.compose.runtime.withFrameMillis
|
||||
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) { withFrameNanos { }; continue }
|
||||
if (clock.page == Size.Zero) { withFrameMillis { }; 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,13 +108,8 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
clock.wall = 0f
|
||||
return@LaunchedEffect
|
||||
}
|
||||
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)
|
||||
withFrameMillis { now ->
|
||||
val dt = if (last < 0) 0f else min(50f, (now - last) / Motion.scale)
|
||||
last = now
|
||||
clock.intro += dt
|
||||
clock.wall += dt
|
||||
@@ -122,41 +117,34 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
|
||||
val before = clock.ball
|
||||
clock.ball += dt
|
||||
|
||||
var x = clock.at.x
|
||||
var y = clock.at.y
|
||||
var x = clock.at.x + vx * dt / 1000f
|
||||
var y = clock.at.y + vy * dt / 1000f
|
||||
val hw = f.ball
|
||||
val hh = f.ball
|
||||
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) }
|
||||
}
|
||||
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,7 +96,8 @@ import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onPlaced
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
|
||||
internal val AttentionAmber: Color @Composable get() = LocalPalette.current.warning
|
||||
|
||||
internal val AttentionAmber = Color(0xFFFFB547)
|
||||
|
||||
@Composable
|
||||
internal fun BottomBar(
|
||||
@@ -307,7 +308,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(pal.warning),
|
||||
.size(8.dp).clip(CircleShape).background(AttentionAmber),
|
||||
)
|
||||
if (count > 0) Text(
|
||||
if (count > 9) "9+" else count.toString(),
|
||||
|
||||
@@ -1254,7 +1254,6 @@ 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,18 +82,7 @@ import kotlinx.coroutines.withContext
|
||||
private const val WALL_MIN_GAMES = 4
|
||||
private const val WALL_DISTINCT = 40
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
private const val DRIFT_STEP_NS = 15_000_000L
|
||||
|
||||
@Composable
|
||||
internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) {
|
||||
@@ -292,7 +281,7 @@ internal fun TiltedWall(
|
||||
var shown = 0L
|
||||
while (true) withFrameNanos { now ->
|
||||
if (shown == 0L) shown = now
|
||||
else if (IdleFrames.due(now)) {
|
||||
else if (now - shown >= DRIFT_STEP_NS) {
|
||||
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 warning: Color = Color(0xFFFFB547),
|
||||
val good: Color, val error: Color = Color(0xFFFF8A80),
|
||||
)
|
||||
|
||||
data class CustomThemeColors(
|
||||
@@ -54,7 +54,6 @@ 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 {
|
||||
@@ -145,7 +144,6 @@ 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)
|
||||
@@ -166,7 +164,6 @@ object Themes {
|
||||
signal = Color(colors.signal),
|
||||
good = Color(colors.good),
|
||||
error = Color(colors.error),
|
||||
warning = Color(colors.warning),
|
||||
)
|
||||
|
||||
fun current(context: Context): Palette {
|
||||
@@ -232,9 +229,7 @@ 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 context = LocalContext.current
|
||||
remember(context) { Themes.loadGradient(context) }
|
||||
val id = theme ?: SessionPrefs.theme(context)
|
||||
val id = theme ?: SessionPrefs.theme(LocalContext.current)
|
||||
if (id == Themes.INNER_GAMER) InnerGamerHue(Themes.rgbSpeed)
|
||||
val p = Themes.byId(id)
|
||||
val scheme = darkColorScheme(
|
||||
|
||||
@@ -4299,7 +4299,6 @@
|
||||
<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,7 +4179,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4219,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4179,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4178,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4109,6 @@
|
||||
<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,7 +4178,6 @@
|
||||
<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,7 +4109,6 @@
|
||||
<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,7 +4109,6 @@
|
||||
<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,7 +4109,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4219,6 @@
|
||||
<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,7 +1812,6 @@
|
||||
<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,7 +1820,6 @@
|
||||
<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,7 +4179,6 @@
|
||||
<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,7 +4220,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4109,6 @@
|
||||
<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,7 +4139,6 @@
|
||||
<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,7 +4219,6 @@
|
||||
<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,7 +4109,6 @@
|
||||
<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,7 +4109,6 @@
|
||||
<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,7 +4109,6 @@
|
||||
<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,7 +4109,6 @@
|
||||
<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,7 +2028,6 @@
|
||||
<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>
|
||||
|
||||
@@ -145,15 +145,4 @@ 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))
|
||||
}
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
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\""))
|
||||
}
|
||||
}
|
||||
@@ -201,25 +201,6 @@ 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,43 +36,7 @@ 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() {
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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"))
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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,7 +13,6 @@ 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. |
|
||||
|
||||
@@ -27,5 +26,6 @@ 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.
|
||||
@@ -294,7 +294,14 @@ adds `tabtip.exe=d` to `WINEDLLOVERRIDES` unless the launch has `SteamDeck=1`
|
||||
or the overrides already set `tabtip.exe` (also as `*tabtip.exe` or
|
||||
`tabtip.exe.dll`): Proton's tabtip only opens Steam's
|
||||
keyboard with `SteamDeck=1`, but it always runs UI Automation queries inside the
|
||||
focused game, which crash games that answer them (Godot 4.5 AccessKit). Malformed
|
||||
focused game, which crash games that answer them (Godot 4.5 AccessKit). A game
|
||||
launch also sets `PROTON_DISABLE_NVAPI=1` unless the launch already sets
|
||||
`PROTON_DISABLE_NVAPI`, `PROTON_FORCE_NVAPI` or `DXVK_ENABLE_NVAPI`. Proton turns
|
||||
NVAPI off itself when `/proc/modules` lists no NVIDIA driver, but Android does
|
||||
not let it read that file, so NVAPI stayed on and its `nvcuda=b` override loaded
|
||||
Wine's nvcuda stub, which exports no functions. A game that delay-loads CUDA
|
||||
then stops with `0xc06d007f` (procedure not found) instead of seeing that there
|
||||
is no nvcuda.dll, as it would on Windows without an NVIDIA driver. Malformed
|
||||
configuration falls back to the inherited environment without evaluating its
|
||||
contents. Both component and environment selection normalize signed non-Steam
|
||||
prefix IDs to unsigned IDs.
|
||||
|
||||
@@ -35,11 +35,10 @@ GAMESCOPE_COMMIT=8f212644c46460549035971ab914421180f61a7c
|
||||
GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-images-under-limiter.patch"
|
||||
VULKAN_HEADERS_TAG=v1.4.341
|
||||
# The bionic DroidDeck-Proton layer the pack is made for: linked against (libwayland-client) and checked against, not packed.
|
||||
# Layer v18: DroidDeck-Proton 11-14.1 (Valve Wine a47c73f52fd7, as GE-Proton11-14), the build Bannerlator ships; it
|
||||
# carries the ARM64EC code-map and unwind fixes the 12.8 layer had (5ebfaa6f, 2515a989, e88fab40).
|
||||
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261124-v18/DroidDeck-proton-11.0-14.1-arm64ec.wcp
|
||||
LAYER_SHA256=bf94176180e96584185835f9e80b168666f9fa752aa9583cfedb8fe493134ff6 # proton-wine 1a5735e7 (run 45926928349)
|
||||
LAYER_VERSION=14.1
|
||||
# Layer v16 (067c719d) plus the ARM64EC code-map fix for 39-bit hosts (d4c9ffa7, run 44291095238).
|
||||
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261118-v16-unwind/DroidDeck-Proton-11.0-12.8-arm64ec.wcp
|
||||
LAYER_SHA256=3cc74b877bc8707d75aa2cc22e335373b6a6c0b6b1937c7b3c2cd98e55de2e89 # proton-wine d48e30a1 (a188791d + fecf7376 on d4c9ffa7)
|
||||
LAYER_VERSION=12.8
|
||||
# Packed into the DroidDeck-Bionic tool next to the layer: FEX with Android-built unix libraries, and default
|
||||
# DXVK / VKD3D-Proton (DroidDeck components can swap these in files/lib/wine/{dxvk,vkd3d-proton} later).
|
||||
FEX_URL=https://github.com/The412Banner/Nightlies/releases/download/FEXCore-2611.1/FEXCore-2611.1-unix.wcp
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# GStreamer plugins packed for winegstreamer (game video/audio), from the imagefs's lib/gstreamer-1.0 by name
|
||||
# (libgst<name>.so): Proton's usual set as far as this imagefs has it (no vpx; videoconvert+videoscale are videoconvertscale).
|
||||
coreelements
|
||||
debug
|
||||
app
|
||||
audioconvert
|
||||
audiorate
|
||||
|
||||
@@ -29,11 +29,6 @@ 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
|
||||
@@ -41,7 +36,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|BANNER_AUDIO_DIRECT_*) ;;
|
||||
TU_DEBUG|MESA_NO_ERROR|DXVK_CONFIG|DXVK_HUD|DROIDDECK_FORCE_SSBS) ;;
|
||||
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) ;;
|
||||
@@ -109,9 +104,6 @@ export NTSYNC_SHM=$COMPAT/ntsync-shm
|
||||
# DroidDeck's Force SSBS (its glibc libssbs.so preload) is bionic Wine's own WINE_FORCE_SSBS
|
||||
on "${DROIDDECK_FORCE_SSBS:-}" && export WINE_FORCE_SSBS=1
|
||||
export HODLL=libwow64fex.dll WINEDEBUG=err+all,fixme-all
|
||||
# The network adapter list (GetAdaptersAddresses) from the layer's getifaddrs code: its default if_nameindex code never
|
||||
# answered here, and the Paradox Launcher (Europa Universalis IV) waited on it forever.
|
||||
export WINE_NEW_NDIS=${WINE_NEW_NDIS:-1}
|
||||
export XENVIRONMENT=$TOOL/bionic/Xdefaults
|
||||
# The adapter's Wayland swapchain gets its buffers back from gamescope later than DroidDeck-Proton's Turnip does;
|
||||
# with gamescope's default three images the game waits for one about a fifth of the time at high frame rates.
|
||||
@@ -309,21 +301,6 @@ if [ "$verb" != runinprefix ] && prefix_busy; then
|
||||
fi
|
||||
prefix_busy || rm -f "$NTSYNC_SHM".v*
|
||||
|
||||
# Steam's running client, as a game's steam_api checks it: Proton names its steam.exe (the prefix's first program,
|
||||
# alive while the game runs), which this tool does not start. Here the first program is the one Steam started, so a
|
||||
# launcher that starts the game and quits (EU4's dowser.exe) left a game that reported "Steam not detected". The
|
||||
# PID is the one this tool's own prefixes carry.
|
||||
steam_pid() {
|
||||
R=$COMPAT/pfx/user.reg
|
||||
[ -f "$R" ] || return 0
|
||||
awk '/^\[/ { on = index($0, "[Software\\\\Valve\\\\Steam\\\\ActiveProcess]") == 1 }
|
||||
on && /^"PID"=dword:/ && $0 != "\"PID\"=dword:0000fffe" { found = 1 } END { exit !found }' "$R" || return 0
|
||||
awk '/^\[/ { on = index($0, "[Software\\\\Valve\\\\Steam\\\\ActiveProcess]") == 1 }
|
||||
on && /^"PID"=dword:/ { print "\"PID\"=dword:0000fffe"; next } { print }' "$R" > "$R.dd-new.$$" && mv -f "$R.dd-new.$$" "$R" &&
|
||||
echo "$(date +%H:%M:%S) Steam's process ID in the registry set to this tool's"
|
||||
}
|
||||
prefix_busy || steam_pid
|
||||
|
||||
# Links into a tool that is gone (an older DroidDeck-Bionic, a deleted DroidDeck-Proton) or to a file it no longer has.
|
||||
# Wine's update cannot write over them, so drivers (network, controller) and other files stay missing. Drop them and
|
||||
# clear both stamps: prepare_prefix relinks this tool's files and Wine's update puts its own back.
|
||||
|
||||
@@ -36,21 +36,6 @@ zpath() {
|
||||
esac
|
||||
}
|
||||
|
||||
# Drive links of the prefix in compatdata folder $1 that name guest paths (DroidDeck-Proton's s: for the Steam library)
|
||||
# -> their Android paths, which this Wine follows. A game's mods on S: were missing otherwise. A session's start
|
||||
# gives them their guest paths back (NativeGuest.relinkPrefixDrives); z: is launch.sh's.
|
||||
android_drives() {
|
||||
local d t a
|
||||
for d in "$1"/pfx/dosdevices/[a-y]:; do
|
||||
[ -L "$d" ] || continue
|
||||
t=$(readlink "$d")
|
||||
case "$t" in /*) ;; *) continue ;; esac
|
||||
a=$(real "$t")
|
||||
[ "$a" = "$t" ] && continue
|
||||
ln -sfn "$a" "$d.dd-new.$$" && mv -fT "$d.dd-new.$$" "$d" && echo "drive ${d##*/} -> $a"
|
||||
done
|
||||
}
|
||||
|
||||
# Where a game launch's log goes in DroidDeck's session folder (Share logs takes that folder): the game's log folder
|
||||
# when Detailed graphics logs made one (droiddeck-game-env), else a folder of its own; nothing for other verbs
|
||||
session_logs() {
|
||||
@@ -124,7 +109,6 @@ print(" ".join(sorted(n for n in names if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*"
|
||||
PY
|
||||
)
|
||||
export DROIDDECK_BIONIC_KEEP
|
||||
[ -n "${STEAM_COMPAT_DATA_PATH:-}" ] && android_drives "$STEAM_COMPAT_DATA_PATH" >&2
|
||||
exec /system/bin/sh "$tool/bionic/launch.sh" "$verb" "$compat" "$exe" ${args[@]+"${args[@]}"} ;;
|
||||
getcompatpath)
|
||||
p=$(real "${1:-}")
|
||||
|
||||
@@ -10,7 +10,6 @@ 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,7 +12,6 @@ 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
|
||||
|
||||
@@ -241,6 +241,13 @@ def keyboard_helper_off(env):
|
||||
return "tabtip.exe off (it only opens Steam's keyboard with SteamDeck=1, and its UI Automation calls crash games)"
|
||||
|
||||
|
||||
def nvapi_off(env):
|
||||
if {"PROTON_DISABLE_NVAPI", "PROTON_FORCE_NVAPI", "DXVK_ENABLE_NVAPI"} & env.keys():
|
||||
return None
|
||||
env["PROTON_DISABLE_NVAPI"] = "1"
|
||||
return "NVAPI and nvcuda off (no NVIDIA driver; Proton cannot read /proc/modules to see that)"
|
||||
|
||||
|
||||
def skip_red_launcher(command):
|
||||
if len(command) > 2 and os.path.basename(command[2]).lower() == "redprelauncher.exe":
|
||||
game = os.path.join(os.path.dirname(command[2]), "bin", "x64", "Cyberpunk2077.exe")
|
||||
@@ -1675,6 +1682,9 @@ def main():
|
||||
note = keyboard_helper_off(env)
|
||||
if note:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
note = nvapi_off(env)
|
||||
if note:
|
||||
print("droiddeck-game-env: " + note, file=sys.stderr)
|
||||
else:
|
||||
path = Path.home() / ".config/droiddeck/game-environment.json"
|
||||
try:
|
||||
|
||||
@@ -324,16 +324,6 @@ 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")
|
||||
@@ -1562,7 +1552,7 @@ def write_licenses(compat_data, licenses):
|
||||
return written
|
||||
|
||||
|
||||
def prepare_ea(folder, sidecar, compat_data, launch_dir, steam=None):
|
||||
def prepare_ea(folder, sidecar, compat_data, launch_dir):
|
||||
game = str(sidecar.get("id"))
|
||||
proton = os.environ.get("DD_STORE_PROTON", "")
|
||||
made = create_prefix(compat_data, proton)
|
||||
@@ -1571,149 +1561,16 @@ def prepare_ea(folder, sidecar, compat_data, launch_dir, steam=None):
|
||||
hardware, probe = ea_hardware(compat_data, proton) if ready else ({}, "no-prefix")
|
||||
answer = None
|
||||
if launch_dir:
|
||||
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)
|
||||
answer = ask(Path(launch_dir) / "stores", {"op": "ea-prepare", "store": "ea", "id": game, "hardware": hardware}, 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 None
|
||||
return
|
||||
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):
|
||||
@@ -1848,8 +1705,6 @@ 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,10 +79,6 @@ 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
|
||||
@@ -92,13 +88,6 @@ 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
|
||||
"$@"
|
||||
@@ -238,14 +227,6 @@ 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"
|
||||
|
||||
@@ -1161,7 +1161,6 @@ int system(const char *command) {
|
||||
|
||||
int status = -1;
|
||||
pid_t pid = start_shell(command, -1, -1, &old, &intr, &quit, 0);
|
||||
if (pid < 0) status = 127 << 8; // as glibc's system() when the shell could not be started
|
||||
if (pid > 0) {
|
||||
while (waitpid(pid, &status, 0) < 0) {
|
||||
if (errno != EINTR) {
|
||||
@@ -1193,52 +1192,28 @@ static pthread_mutex_t g_popen_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static pid_t start_shell(const char *command, int child_fd, int target_fd, const sigset_t *mask,
|
||||
const struct sigaction *intr, const struct sigaction *quit, int close_popen_streams) {
|
||||
// Through posix_spawn(), as glibc does: its child only makes system calls. A forked child running
|
||||
// the exec code here would take locks that another thread of a multithreaded caller may have held
|
||||
// at fork(), and wait for them forever (Steam's popen()s did, and its main loop stalled).
|
||||
posix_spawn_file_actions_t actions;
|
||||
posix_spawnattr_t attr;
|
||||
if (posix_spawn_file_actions_init(&actions) != 0) return -1;
|
||||
if (posix_spawnattr_init(&attr) != 0) {
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
return -1;
|
||||
}
|
||||
int err = 0;
|
||||
pid_t pid = fork();
|
||||
if (pid != 0) return pid;
|
||||
if (intr) sigaction(SIGINT, intr, NULL);
|
||||
if (quit) sigaction(SIGQUIT, quit, NULL);
|
||||
if (mask) sigprocmask(SIG_SETMASK, mask, NULL);
|
||||
if (child_fd >= 0) {
|
||||
// dup2 onto itself clears FD_CLOEXEC in the child (glibc 2.29 and later)
|
||||
err = posix_spawn_file_actions_adddup2(&actions, child_fd, target_fd);
|
||||
if (child_fd == target_fd) {
|
||||
fcntl(target_fd, F_SETFD, 0);
|
||||
} else if (dup2(child_fd, target_fd) < 0) {
|
||||
_exit(127);
|
||||
}
|
||||
}
|
||||
// POSIX: the streams of earlier popen() calls are not open in the new shell
|
||||
for (struct ddnatv_popen *p = g_popen_streams; !err && close_popen_streams && p; p = p->next) {
|
||||
int fd = fileno(p->fp);
|
||||
if (fd >= 0 && fd != target_fd) err = posix_spawn_file_actions_addclose(&actions, fd);
|
||||
if (close_popen_streams) {
|
||||
for (struct ddnatv_popen *p = g_popen_streams; p; p = p->next) {
|
||||
int fd = fileno(p->fp);
|
||||
if (fd >= 0 && fd != target_fd) close(fd);
|
||||
}
|
||||
}
|
||||
short flags = 0;
|
||||
if (!err && mask) {
|
||||
posix_spawnattr_setsigmask(&attr, mask);
|
||||
flags |= POSIX_SPAWN_SETSIGMASK;
|
||||
}
|
||||
// SIGINT and SIGQUIT as they were before system() ignored them: an exec keeps an ignored signal
|
||||
// ignored and puts a handled one back to the default
|
||||
sigset_t defaults;
|
||||
sigemptyset(&defaults);
|
||||
if (intr && intr->sa_handler != SIG_IGN) sigaddset(&defaults, SIGINT);
|
||||
if (quit && quit->sa_handler != SIG_IGN) sigaddset(&defaults, SIGQUIT);
|
||||
if (!err && (intr || quit)) {
|
||||
posix_spawnattr_setsigdefault(&attr, &defaults);
|
||||
flags |= POSIX_SPAWN_SETSIGDEF;
|
||||
}
|
||||
if (!err) err = posix_spawnattr_setflags(&attr, flags);
|
||||
pid_t pid = -1;
|
||||
char *const argv[] = { (char *)"sh", (char *)"-c", (char *)command, NULL };
|
||||
if (!err) err = posix_spawn(&pid, "/bin/sh", &actions, &attr, argv, environ);
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
posix_spawnattr_destroy(&attr);
|
||||
if (err) {
|
||||
errno = err;
|
||||
return -1;
|
||||
}
|
||||
return pid;
|
||||
ddnatv_execve("/bin/sh", argv, environ, 0);
|
||||
_exit(127);
|
||||
}
|
||||
|
||||
FILE *popen(const char *command, const char *type) {
|
||||
|
||||
@@ -6,7 +6,7 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
RUN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-appimage-run"
|
||||
KEYS = ("TU_DEBUG", "DROIDDECK_GAME_TU_DEBUG", "QT_QPA_PLATFORM", "WAYLAND_DISPLAY", "SDL_VIDEODRIVER", "XDG_SESSION_TYPE", "QT_WAYLAND_DISABLE_WINDOWDECORATION", "DISABLE_GAMESCOPE_WSI", "QTWEBENGINE_DISABLE_SANDBOX")
|
||||
KEYS = ("TU_DEBUG", "DROIDDECK_GAME_TU_DEBUG", "QT_QPA_PLATFORM", "WAYLAND_DISPLAY", "SDL_VIDEODRIVER", "XDG_SESSION_TYPE", "QT_WAYLAND_DISABLE_WINDOWDECORATION", "DISABLE_GAMESCOPE_WSI")
|
||||
QUICK = ("usr/lib/libQt6Quick.so.6", "usr/lib/libvulkan.so.1", "usr/plugins/platforms/libqwayland-generic.so")
|
||||
RUN_MODE = {"GAMESCOPE_WAYLAND_DISPLAY": "gamescope-0", "WAYLAND_DISPLAY": "gamescope-0", "DISPLAY": ":0",
|
||||
"QT_QPA_PLATFORM": "xcb", "SDL_VIDEODRIVER": "x11", "XDG_SESSION_TYPE": "x11"}
|
||||
@@ -128,11 +128,6 @@ class AppImageRunTest(unittest.TestCase):
|
||||
self.assertEqual("wayland;xcb", env["QT_QPA_PLATFORM"])
|
||||
|
||||
|
||||
def test_a_web_engine_app_starts_as_root_in_either_session(self):
|
||||
for session in (RUN_MODE, DESKTOP):
|
||||
env, _ = self.launch(session)
|
||||
self.assertEqual("1", env["QTWEBENGINE_DISABLE_SANDBOX"])
|
||||
|
||||
def test_a_program_drops_the_sessions_sysmem_like_a_steam_game(self):
|
||||
env, _ = self.launch(dict(RUN_MODE, TU_DEBUG="sysmem", DROIDDECK_GAME_TU_DEBUG=""))
|
||||
self.assertEqual("unset", env["TU_DEBUG"])
|
||||
|
||||
@@ -65,14 +65,6 @@ class ToolArguments(unittest.TestCase):
|
||||
def test_wine_keeps_the_guest_root(self):
|
||||
self.assertIn('DROIDDECK_GUEST_ROOT) ;;', LAUNCH.read_text())
|
||||
|
||||
def test_directaudio_settings_reach_the_built_in_driver(self):
|
||||
text = LAUNCH.read_text()
|
||||
block = text[text.index('KEEP="'):text.index('export PATH=/system/bin')]
|
||||
script = block + 'env | grep -E "AUDIO_DIRECT_|^OTHER=" | sort\n'
|
||||
env = {'PATH': os.environ['PATH'], 'DROIDDECK_BIONIC_KEEP': 'PATH', 'AUDIO_DIRECT_MIC': '1', 'AUDIO_DIRECT_MS': '60', 'OTHER': 'x'}
|
||||
result = subprocess.run(['sh', '-c', script], env=env, text=True, capture_output=True, check=True)
|
||||
self.assertEqual(['BANNER_AUDIO_DIRECT_MIC=1', 'BANNER_AUDIO_DIRECT_MS=60'], result.stdout.split())
|
||||
|
||||
|
||||
class SessionLogs(unittest.TestCase):
|
||||
SESSION = '/data/user/0/com.droiddeck.launcher/files/logs/2026-11-22-09-steam'
|
||||
@@ -144,53 +136,6 @@ class LaunchLog(unittest.TestCase):
|
||||
self.assertIn('DXVK_LOG_PATH=${DXVK_LOG_PATH:-$COMPAT}', text)
|
||||
|
||||
|
||||
class PrefixFromProton(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.compat = Path(self.tmp.name) / 'compatdata/236850'
|
||||
self.drives = self.compat / 'pfx/dosdevices'
|
||||
self.drives.mkdir(parents=True)
|
||||
|
||||
def test_guest_drive_links_get_android_paths(self):
|
||||
for name, target in (('c:', '../drive_c'), ('s:', '/root/.local/share/Steam'), ('d:', '/mnt/sd/Steam'),
|
||||
('e:', '/storage/emulated/0/Games'), ('z:', '/')):
|
||||
os.symlink(target, self.drives / name)
|
||||
out = proton_function('android_drives "$1"', str(self.compat))
|
||||
links = {p.name: os.readlink(p) for p in self.drives.iterdir()}
|
||||
self.assertEqual({'c:': '../drive_c', 's:': ANDROID + '/root/.local/share/Steam', 'd:': '/storage/1234-5678/Steam/Steam',
|
||||
'e:': '/storage/emulated/0/Games', 'z:': '/'}, links)
|
||||
self.assertEqual(2, len(out.splitlines()))
|
||||
self.assertEqual('', proton_function('android_drives "$1"', str(self.compat)))
|
||||
|
||||
def test_a_prefix_without_drives_is_left_alone(self):
|
||||
self.assertEqual('', proton_function('android_drives "$1"', str(Path(self.tmp.name) / 'compatdata/1')))
|
||||
|
||||
def steam_pid(self, reg):
|
||||
text = LAUNCH.read_text()
|
||||
function = text[text.index('steam_pid() {'):text.index('prefix_busy || steam_pid')]
|
||||
(self.compat / 'pfx/user.reg').write_text(reg)
|
||||
out = subprocess.run(['sh', '-c', function + 'steam_pid'], env=dict(os.environ, COMPAT=str(self.compat)),
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
return out, (self.compat / 'pfx/user.reg').read_text()
|
||||
|
||||
def test_steams_process_id_is_this_tools(self):
|
||||
reg = ('[Software\\\\Valve\\\\Steam\\\\ActiveProcess] 1795314478\n#time=1dd7a2916a0be94\n"PID"=dword:00000020\n'
|
||||
'"SteamPath"="C:\\\\Program Files (x86)\\\\Steam"\n\n[Software\\\\Other] 1\n"PID"=dword:00000020\n')
|
||||
out, after = self.steam_pid(reg)
|
||||
self.assertIn('process ID', out)
|
||||
self.assertEqual(reg.replace('"PID"=dword:00000020', '"PID"=dword:0000fffe', 1), after)
|
||||
out, again = self.steam_pid(after)
|
||||
self.assertEqual(('', after), (out, again))
|
||||
|
||||
def test_a_prefix_without_steams_key_is_unchanged(self):
|
||||
reg = '[Software\\\\Wine] 1\n"PID"=dword:00000020\n'
|
||||
self.assertEqual(('', reg), self.steam_pid(reg))
|
||||
|
||||
def test_the_network_list_uses_getifaddrs(self):
|
||||
self.assertIn('export WINE_NEW_NDIS=${WINE_NEW_NDIS:-1}', LAUNCH.read_text())
|
||||
|
||||
|
||||
class StorePaths(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
DESKTOP = (TOOLS / "linuxfs/desktop/droiddeck-desktop").read_text()
|
||||
PACKAGES = (TOOLS / "ubuntu/packages-desktop.txt").read_text().split()
|
||||
SANDBOXES = ("MOZ_DISABLE_CONTENT_SANDBOX", "MOZ_SHM_NO_SEALS", "QTWEBENGINE_DISABLE_SANDBOX")
|
||||
|
||||
|
||||
class DesktopRootAppsTest(unittest.TestCase):
|
||||
def desktop_environment(self):
|
||||
head = DESKTOP[:DESKTOP.index("\nexport KWIN_COMPOSE=")]
|
||||
env = {k: v for k, v in os.environ.items() if k not in SANDBOXES}
|
||||
probe = "".join('echo %s=${%s-unset}\n' % (name, name) for name in SANDBOXES)
|
||||
result = subprocess.run(["bash", "-c", head + "\nsh -c '" + probe + "'"], env=env,
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
return dict(line.split("=", 1) for line in result.stdout.splitlines())
|
||||
|
||||
def test_web_engine_apps_start_as_root_like_firefox(self):
|
||||
self.assertEqual({name: "1" for name in SANDBOXES}, self.desktop_environment())
|
||||
|
||||
def test_the_sandbox_switches_are_set_before_plasma(self):
|
||||
self.assertLess(DESKTOP.index("export QTWEBENGINE_DISABLE_SANDBOX=1"),
|
||||
DESKTOP.index("dbus-run-session -- startplasma-wayland"))
|
||||
|
||||
def test_software_sources_gets_the_modules_it_imports(self):
|
||||
self.assertIn("software-properties-qt", PACKAGES)
|
||||
for module in ("pyqt6-dev-tools", "ubuntu-drivers-common"):
|
||||
self.assertIn(module, PACKAGES)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -163,14 +163,6 @@ typedef struct {
|
||||
#define droiddeck_log(...) ((void)0)
|
||||
#define LOGE(...) ((void)0)
|
||||
struct droiddeck_color { uint32_t identity; };
|
||||
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
|
||||
};
|
||||
typedef struct AHardwareBuffer AHardwareBuffer;
|
||||
'''
|
||||
|
||||
|
||||
@@ -1095,7 +1095,8 @@ class LauncherTest(SyncTestCase):
|
||||
self.assertEqual((calls[0][2]["WINEESYNC"], calls[0][2]["PROTON_NO_ESYNC"], calls[0][2]["DD_SYNC_PACK"]), ("0", "1", pack["id"]))
|
||||
self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", DD_SYNC="0", WINEESYNC="1",
|
||||
vblank_mode="0", GAMESCOPE_WSI_MIN_IMAGE_COUNT="8",
|
||||
GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT="1", **expected))
|
||||
GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT="1", PROTON_DISABLE_NVAPI="1",
|
||||
**expected))
|
||||
self.assertEqual(calls[0][2].get("WINEDLLOVERRIDES"), expected.get("WINEDLLOVERRIDES"))
|
||||
self.assertEqual(calls[0][2].get("SteamDeck"), expected.get("SteamDeck"))
|
||||
self.assertIn("could not start (", said.getvalue())
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
|
||||
|
||||
|
||||
class LiveGameCpusTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
base = Path(self.temp.name)
|
||||
self.live = base / "game-cores"
|
||||
tools = base / "tools"
|
||||
tools.mkdir()
|
||||
for name, body in (("taskset", "exit 0"), ("nproc", "echo 8")):
|
||||
tool = tools / name
|
||||
tool.write_text("#!/bin/sh\n" + body + "\n")
|
||||
tool.chmod(0o755)
|
||||
self.path = str(tools) + os.pathsep + os.environ.get("PATH", "")
|
||||
|
||||
def run_setup(self, live=None, **extra):
|
||||
if live is not None:
|
||||
self.live.write_bytes(live.encode())
|
||||
setup = COMPAT["DD_GAME_CPUS_SETUP"].replace("/root/.config/droiddeck/game-cores", str(self.live))
|
||||
script = setup + '\ndd_game_cpus\necho "taskset=${DD_TASKSET:-}"\necho "cpus=${DD_GAME_CPUS-unset}"\n'
|
||||
env = {key: value for key, value in os.environ.items() if not key.startswith("DD_")}
|
||||
env.update(PATH=self.path, **extra)
|
||||
result = subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, check=True)
|
||||
return result.stdout.splitlines()
|
||||
|
||||
def test_a_change_made_during_the_session_wins_over_the_session_value(self):
|
||||
self.assertEqual(self.run_setup("6,7\n", DD_GAME_CPUS="3,4,5,6,7"),
|
||||
["taskset=taskset -c 6,7", "cpus=6,7"])
|
||||
|
||||
def test_every_core_chosen_during_the_session_drops_the_session_pin(self):
|
||||
self.assertEqual(self.run_setup("\n", DD_GAME_CPUS="3,4,5,6,7"), ["taskset=", "cpus=unset"])
|
||||
|
||||
def test_every_core_with_a_pinned_client_still_frees_the_game_from_the_client_cores(self):
|
||||
self.assertEqual(self.run_setup("\n", DD_GAME_CPUS="0-7", DD_CLIENT_CPUS="0"),
|
||||
["taskset=taskset -c 0-7", "cpus=0-7"])
|
||||
|
||||
def test_without_the_live_file_the_session_value_is_used(self):
|
||||
self.assertEqual(self.run_setup(DD_GAME_CPUS="3,4,5,6,7"),
|
||||
["taskset=taskset -c 3,4,5,6,7", "cpus=3,4,5,6,7"])
|
||||
self.assertEqual(self.run_setup(), ["taskset=", "cpus=unset"])
|
||||
|
||||
def test_a_file_caught_mid_write_keeps_the_session_value(self):
|
||||
for partial in ("", "6,7", "6"):
|
||||
self.assertEqual(self.run_setup(partial, DD_GAME_CPUS="4,5"), ["taskset=taskset -c 4,5", "cpus=4,5"], partial)
|
||||
|
||||
def test_an_unreadable_value_keeps_the_session_value(self):
|
||||
for bad in ("3;rm\n", "6-\n", "-3\n", "3,,4\n", "3,\n", "3\n4\n", "3\n4", "\n3\n", "3\0,4\n", "\0\n"):
|
||||
self.assertEqual(self.run_setup(bad, DD_GAME_CPUS="4,5"), ["taskset=taskset -c 4,5", "cpus=4,5"], bad)
|
||||
|
||||
def test_the_file_is_found_whatever_home_the_client_runs_with(self):
|
||||
self.assertEqual(self.run_setup("6,7\n", DD_GAME_CPUS="3,4,5,6,7", HOME="/root/.droiddeck-x64"),
|
||||
["taskset=taskset -c 6,7", "cpus=6,7"])
|
||||
self.assertIn("live=/root/.config/droiddeck/game-cores ", COMPAT["DD_GAME_CPUS_SETUP"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -912,6 +912,46 @@ class GameEnvironmentTest(unittest.TestCase):
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
self.assertEqual(result.stdout.strip().splitlines()[-1], expected)
|
||||
|
||||
def test_nvapi_is_off_unless_the_user_chose_an_nvapi_setting(self):
|
||||
cases = (
|
||||
({}, {"PROTON_DISABLE_NVAPI": "1"}),
|
||||
({"WINEDLLOVERRIDES": "nvcuda=n,b"}, {"WINEDLLOVERRIDES": "nvcuda=n,b", "PROTON_DISABLE_NVAPI": "1"}),
|
||||
({"PROTON_DISABLE_NVAPI": "0"}, {"PROTON_DISABLE_NVAPI": "0"}),
|
||||
({"PROTON_DISABLE_NVAPI": ""}, {"PROTON_DISABLE_NVAPI": ""}),
|
||||
({"PROTON_FORCE_NVAPI": "1"}, {"PROTON_FORCE_NVAPI": "1"}),
|
||||
({"DXVK_ENABLE_NVAPI": "1"}, {"DXVK_ENABLE_NVAPI": "1"}),
|
||||
)
|
||||
for before, after in cases:
|
||||
with self.subTest(env=before):
|
||||
env = dict(before)
|
||||
note = MODULE["nvapi_off"](env)
|
||||
self.assertEqual(env, after)
|
||||
self.assertEqual(note is not None, env != before)
|
||||
|
||||
def test_game_launch_turns_nvapi_off_and_keeps_user_choices(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
probe = home / "probe"
|
||||
probe.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('PROTON_DISABLE_NVAPI', 'unset'), os.environ.get('PROTON_FORCE_NVAPI', 'unset'))\n")
|
||||
probe.chmod(0o755)
|
||||
config = home / ".config/droiddeck/game-environment.json"
|
||||
config.parent.mkdir(parents=True)
|
||||
cases = (
|
||||
("waitforexitandrun", {}, "1 unset"),
|
||||
("waitforexitandrun", {"PROTON_DISABLE_NVAPI": "0"}, "0 unset"),
|
||||
("waitforexitandrun", {"PROTON_FORCE_NVAPI": "1"}, "unset 1"),
|
||||
("run", {}, "unset unset"),
|
||||
)
|
||||
for verb, profile, expected in cases:
|
||||
with self.subTest(verb=verb, profile=profile):
|
||||
config.write_text(json.dumps({"version": 1, "games": {"42": profile}}))
|
||||
env = {k: v for k, v in os.environ.items()
|
||||
if k not in ("PROTON_DISABLE_NVAPI", "PROTON_FORCE_NVAPI", "DXVK_ENABLE_NVAPI")}
|
||||
env.update(HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/42")
|
||||
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), verb],
|
||||
env=env, text=True, capture_output=True, check=True)
|
||||
self.assertEqual(result.stdout.strip().splitlines()[-1], expected)
|
||||
|
||||
def test_optional_xbox_loader_failure_keeps_stock_launch(self):
|
||||
from unittest.mock import patch
|
||||
for error in (FileNotFoundError('missing'), RuntimeError('module initialization failed')):
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -55,70 +54,12 @@ FORKER = r"""
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <semaphore.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static const char *name;
|
||||
static _Atomic int done;
|
||||
static _Atomic int parked_word;
|
||||
static _Atomic pid_t parked_tid;
|
||||
|
||||
// the host's futex call: 202 on x86-64, where qemu-user runs, 98 on aarch64
|
||||
static int blocked_futex(const char *path, unsigned long *addr) {
|
||||
unsigned long nr = 0;
|
||||
FILE *f = fopen(path, "r");
|
||||
int got = f && fscanf(f, "%lu %lx", &nr, addr) == 2;
|
||||
if (f) fclose(f);
|
||||
return got && (nr == 202 || nr == 98);
|
||||
}
|
||||
|
||||
static void *park(void *arg) {
|
||||
parked_tid = (pid_t)syscall(SYS_gettid);
|
||||
while (!parked_word) syscall(SYS_futex, &parked_word, 0 /* FUTEX_WAIT */, 0, NULL, NULL, 0);
|
||||
return arg;
|
||||
}
|
||||
|
||||
// How far qemu-user moved the guest in the host's address space (its guest_base; 0 natively): a
|
||||
// thread parked on a futex this program knows shows that futex's host address in its syscall file,
|
||||
// which qemu-user passes through unlike /proc/self/maps.
|
||||
static long guest_base(void) {
|
||||
char path[96];
|
||||
unsigned long addr = 0;
|
||||
while (!parked_tid) usleep(1000);
|
||||
snprintf(path, sizeof(path), "/proc/%d/task/%d/syscall", (int)getpid(), (int)parked_tid);
|
||||
for (int i = 0; i < 5000; i++) {
|
||||
if (blocked_futex(path, &addr) && addr) return (long)(addr - (unsigned long)&parked_word);
|
||||
usleep(1000);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// A child that hangs in qemu-user itself: a fork while another thread is inside the emulator's
|
||||
// own locks (its mmap() handling) can leave the child waiting on a futex in qemu's memory, which no
|
||||
// guest lock is. The child's blocking call shows the host's address; under qemu-user this
|
||||
// program's /proc/self/maps lists the guest's mappings only, and a futex outside all of them, once
|
||||
// moved back by the guest base, is the emulator's. Natively every futex is in the process's own
|
||||
// mappings: never counted. Seen on x86 runners; there is no emulator on a device.
|
||||
static int stuck_in_emulator(pid_t pid, long base) {
|
||||
char path[64], line[512];
|
||||
unsigned long addr = 0;
|
||||
snprintf(path, sizeof(path), "/proc/%d/syscall", (int)pid);
|
||||
if (base < 0 || !blocked_futex(path, &addr)) return 0;
|
||||
addr -= (unsigned long)base;
|
||||
FILE *f = fopen("/proc/self/maps", "r");
|
||||
if (!f) return 0;
|
||||
int guest = 0;
|
||||
while (!guest && fgets(line, sizeof(line), f)) {
|
||||
unsigned long start, end;
|
||||
if (sscanf(line, "%lx-%lx", &start, &end) == 2 && addr >= start && addr < end) guest = 1;
|
||||
}
|
||||
fclose(f);
|
||||
return !guest;
|
||||
}
|
||||
|
||||
static void *churn(void *arg) {
|
||||
while (!done) {
|
||||
@@ -130,40 +71,24 @@ static void *churn(void *arg) {
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
name = argv[1];
|
||||
pthread_t parked, thread;
|
||||
if (pthread_create(&parked, NULL, park, NULL) != 0) return 1;
|
||||
long base = guest_base();
|
||||
printf("base\t%ld\n", base);
|
||||
pthread_t thread;
|
||||
if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1;
|
||||
int finished = 0, emulator = 0;
|
||||
int finished = 0;
|
||||
for (int i = 0; i < 200; i++) {
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) break;
|
||||
if (pid == 0) {
|
||||
alarm(10);
|
||||
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
|
||||
_exit(sem == SEM_FAILED || sem_close(sem) != 0);
|
||||
}
|
||||
int status = 0, stalled = 0;
|
||||
pid_t r;
|
||||
for (int waited = 0; (r = waitpid(pid, &status, WNOHANG)) == 0; waited++) {
|
||||
if (waited == 1000) { // 10 s
|
||||
stalled = stuck_in_emulator(pid, base);
|
||||
kill(pid, SIGKILL);
|
||||
}
|
||||
usleep(10000);
|
||||
}
|
||||
if (r != pid) continue;
|
||||
if (stalled) emulator++;
|
||||
else if (WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++;
|
||||
int status;
|
||||
if (waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++;
|
||||
}
|
||||
done = 1;
|
||||
pthread_join(thread, NULL);
|
||||
parked_word = 1;
|
||||
syscall(SYS_futex, &parked_word, 1 /* FUTEX_WAKE */, 1, NULL, NULL, 0);
|
||||
pthread_join(parked, NULL);
|
||||
sem_unlink(name);
|
||||
printf("finished\t%d\n", finished);
|
||||
printf("emulator\t%d\n", emulator);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
@@ -191,7 +116,7 @@ class NativeHookNamedSemaphoresTest(unittest.TestCase):
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_hooked(self, program, *args, timeout=120):
|
||||
def run_hooked(self, program, *args):
|
||||
hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
|
||||
if self.prefix:
|
||||
@@ -199,17 +124,9 @@ class NativeHookNamedSemaphoresTest(unittest.TestCase):
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
# its own process group, so a timeout also ends a child still blocked once the program is gone
|
||||
proc = subprocess.Popen(cmd + [str(program), *args], env=env, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, start_new_session=True)
|
||||
try:
|
||||
stdout, stderr = proc.communicate(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(proc.pid, signal.SIGKILL)
|
||||
proc.communicate()
|
||||
raise
|
||||
self.assertEqual(proc.returncode, 0, stderr)
|
||||
return dict(line.split("\t") for line in stdout.splitlines())
|
||||
out = subprocess.run(cmd + [str(program), *args], env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return dict(line.split("\t") for line in out.stdout.splitlines())
|
||||
|
||||
def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self):
|
||||
name = f"/ddsem-{os.getpid()}"
|
||||
@@ -222,20 +139,7 @@ class NativeHookNamedSemaphoresTest(unittest.TestCase):
|
||||
source.write_text(FORKER)
|
||||
forker = self.probe.with_name("forker")
|
||||
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True)
|
||||
name = f"/ddsem-fork-{os.getpid()}"
|
||||
# left by a run that did not get to sem_unlink(), it would fail the other tests' empty /dev/shm
|
||||
self.addCleanup(lambda: (self.shm / f"sem.{name[1:]}").unlink(missing_ok=True))
|
||||
# 200 forks under a loaded qemu-user, and 10 s for each child that hangs in the emulator
|
||||
result = self.run_hooked(forker, name, timeout=300)
|
||||
# every child opened one, but for one now and then that hung in qemu-user itself (a fork during
|
||||
# the emulator's own locking), which a native run never has
|
||||
if self.prefix:
|
||||
self.assertNotEqual("-1", result.get("base"), result)
|
||||
else:
|
||||
self.assertEqual("0", result.get("base"), result)
|
||||
emulator = int(result.get("emulator", "0"))
|
||||
self.assertEqual(200, int(result.get("finished", "0")) + emulator, result)
|
||||
self.assertLessEqual(emulator, 0 if not self.prefix else 3, result)
|
||||
self.assertEqual({"finished": "200"}, self.run_hooked(forker, f"/ddsem-fork-{os.getpid()}"))
|
||||
|
||||
def test_a_created_semaphore_keeps_its_name_and_mode(self):
|
||||
name = f"ddsem-kept-{os.getpid()}"
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
# The rootfs' /bin/sh for these tests: "sh -c 'echo WORDS'" prints WORDS, "sh -c 'exit N'" exits N.
|
||||
SHELL = r"""
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 3 || strcmp(argv[1], "-c") != 0) return 2;
|
||||
if (strncmp(argv[2], "echo ", 5) == 0) {
|
||||
puts(argv[2] + 5);
|
||||
return 0;
|
||||
}
|
||||
if (strncmp(argv[2], "exit ", 5) == 0) return atoi(argv[2] + 5);
|
||||
return 127;
|
||||
}
|
||||
"""
|
||||
|
||||
# posix_spawn() of argv[1] -c "exit 3", without the hook: prints the exit status it got
|
||||
SPAWN_PROBE = r"""
|
||||
#include <spawn.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
extern char **environ;
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
pid_t pid;
|
||||
char *args[] = {"sh", "-c", "exit 3", NULL};
|
||||
int status = 0;
|
||||
if (posix_spawn(&pid, argv[1], NULL, NULL, args, environ) != 0 || waitpid(pid, &status, 0) != pid) return 1;
|
||||
printf("%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
# popen() and system() through the hook (which starts the shell with posix_spawn())
|
||||
PROGRAM = r"""
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (strcmp(argv[1], "system") == 0) {
|
||||
int status = system("exit 3");
|
||||
printf("system\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
||||
return 0;
|
||||
}
|
||||
// a second stream open while the first is read: the shell of the first must not hold it
|
||||
FILE *other = popen("echo other", "r");
|
||||
FILE *f = popen("echo from the shell", "r");
|
||||
char line[64] = "";
|
||||
if (f && !fgets(line, sizeof(line), f)) line[0] = 0;
|
||||
line[strcspn(line, "\n")] = 0;
|
||||
int status = f ? pclose(f) : -1;
|
||||
if (other) pclose(other);
|
||||
printf("popen\t%s\n", line);
|
||||
printf("pclose\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookPopenTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
cls.root = tmp / "root"
|
||||
(cls.root / "bin").mkdir(parents=True)
|
||||
(tmp / "sh.c").write_text(SHELL)
|
||||
subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/sh"), str(tmp / "sh.c")], check=True)
|
||||
# posix_spawn()'s child execs the shell itself. Under qemu-user that exec works only where the
|
||||
# kernel runs aarch64 programs (binfmt_misc), which a plain x86 runner does not.
|
||||
(tmp / "spawn.c").write_text(SPAWN_PROBE)
|
||||
subprocess.run([cls.cc, "-static", "-O1", "-o", str(tmp / "spawn"), str(tmp / "spawn.c")], check=True)
|
||||
probe = subprocess.run(list(cls.prefix or []) + [str(tmp / "spawn"), str(cls.root / "bin/sh")],
|
||||
capture_output=True, text=True, timeout=60)
|
||||
if probe.stdout.strip() != "3":
|
||||
cls.tmp.cleanup()
|
||||
raise unittest.SkipTest("this runner cannot exec an aarch64 program from a posix_spawn() child")
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
cls.program = tmp / "prog"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c")], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_program(self, mode):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
|
||||
# Only what the program needs: other test modules in the same run change os.environ
|
||||
env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.program), mode], env=env, capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
return dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out
|
||||
|
||||
def test_popen_reads_the_shells_output(self):
|
||||
result, out = self.run_program("popen")
|
||||
self.assertEqual("from the shell", result.get("popen"), out.stdout + out.stderr)
|
||||
self.assertEqual("0", result.get("pclose"), out.stdout)
|
||||
|
||||
def test_system_returns_the_shells_status(self):
|
||||
result, out = self.run_program("system")
|
||||
self.assertEqual("3", result.get("system"), out.stdout + out.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -452,107 +452,6 @@ class Launchers(unittest.TestCase):
|
||||
self.assertEqual(-2, rc)
|
||||
|
||||
|
||||
def test_a_steam_ea_link_is_swapped_for_droiddecks_launcher_and_reports_its_exit(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
hook = Path(root) / 'hook'
|
||||
record = Path(root) / 'ran'
|
||||
hook.write_text('#!/bin/sh\necho "$@" >> "%s"\n' % record)
|
||||
hook.chmod(0o755)
|
||||
setup = compat.DD_STORE_SETUP.replace('/usr/local/bin/droiddeck-store-launch', str(hook)).replace(
|
||||
'[ -x %s ] || return 0' % hook, '[ -x %s ] || return 0; verb=waitforexitandrun' % hook)
|
||||
setup = setup.replace(' %s "$@"\n rc=$?' % hook, ' %s "$@"\n rc=13' % hook)
|
||||
script = setup + '\nverb=waitforexitandrun\ndd_store_launch steam2ea://launchgame/1237970 -dev\nDD_STORE_ARGS=(steam2ea://launchgame/1237970 -dev)\ndd_run %s proton waitforexitandrun Steam2EA://launchgame/1237970 -dev\n' % hook
|
||||
done = subprocess.run(['bash', '-c', script], env=dict(os.environ, STEAM_COMPAT_DATA_PATH=root + '/'), timeout=20)
|
||||
self.assertEqual(0, done.returncode)
|
||||
lines = record.read_text().splitlines()
|
||||
self.assertEqual('proton waitforexitandrun %s/droiddeck-ea-steam.bat -dev' % root, lines[1])
|
||||
self.assertEqual('--exited --code 0 steam2ea://launchgame/1237970 -dev', lines[2])
|
||||
|
||||
|
||||
MANIFEST = """<?xml version='1.0' encoding='utf-8'?>
|
||||
<DiPManifest version="4.0">
|
||||
<buildMetaData><gameVersion version="1.0.1.3" /></buildMetaData>
|
||||
<contentIDs><contentID>1039093</contentID></contentIDs>
|
||||
<runtime>
|
||||
<launcher uid="1-2"><filePath>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Respawn\\Titanfall2\\Install Dir]Titanfall2.exe</filePath><parameters /><trial>0</trial></launcher>
|
||||
<launcher uid="2-2"><filePath>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Respawn\\Titanfall2\\Install Dir]Titanfall2_trial.exe</filePath><parameters /><trial>1</trial></launcher>
|
||||
</runtime>
|
||||
<gameTitles><gameTitle locale="en_US">Titanfall 2</gameTitle></gameTitles>
|
||||
</DiPManifest>
|
||||
"""
|
||||
|
||||
|
||||
class SteamEa(unittest.TestCase):
|
||||
def steam_copy(self, root):
|
||||
folder = Path(root) / 'steamapps/common/Titanfall2'
|
||||
(folder / '__Installer/LOC').mkdir(parents=True)
|
||||
(folder / '__Installer/installerdata.xml').write_bytes(b'\xff\xfe' + MANIFEST.encode('utf-16-le'))
|
||||
(folder / '__Installer/LOC/Origin.OFR.50.0001456.dat').write_text('')
|
||||
(folder / '__Installer/LOC/Origin.OFR.50.0001452.dat').write_text('')
|
||||
(folder / 'Titanfall2.exe').write_text('')
|
||||
(folder / 'Titanfall2_trial.exe').write_text('')
|
||||
data = Path(root) / 'compatdata/1237970'
|
||||
(data / 'pfx').mkdir(parents=True)
|
||||
return folder, data
|
||||
|
||||
def test_the_manifest_names_the_full_game_its_content_and_version(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder, _ = self.steam_copy(root)
|
||||
manifest = store.ea_manifest(folder)
|
||||
self.assertEqual(folder / 'Titanfall2.exe', manifest['exe'])
|
||||
self.assertEqual(['1039093'], manifest['contentIds'])
|
||||
self.assertEqual('1.0.1.3', manifest['version'])
|
||||
self.assertEqual('Titanfall 2', manifest['title'])
|
||||
self.assertEqual(['Origin.OFR.50.0001452', 'Origin.OFR.50.0001456'], store.steam_ea_offers(folder))
|
||||
|
||||
def test_a_steam_ea_launch_gets_a_session_and_a_launcher_that_reads_it_once(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder, data = self.steam_copy(root)
|
||||
asked = []
|
||||
answer = {'ok': True, 'id': 'Origin.OFR.50.0001452', 'env': {'EALsxPort': '3216', 'ContentId': '1039093'}}
|
||||
prepare = lambda *a: asked.append(a) or answer
|
||||
env = {'STEAM_COMPAT_INSTALL_PATH': str(folder), 'STEAM_COMPAT_DATA_PATH': str(data), 'DD_LAUNCH_DIR': str(Path(root) / 'session')}
|
||||
with patch.dict(os.environ, env), patch.object(store, 'prepare_ea', side_effect=prepare):
|
||||
self.assertEqual(store.REPLACED, store.main(['steam2ea://launchgame/1237970?platform=steam&theme=tf2']))
|
||||
steam = asked[0][4]
|
||||
self.assertEqual(['Origin.OFR.50.0001452', 'Origin.OFR.50.0001456'], steam['offers'])
|
||||
self.assertEqual(['1039093'], steam['contentIds'])
|
||||
self.assertEqual('Titanfall2.exe', steam['exe'])
|
||||
self.assertEqual(b'EALsxPort=3216\r\nContentId=1039093\r\n', (data / store.STEAM_EA_ENV).read_bytes())
|
||||
bat = (data / store.STEAM_EA_LAUNCHER).read_text()
|
||||
envfile = store.windows_path(str(data / store.STEAM_EA_ENV))
|
||||
self.assertIn('cd /d "%s"' % store.windows_path(str(folder)), bat)
|
||||
self.assertIn('for /f "usebackq tokens=1,* delims==" %%%%a in ("%s") do set "%%%%a=%%%%b"' % envfile, bat)
|
||||
self.assertIn('del "%s"' % envfile, bat)
|
||||
self.assertIn('"%s" %%*' % store.windows_path(str(folder / 'Titanfall2.exe')), bat)
|
||||
self.assertEqual({'id': 'Origin.OFR.50.0001452'}, json.loads((data / store.STEAM_EA_STATE).read_text()))
|
||||
asked.clear()
|
||||
record = lambda channel, request, timeout=5.0, claim=False: asked.append(request)
|
||||
with patch.dict(os.environ, env), patch.object(store, 'ask', side_effect=record):
|
||||
self.assertEqual(0, store.main(['--exited', 'steam2ea://launchgame/1237970']))
|
||||
self.assertEqual([{'op': 'ea-exited', 'store': 'ea', 'id': 'Origin.OFR.50.0001452'}], asked)
|
||||
|
||||
def test_the_manifests_launch_parameters_keep_their_quotes(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder, data = self.steam_copy(root)
|
||||
bat = store.steam_ea_launcher(folder, folder / 'Titanfall2.exe', '-config "game profile.cfg" -rate 50%', str(data))
|
||||
self.assertIn('Titanfall2.exe" -config "game profile.cfg" -rate 50%% %*', bat)
|
||||
|
||||
def test_steam_keeps_the_link_when_droiddeck_cannot_start_the_game(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder, data = self.steam_copy(root)
|
||||
env = {'STEAM_COMPAT_INSTALL_PATH': str(folder), 'STEAM_COMPAT_DATA_PATH': str(data), 'DD_LAUNCH_DIR': str(Path(root) / 'session')}
|
||||
link = ['steam2ea://launchgame/1237970']
|
||||
with patch.dict(os.environ, env), patch.object(store, 'prepare_ea', return_value={'ok': False, 'reason': 'signed-out'}):
|
||||
self.assertEqual(0, store.main(link))
|
||||
client = data / 'pfx' / store.STEAM_EA_CLIENT
|
||||
client.parent.mkdir(parents=True)
|
||||
client.write_text('')
|
||||
with patch.dict(os.environ, env), patch.object(store, 'prepare_ea', side_effect=AssertionError('the EA app is installed')):
|
||||
self.assertEqual(0, store.main(link))
|
||||
self.assertFalse((data / store.STEAM_EA_LAUNCHER).exists())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
|
||||
@@ -20,14 +20,6 @@ LAYER_HARNESS = r'''
|
||||
#include "vk_linear_dmabuf.h"
|
||||
|
||||
typedef struct AHardwareBuffer AHardwareBuffer;
|
||||
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
|
||||
};
|
||||
%(image)s
|
||||
struct vkp_draw {
|
||||
struct vkp_image *img;
|
||||
|
||||
@@ -31,10 +31,8 @@ def function(text, name):
|
||||
HARNESS = r'''
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <unistd.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdarg.h>
|
||||
#include <unistd.h>
|
||||
typedef int VkResult;
|
||||
typedef uintptr_t VkFence;
|
||||
#define VK_TRUE 1
|
||||
@@ -71,31 +69,12 @@ static struct {
|
||||
typedef struct AHardwareBuffer AHardwareBuffer;
|
||||
static int released_buffers;
|
||||
static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; ++released_buffers; }
|
||||
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 {
|
||||
uintptr_t image, mem;
|
||||
void *map;
|
||||
AHardwareBuffer *android_buffer;
|
||||
uintptr_t linear_buf, linear_mem;
|
||||
int staged, in_general;
|
||||
enum vkp_image_source source_type;
|
||||
int source_fd;
|
||||
uint8_t *recovery_pixels;
|
||||
struct vkp_image *next;
|
||||
};
|
||||
static void image_unregister(struct vkp_image *img) { (void)img; }
|
||||
struct vkp_image { uintptr_t image, mem; void *map; AHardwareBuffer *android_buffer; uintptr_t linear_buf, linear_mem; int staged, in_general; };
|
||||
static void blendp_forget_image(uintptr_t image) { (void)image; ++forgotten; }
|
||||
/* PRODUCTION_FUNCTIONS */
|
||||
static struct vkp_image *image(void) {
|
||||
struct vkp_image *p = calloc(1, sizeof(*p)); assert(p);
|
||||
p->image=1; p->mem=2; p->map=p; p->source_fd=-1; return p;
|
||||
p->image=1; p->mem=2; p->map=p; return p;
|
||||
}
|
||||
int main(void) {
|
||||
g_dev_state=1; answer=VK_SUCCESS;
|
||||
|
||||
@@ -117,9 +117,6 @@ int __android_log_print(int, const char *, const char *, ...);
|
||||
def test_finite_blit_timeout_same_size_pixel_upload(self):
|
||||
self.run_scenario('pixel-timeout')
|
||||
|
||||
def test_lost_device_shm_upload_keeps_cpu_snapshot(self):
|
||||
self.run_scenario('lost-shm-upload')
|
||||
|
||||
def test_normal_present(self):
|
||||
self.run_scenario('normal')
|
||||
|
||||
@@ -129,9 +126,6 @@ int __android_log_print(int, const char *, const char *, ...);
|
||||
def test_healthy_later_acquire_timeout_drains_work(self):
|
||||
self.run_scenario('later-timeout')
|
||||
|
||||
def test_device_loss_with_unconfirmed_idle_retains_resources(self):
|
||||
self.run_scenario('acquire-device-lost-unconfirmed')
|
||||
|
||||
def test_real_device_lost_on_acquire(self):
|
||||
self.run_scenario('acquire-device-lost')
|
||||
|
||||
|
||||
@@ -38,11 +38,7 @@ static void blit(VkCommandBuffer c, VkImage s, VkImageLayout sl, VkImage d, VkIm
|
||||
uint32_t n, const VkImageBlit *b, VkFilter f) { live(); }
|
||||
static void destroy_swap(VkDevice d, VkSwapchainKHR s, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void destroy_surface(VkInstance i, VkSurfaceKHR s, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void destroy_fence(VkDevice d, VkFence f, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void destroy_pool(VkDevice d, VkCommandPool p, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void destroy_device(VkDevice d, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void destroy_instance(VkInstance i, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void destroy_sem(VkDevice d, VkSemaphore s, const VkAllocationCallbacks *a) { ++destroys; }
|
||||
static void destroy_sem(VkDevice d, VkSemaphore s, const VkAllocationCallbacks *a) { live(); ++destroys; }
|
||||
static VkResult create_sem(VkDevice d, const VkSemaphoreCreateInfo *c, const VkAllocationCallbacks *a, VkSemaphore *s) {
|
||||
live(); *s = (VkSemaphore)(uintptr_t)1; return VK_SUCCESS;
|
||||
}
|
||||
@@ -65,17 +61,15 @@ int sc_layer_base_black(int w, int h) { return 0; }
|
||||
void sc_layer_hide_base(void) {}
|
||||
void sc_layer_hide_overlay(void) {}
|
||||
void vkp_cardboard_bind_device(VkDevice d, const VkPhysicalDeviceMemoryProperties *m) {}
|
||||
void vkp_cardboard_destroy(void) {}
|
||||
int vkp_cardboard_active(void) { return 0; }
|
||||
void vkp_cardboard_begin_frame(void) {}
|
||||
VkImage vkp_cardboard_run(VkCommandBuffer c, VkImage s, int sw, int sh, int ow, int oh) { return s; }
|
||||
int vk_loader_open(const char *a, const char *b, const char *c) { return -1; }
|
||||
void vk_loader_close(void) {}
|
||||
void vk_loader_load_instance(VkInstance i) {}
|
||||
void vk_loader_load_device(VkDevice d) {}
|
||||
int vk_loader_open(const char *a, const char *b, const char *c) { assert(0); return -1; }
|
||||
void vk_loader_close(void) { assert(0); }
|
||||
void vk_loader_load_instance(VkInstance i) { assert(0); }
|
||||
void vk_loader_load_device(VkDevice d) { assert(0); }
|
||||
PFN_vkGetInstanceProcAddr vk_loader_gipa(void) { return NULL; }
|
||||
void vkp_effects_bind_device(VkDevice d, VkPhysicalDevice p, const VkPhysicalDeviceMemoryProperties *m) {}
|
||||
void vkp_effects_destroy(void) {}
|
||||
int vkp_effects_active(void) { return 0; }
|
||||
int vkp_effects_upscaling(void) { return 0; }
|
||||
int vkp_effects_sharpening(void) { return 0; }
|
||||
@@ -100,11 +94,9 @@ void vkp_framegen_presented(int n) { ++presented_notifications; }
|
||||
void vkp_gpu_busy_device(VkPhysicalDevice p, VkDevice d, uint32_t f) {}
|
||||
void vkp_gpu_busy_device_lost(void) {}
|
||||
void hdrc_bind_device(VkDevice d, const VkPhysicalDeviceMemoryProperties *m) {}
|
||||
void hdrc_destroy(void) {}
|
||||
void hdrc_forget_image(VkImage i) {}
|
||||
int hdrc_encode(VkCommandBuffer c, VkImage a, VkImage b, VkFormat f, int w, int h, const struct hdrc_params *p) { return -1; }
|
||||
void blendp_bind_device(VkDevice d) {}
|
||||
void blendp_destroy(void) {}
|
||||
void blendp_forget_image(VkImage i) {}
|
||||
void vkp_effects_forget_image(VkImage i) {}
|
||||
void blendp_begin_frame(void) {}
|
||||
@@ -163,8 +155,6 @@ static void setup(int extra) {
|
||||
.ResetCommandBuffer = reset_cmd, .ResetFences = reset_fence, .BeginCommandBuffer = begin_cmd,
|
||||
.EndCommandBuffer = end_cmd, .CmdPipelineBarrier = barrier, .CmdClearColorImage = clear,
|
||||
.CmdBlitImage = blit, .DestroySwapchainKHR = destroy_swap, .DestroySurfaceKHR = destroy_surface,
|
||||
.DestroyFence = destroy_fence, .DestroyCommandPool = destroy_pool,
|
||||
.DestroyDevice = destroy_device, .DestroyInstance = destroy_instance,
|
||||
.DestroySemaphore = destroy_sem, .CreateSemaphore = create_sem,
|
||||
.DestroyImage = destroy_image, .FreeMemory = free_memory, .UnmapMemory = unmap};
|
||||
idle_answer = fence_answer = acquire_answer = present_answer = VK_SUCCESS;
|
||||
@@ -190,7 +180,6 @@ static void setup(int extra) {
|
||||
/* Probe the public GPU entry points after a terminal result. This includes an
|
||||
* active off-screen pass and consumed release fds, not just the render guard. */
|
||||
static void assert_stopped(void) {
|
||||
assert(g_dev_state == -3 || (g_dev_state == -2 && g_recovery_attempted));
|
||||
unsigned before = operations, before_destroys = destroys;
|
||||
struct vkp_image src = {.image = (VkImage)(uintptr_t)7, .w = 1, .h = 1};
|
||||
struct vkp_image dst = {.image = (VkImage)(uintptr_t)8, .w = 1, .h = 1, .blit_dst = 1};
|
||||
@@ -279,20 +268,7 @@ int main(int argc, char **argv) {
|
||||
else if (!strcmp(name, "later-surface-lost")) acquire_failure(1, VK_ERROR_SURFACE_LOST_KHR);
|
||||
else if (!strcmp(name, "shm-timeout")) upload_timeout(0);
|
||||
else if (!strcmp(name, "pixel-timeout")) upload_timeout(1);
|
||||
else if (!strcmp(name, "lost-shm-upload")) {
|
||||
setup(0);
|
||||
uint8_t bytes[64], data[16];
|
||||
memset(bytes, 0xa5, sizeof(bytes));
|
||||
for (unsigned i = 0; i < sizeof(data); i++) data[i] = (uint8_t)(i + 1);
|
||||
struct vkp_image img = {.map = bytes, .offset = 3, .row_pitch = 16, .w = 2, .h = 2,
|
||||
.source_type = VKP_IMAGE_SOURCE_SHM};
|
||||
g_dev_state = -2;
|
||||
vkp_image_upload_shm(&img, data, 8);
|
||||
assert(img.recovery_pixels && !memcmp(img.recovery_pixels, data, sizeof(data)));
|
||||
assert(bytes[3] == 0xa5 && bytes[19] == 0xa5);
|
||||
free(img.recovery_pixels);
|
||||
free(g_images);
|
||||
} else if (!strcmp(name, "pass-terminal")) { setup(0); g_dev_state = -3; assert_stopped(); free(g_images); }
|
||||
else if (!strcmp(name, "pass-terminal")) { setup(0); g_dev_state = -3; assert_stopped(); free(g_images); }
|
||||
else if (!strcmp(name, "normal") || !strcmp(name, "framegen")) {
|
||||
int extra = !strcmp(name, "framegen"); setup(extra);
|
||||
assert(vkp_render(64, 64, NULL, 0) == 0 && g_dev_state == 1);
|
||||
@@ -303,18 +279,6 @@ int main(int argc, char **argv) {
|
||||
setup(1); fail_acquire_at = 2; acquire_answer = VK_TIMEOUT;
|
||||
assert(vkp_render(64, 64, NULL, 0) == -1 && g_dev_state == 1);
|
||||
assert(acquires == 2 && submits == 2 && markers == 1 && waits == 1); free(g_images);
|
||||
} else if (!strcmp(name, "acquire-device-lost-unconfirmed")) {
|
||||
setup(1);
|
||||
fail_acquire_at = 2;
|
||||
acquire_answer = VK_ERROR_DEVICE_LOST;
|
||||
idle_answer = VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
VkImage *retained = g_images;
|
||||
assert(vkp_render(64, 64, NULL, 0) == -1);
|
||||
assert(g_dev_state == -3 && vkp_completion_unknown() && !vkp_device_lost());
|
||||
assert(idle_calls == 1 && lost_notifications == 0 && waits == 0);
|
||||
assert(g_images == retained && g_nimg == 1 && g_swapchain && g_surface && destroys == 0);
|
||||
assert_stopped();
|
||||
free(g_images); /* test-owned fake resources only */
|
||||
} else if (!strcmp(name, "acquire-device-lost") || !strcmp(name, "present-device-lost")) {
|
||||
setup(1);
|
||||
if (!strcmp(name, "acquire-device-lost")) { fail_acquire_at = 2; acquire_answer = VK_ERROR_DEVICE_LOST; }
|
||||
@@ -323,8 +287,6 @@ int main(int argc, char **argv) {
|
||||
assert(!vkp_completion_unknown());
|
||||
assert(g_dev_state == -2 && lost_notifications == 1 && markers == 0 && waits == 0);
|
||||
assert(!g_images && !g_swapchain && !g_surface && destroys == 2);
|
||||
assert(vkp_ready() == -1);
|
||||
assert(g_dev_state == -2 && g_recovery_attempted);
|
||||
assert_stopped();
|
||||
} else assert(0 && "unknown scenario");
|
||||
return 0;
|
||||
|
||||
@@ -11,8 +11,6 @@ Steam on the desktop). The app installs it into `files/linuxfs` and runs it unde
|
||||
UBWC 5/6 (backported from upstream Mesa) and the KGSL device numbers for WSI (from
|
||||
[Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)). It also carries Icenowy Zheng's upstream
|
||||
Zink fix that keeps the Imagination depth/stencil swizzle off colour views (Mesa d55418dae7).
|
||||
Zink also reclaims the memory a client freed once it has been idle for a second: otherwise only its
|
||||
next allocation does, and Steam's UI behind a game held 250 MiB more of unswappable GPU memory.
|
||||
- The runtime's built-in Vulkan driver is DroidDeck's DD-Turnip Linux build (`DD_TURNIP_URL` and
|
||||
`DD_TURNIP_SHA256` in `base.env`): Ubuntu's Turnip is diverted to `libvulkan_freedreno.so.distrib`
|
||||
because it lacks the Adreno 8xx fixes. Zink, EGL and llvmpipe stay Ubuntu's.
|
||||
|
||||
@@ -215,7 +215,6 @@ power-profiles-daemon
|
||||
powerdevil
|
||||
ppa-purge
|
||||
print-manager
|
||||
pyqt6-dev-tools
|
||||
python3-dbus
|
||||
python3-launchpadlib
|
||||
python3-setuptools
|
||||
@@ -242,7 +241,6 @@ software-properties-qt
|
||||
squashfs-tools
|
||||
synaptic
|
||||
systemsettings
|
||||
ubuntu-drivers-common
|
||||
udisks2
|
||||
unrar-free
|
||||
upower
|
||||
|
||||
-143
@@ -1,143 +0,0 @@
|
||||
Subject: zink: reclaim freed slab entries and cached buffers while the client is idle
|
||||
|
||||
zink only reclaims slab entries and expired cached buffers during its next
|
||||
allocation, and pb_slabs_reclaim stops at the first entries still in use. A
|
||||
client that frees a lot and then goes idle keeps all of it allocated: Steam's web helper held 500-700 MiB of KGSL memory behind a
|
||||
fullscreen game after scrolling its library, and released it the moment the
|
||||
overlay drew a frame. A thread now reclaims once a second after a second
|
||||
without allocations.
|
||||
|
||||
--- a/src/util/pb_slab.h
|
||||
+++ b/src/util/pb_slab.h
|
||||
@@ -145,6 +145,9 @@
|
||||
unsigned
|
||||
pb_slabs_reclaim(struct pb_slabs *slabs);
|
||||
|
||||
+unsigned
|
||||
+pb_slabs_reclaim_all(struct pb_slabs *slabs);
|
||||
+
|
||||
bool
|
||||
pb_slabs_init(struct pb_slabs *slabs,
|
||||
unsigned min_order, unsigned max_order,
|
||||
--- a/src/util/pb_slab.c
|
||||
+++ b/src/util/pb_slab.c
|
||||
@@ -231,6 +231,19 @@
|
||||
return num_reclaims;
|
||||
}
|
||||
|
||||
+/* Like pb_slabs_reclaim, but skips entries that are still in use instead of
|
||||
+ * stopping at the first ones, so entries freed behind them are reclaimed too.
|
||||
+ */
|
||||
+unsigned
|
||||
+pb_slabs_reclaim_all(struct pb_slabs *slabs)
|
||||
+{
|
||||
+ unsigned num_reclaims;
|
||||
+ simple_mtx_lock(&slabs->mutex);
|
||||
+ num_reclaims = pb_slabs_reclaim_all_locked(slabs);
|
||||
+ simple_mtx_unlock(&slabs->mutex);
|
||||
+ return num_reclaims;
|
||||
+}
|
||||
+
|
||||
/* Initialize the slabs manager.
|
||||
*
|
||||
* The minimum and maximum size of slab entries are 2^min_order and
|
||||
--- a/src/gallium/drivers/zink/zink_types.h
|
||||
+++ b/src/gallium/drivers/zink/zink_types.h
|
||||
@@ -1427,6 +1427,12 @@
|
||||
struct pb_slabs bo_slabs[NUM_SLAB_ALLOCATORS];
|
||||
unsigned min_alloc_size;
|
||||
uint32_t next_bo_unique_id;
|
||||
+ uint32_t alloc_serial;
|
||||
+ thrd_t reclaim_thread;
|
||||
+ mtx_t reclaim_lock;
|
||||
+ cnd_t reclaim_cond;
|
||||
+ bool reclaim_stop;
|
||||
+ bool reclaim_running;
|
||||
} pb;
|
||||
uint8_t heap_map[ZINK_HEAP_MAX][VK_MAX_MEMORY_TYPES]; // mapping from zink heaps to memory type indices
|
||||
uint8_t heap_count[ZINK_HEAP_MAX]; // number of memory types per zink heap
|
||||
--- a/src/gallium/drivers/zink/zink_bo.c
|
||||
+++ b/src/gallium/drivers/zink/zink_bo.c
|
||||
@@ -34,6 +34,7 @@
|
||||
#include "zink_resource.h"
|
||||
#include "zink_screen.h"
|
||||
#include "util/u_hash_table.h"
|
||||
+#include "util/u_thread.h"
|
||||
|
||||
#ifdef HAVE_LIBDRM
|
||||
#define ZINK_USE_DMABUF
|
||||
@@ -577,6 +578,7 @@
|
||||
zink_bo_create(struct zink_screen *screen, uint64_t size, unsigned alignment, enum zink_heap heap, enum zink_alloc_flag flags, unsigned mem_type_idx, const void *pNext)
|
||||
{
|
||||
struct zink_bo *bo;
|
||||
+ p_atomic_inc(&screen->pb.alloc_serial);
|
||||
/* pull in sparse flag */
|
||||
flags |= zink_alloc_flags_from_heap(heap);
|
||||
|
||||
@@ -1390,6 +1392,40 @@
|
||||
return bo_slab_alloc(priv, mem_type_idx, entry_size, group_index, false);
|
||||
}
|
||||
|
||||
+/* Slab entries and cached buffers a client frees are otherwise only reclaimed by its next
|
||||
+ * allocation, so a client that goes idle (a browser UI behind a fullscreen game) keeps all of
|
||||
+ * that memory allocated. On UMA devices it is system RAM that cannot be swapped. */
|
||||
+static int
|
||||
+bo_reclaim_thread(void *data)
|
||||
+{
|
||||
+ struct zink_screen *screen = data;
|
||||
+ uint32_t seen = p_atomic_read(&screen->pb.alloc_serial);
|
||||
+
|
||||
+ u_thread_setname("zink_reclaim");
|
||||
+ mtx_lock(&screen->pb.reclaim_lock);
|
||||
+ while (!screen->pb.reclaim_stop) {
|
||||
+ struct timespec deadline;
|
||||
+ timespec_get(&deadline, TIME_UTC);
|
||||
+ deadline.tv_sec += 1;
|
||||
+ cnd_timedwait(&screen->pb.reclaim_cond, &screen->pb.reclaim_lock, &deadline);
|
||||
+ if (screen->pb.reclaim_stop)
|
||||
+ break;
|
||||
+ mtx_unlock(&screen->pb.reclaim_lock);
|
||||
+
|
||||
+ uint32_t serial = p_atomic_read(&screen->pb.alloc_serial);
|
||||
+ if (serial == seen) {
|
||||
+ for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++)
|
||||
+ pb_slabs_reclaim_all(&screen->pb.bo_slabs[i]);
|
||||
+ pb_cache_release_all_buffers(&screen->pb.bo_cache);
|
||||
+ }
|
||||
+ seen = serial;
|
||||
+
|
||||
+ mtx_lock(&screen->pb.reclaim_lock);
|
||||
+ }
|
||||
+ mtx_unlock(&screen->pb.reclaim_lock);
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
bool
|
||||
zink_bo_init(struct zink_screen *screen)
|
||||
{
|
||||
@@ -1425,12 +1461,25 @@
|
||||
min_slab_order = max_order + 1;
|
||||
}
|
||||
screen->pb.min_alloc_size = 1 << screen->pb.bo_slabs[0].min_order;
|
||||
+
|
||||
+ mtx_init(&screen->pb.reclaim_lock, mtx_plain);
|
||||
+ cnd_init(&screen->pb.reclaim_cond);
|
||||
+ screen->pb.reclaim_running =
|
||||
+ u_thread_create(&screen->pb.reclaim_thread, bo_reclaim_thread, screen) == thrd_success;
|
||||
return true;
|
||||
}
|
||||
|
||||
void
|
||||
zink_bo_deinit(struct zink_screen *screen)
|
||||
{
|
||||
+ if (screen->pb.reclaim_running) {
|
||||
+ mtx_lock(&screen->pb.reclaim_lock);
|
||||
+ screen->pb.reclaim_stop = true;
|
||||
+ cnd_signal(&screen->pb.reclaim_cond);
|
||||
+ mtx_unlock(&screen->pb.reclaim_lock);
|
||||
+ thrd_join(screen->pb.reclaim_thread, NULL);
|
||||
+ screen->pb.reclaim_running = false;
|
||||
+ }
|
||||
for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) {
|
||||
if (screen->pb.bo_slabs[i].groups)
|
||||
pb_slabs_deinit(&screen->pb.bo_slabs[i]);
|
||||
Reference in new issue
Block a user