mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f39d71f95 | ||
|
|
1dc49b527b | ||
|
|
cc3fec0768 | ||
|
|
5270574e5a | ||
|
|
a8af973726 | ||
|
|
ed1f8dd2b6 | ||
|
|
e8aaae1343 | ||
|
|
036317f371 | ||
|
|
ce0da01163 | ||
|
|
75ae619e21 | ||
|
|
3efa5acfa6 | ||
|
|
9369dc3031 | ||
|
|
5d84d3fef7 | ||
|
|
51baf75af1 | ||
|
|
20f2c98d18 | ||
|
|
e3ceae412b | ||
|
|
7e6affed12 | ||
|
|
40fc5463f3 | ||
|
|
039948f4d2 | ||
|
|
bbb95e8a60 | ||
|
|
7763d00b78 | ||
|
|
3452730725 | ||
|
|
e50f61f5d9 | ||
|
|
a7a4308e3c | ||
|
|
e811576e79 | ||
|
|
960abec0ed | ||
|
|
855ab88d6c | ||
|
|
f7ee6e78f0 | ||
|
|
293c58aeba | ||
|
|
95b8a4c3c4 | ||
|
|
b7fd52de79 | ||
|
|
53ce764548 | ||
|
|
157e74907a | ||
|
|
015ac26e07 | ||
|
|
1fe7faaa8d | ||
|
|
2e7f99897d | ||
|
|
d7fa65ad20 | ||
|
|
ae614ce476 | ||
|
|
7d6e1cce2f | ||
|
|
bbf46cad9d | ||
|
|
68c7b4b3c8 | ||
|
|
5d38a6c8c5 | ||
|
|
99a0c44f98 | ||
|
|
1812ba20e2 | ||
|
|
771d3c399c | ||
|
|
af74a4449e | ||
|
|
039e14de5a | ||
|
|
3fac2e8945 |
No files matched your search
@@ -84,6 +84,14 @@
|
||||
fixed-shape window instead and STRETCHES it onto the other panel - the app never sees a
|
||||
size change, so nothing it does can help.
|
||||
-->
|
||||
<activity
|
||||
android:name=".input.ControllerEditorActivity"
|
||||
android:exported="false"
|
||||
android:theme="@style/SessionTheme"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
|
||||
|
||||
<activity
|
||||
android:name=".files.FileManagerActivity"
|
||||
android:exported="false"
|
||||
|
||||
@@ -1231,6 +1231,8 @@ EXPORT int close(int fd) {
|
||||
return my_close(fd);
|
||||
}
|
||||
|
||||
static constexpr int kMaxRingWaitMs = 2;
|
||||
|
||||
EXPORT ssize_t read(int fd, void *buf, size_t count) {
|
||||
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
||||
auto controller = controller_map().find(fd);
|
||||
@@ -1323,7 +1325,7 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) {
|
||||
int result = nanosleep(&sleep_time, nullptr);
|
||||
guard.lock();
|
||||
if (result < 0) return -1;
|
||||
if (backoff_ns < 16 * 1000 * 1000) backoff_ns *= 2;
|
||||
if (backoff_ns < kMaxRingWaitMs * 1000 * 1000) backoff_ns *= 2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1469,7 +1471,7 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
|
||||
if (deadline_ms >= 0 && monotonic_ms() >= deadline_ms)
|
||||
return 0;
|
||||
|
||||
if (backoff_ms < 16)
|
||||
if (backoff_ms < kMaxRingWaitMs)
|
||||
backoff_ms *= 2;
|
||||
}
|
||||
}
|
||||
@@ -1644,7 +1646,7 @@ EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
||||
if (deadline_ms >= 0 && monotonic_ms() >= deadline_ms)
|
||||
return 0;
|
||||
|
||||
if (backoff_ms < 16)
|
||||
if (backoff_ms < kMaxRingWaitMs)
|
||||
backoff_ms *= 2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,7 +226,7 @@ static void on_client_created(struct wl_listener *l, void *data) {
|
||||
|
||||
/* ------------------------------------------------------------------ surfaces */
|
||||
|
||||
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP };
|
||||
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE, ROLE_DESKTOP, ROLE_CURSOR };
|
||||
|
||||
struct surface {
|
||||
struct wl_resource *resource;
|
||||
@@ -474,6 +474,69 @@ static struct seat_keyboard g_kbs[MAX_PTRS];
|
||||
static int g_nkbs;
|
||||
static struct seat_touch g_touches[MAX_PTRS];
|
||||
static int g_ntouches;
|
||||
|
||||
/* ---- the client's cursor (wl_pointer.set_cursor) -------------------------------------------
|
||||
* Not composited: under zero-copy the program's buffer goes straight to an Android layer and there
|
||||
* is nothing to composite into. The cursor surface is snapshotted here instead and the app draws it
|
||||
* as its overlay, above every present path (Bannerlator's design). What it buys: the real SHAPE -
|
||||
* labwc's resize arrows at a window's edges and corners, a text field's I-beam - and an
|
||||
* authoritative HIDE (set_cursor with a NULL surface, what a mouse-look game does).
|
||||
* wl_shm cursors (Wine, pixman) are copied directly; a GPU cursor (labwc on Vulkan/GLES, which
|
||||
* wlroots hands over as a dma-buf, usually UBWC) is read back through vkp_image_readback. */
|
||||
#define CURSOR_MAX_PX (256 * 256)
|
||||
static pthread_mutex_t g_cursor_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct surface *g_cursor_surface; /* compositor thread only */
|
||||
static int g_cursor_hx, g_cursor_hy; /* hotspot, surface-local */
|
||||
static uint32_t g_cursor_px[CURSOR_MAX_PX]; /* guarded by g_cursor_lock: ARGB8888 snapshot */
|
||||
static uint32_t g_cursor_rb[CURSOR_MAX_PX]; /* compositor thread: GPU readback staging */
|
||||
static int g_cursor_w, g_cursor_h; /* 0 = nothing to draw */
|
||||
static int g_cursor_hidden = 1; /* the client asked for no pointer */
|
||||
static int g_cursor_serial; /* bumped on every change; the app polls it */
|
||||
|
||||
static void cursor_publish_hidden(void) {
|
||||
pthread_mutex_lock(&g_cursor_lock);
|
||||
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
|
||||
pthread_mutex_unlock(&g_cursor_lock);
|
||||
}
|
||||
|
||||
static void cursor_publish_pixels(const uint8_t *src, int w, int h, size_t stride, int hx, int hy) {
|
||||
if (w <= 0 || h <= 0 || w * h > CURSOR_MAX_PX) return;
|
||||
pthread_mutex_lock(&g_cursor_lock);
|
||||
for (int y = 0; y < h; y++)
|
||||
memcpy(&g_cursor_px[y * w], src + (size_t)y * stride, (size_t)w * 4);
|
||||
g_cursor_w = w; g_cursor_h = h;
|
||||
g_cursor_hx = hx; g_cursor_hy = hy;
|
||||
g_cursor_hidden = 0;
|
||||
g_cursor_serial++;
|
||||
pthread_mutex_unlock(&g_cursor_lock);
|
||||
}
|
||||
|
||||
static void cursor_publish_shm(struct wl_shm_buffer *shm, int hx, int hy) {
|
||||
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
|
||||
if (w <= 0 || h <= 0 || w * h > CURSOR_MAX_PX) return;
|
||||
wl_shm_buffer_begin_access(shm);
|
||||
cursor_publish_pixels((const uint8_t *)wl_shm_buffer_get_data(shm), w, h,
|
||||
(size_t)wl_shm_buffer_get_stride(shm), hx, hy);
|
||||
wl_shm_buffer_end_access(shm);
|
||||
}
|
||||
|
||||
/* Read by the app (UI thread). out = [serial, hidden, w, h, hotspotX, hotspotY, pixels...].
|
||||
* Returns the number of ints written, or 0 if out is too small. */
|
||||
int banner_cursor_snapshot(int *out, int cap) {
|
||||
int n = 0;
|
||||
pthread_mutex_lock(&g_cursor_lock);
|
||||
int need = 6 + (g_cursor_hidden ? 0 : g_cursor_w * g_cursor_h);
|
||||
if (cap >= need) {
|
||||
out[0] = g_cursor_serial; out[1] = g_cursor_hidden;
|
||||
out[2] = g_cursor_w; out[3] = g_cursor_h;
|
||||
out[4] = g_cursor_hx; out[5] = g_cursor_hy;
|
||||
if (!g_cursor_hidden)
|
||||
memcpy(out + 6, g_cursor_px, (size_t)g_cursor_w * g_cursor_h * 4);
|
||||
n = need;
|
||||
}
|
||||
pthread_mutex_unlock(&g_cursor_lock);
|
||||
return n;
|
||||
}
|
||||
struct active_touch { struct surface *surface; int pointer_fallback; };
|
||||
static struct active_touch g_touch_points[MAX_TOUCH_POINTS];
|
||||
static void touch_cancel_surface(struct surface *surface);
|
||||
@@ -686,9 +749,11 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
||||
if (ci && ci->asked_feedback) ci->shm_frames++; /* since it asked for GPU buffers */
|
||||
}
|
||||
|
||||
/* The window the app's performance HUD follows: the latest one to start presenting GPU frames
|
||||
* (X11 binds the HUD to the _MESA_DRV window and counts X presents instead). JNI upcalls. */
|
||||
/* The window the app's performance HUD follows: the latest one at least as big as the last to
|
||||
* start presenting GPU frames (take_dmabuf) (X11 binds the HUD to the _MESA_DRV window and counts X presents instead). JNI upcalls. */
|
||||
static struct surface *g_hud_surface;
|
||||
/* When the HUD's window last presented a frame (now_ns), to let a replacement take over. */
|
||||
static int64_t g_hud_last_ns;
|
||||
extern void banner_on_game_surface(const char *window, const char *gpu); /* window NULL = gone */
|
||||
extern void banner_on_game_frame(void);
|
||||
/* The program behind that window: its Linux pid (the Wayland client's credentials) and executable name
|
||||
@@ -731,6 +796,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
s->buf_h = b->height;
|
||||
s->has_content = b->img != NULL;
|
||||
g_stat_dmabuf++;
|
||||
const int announced_now = !s->announced_vulkan;
|
||||
if (!s->announced_vulkan) {
|
||||
char name[160];
|
||||
s->announced_vulkan = 1;
|
||||
@@ -751,14 +817,23 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
else
|
||||
banner_log("error", "could not import GPU frames from %s (%dx%d, modifier %#llx)",
|
||||
name, b->width, b->height, (unsigned long long)b->modifier);
|
||||
/* The HUD follows the window whether its frames are copied or go straight to the layer:
|
||||
* a zero-copy frame the compositor never imported is still a presented game frame. */
|
||||
if (b->img || ahb_swapchain_has_ahb(b)) {
|
||||
g_hud_surface = s;
|
||||
banner_on_game_surface(name, vkp_gpu_name());
|
||||
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
|
||||
if (ci) banner_on_game_program((int)ci->pid, strncmp(ci->name, "pid ", 4) ? ci->name : "");
|
||||
}
|
||||
}
|
||||
/* The HUD follows the window whether its frames are copied or go straight to the layer: a
|
||||
* zero-copy frame the compositor never imported is still a presented game frame. A
|
||||
* program's small surfaces - gamescope's 1x1 cursor, Qt's menus and tooltips (melonDS) -
|
||||
* came after the game's and drew too rarely to count, which left the HUD on 0 fps while the
|
||||
* game ran at 60. So a new window takes the HUD only when it is at least as big (a
|
||||
* full-screen gamescope over the desktop still does), and a window gone quiet for a second
|
||||
* gives way to whatever draws next. */
|
||||
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
|
||||
(!g_hud_surface || now_ns() - g_hud_last_ns > 1000000000LL ||
|
||||
(announced_now && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||
char name[160];
|
||||
describe(s, name, sizeof(name));
|
||||
g_hud_surface = s;
|
||||
banner_on_game_surface(name, vkp_gpu_name());
|
||||
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
|
||||
if (ci) banner_on_game_program((int)ci->pid, strncmp(ci->name, "pid ", 4) ? ci->name : "");
|
||||
}
|
||||
/* HDR session (gate open): a DXVK game switches to HDR by REBUILDING its swapchain on the same
|
||||
* surface, so the one-shot line above never sees the 10-bit buffers - name every format change. */
|
||||
@@ -780,7 +855,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
* Asking whether the compositor could import it, as this used to, is a question about the
|
||||
* copy path and not about whether a frame happened: a game whose buffers go straight to
|
||||
* the display layer draws on screen while the counter sat at 0.0 fps and 1000.0 ms. */
|
||||
if (s == g_hud_surface) banner_on_game_frame();
|
||||
if (s == g_hud_surface) { g_hud_last_ns = now_ns(); banner_on_game_frame(); }
|
||||
}
|
||||
|
||||
/* ---- hooks for ahb_swapchain.c (zero-copy layers) */
|
||||
@@ -936,8 +1011,26 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
s->pending_buffer = NULL;
|
||||
s->pending_attach = 0;
|
||||
|
||||
if (s->role == ROLE_NONE) {
|
||||
/* Cursor or role-less surface: never drawn (the app draws its own pointer). */
|
||||
if (s->role == ROLE_CURSOR) {
|
||||
/* The client's pointer image, copied out for the app's overlay (see cursor_publish_*)
|
||||
* rather than composited, so it survives the zero-copy and HDR layer paths. */
|
||||
if (!buffer) {
|
||||
cursor_publish_hidden(); /* wlroots clears its cursor surface to hide the pointer */
|
||||
} else if (shm) {
|
||||
cursor_publish_shm(shm, g_cursor_hx, g_cursor_hy);
|
||||
} else if (db && db->n_planes >= 1 && db->width * db->height <= CURSOR_MAX_PX) {
|
||||
if (!db->img && !db->import_failed) {
|
||||
db->img = vkp_image_from_dmabuf(db->fd[0], db->format, db->modifier, db->width, db->height,
|
||||
db->stride[0], db->offset[0]);
|
||||
if (!db->img) db->import_failed = 1;
|
||||
}
|
||||
if (db->img && vkp_image_readback(db->img, g_cursor_rb, CURSOR_MAX_PX) == 0)
|
||||
cursor_publish_pixels((const uint8_t *)g_cursor_rb, db->width, db->height,
|
||||
(size_t)db->width * 4, g_cursor_hx, g_cursor_hy);
|
||||
}
|
||||
if (buffer) wl_buffer_send_release(buffer);
|
||||
} else if (s->role == ROLE_NONE) {
|
||||
/* Role-less surface: never drawn. */
|
||||
if (buffer) wl_buffer_send_release(buffer);
|
||||
} else if (db) {
|
||||
take_dmabuf(s, db, buffer);
|
||||
@@ -1009,6 +1102,7 @@ static void surface_resource_destroy(struct wl_resource *r) {
|
||||
for (int i = 0; i < g_nptrs; i++) if (g_ptrs[i].focus == r) g_ptrs[i].focus = NULL;
|
||||
for (int i = 0; i < g_nkbs; i++) if (g_kbs[i].focus == r) g_kbs[i].focus = NULL;
|
||||
touch_cancel_surface(s);
|
||||
if (g_cursor_surface == s) { g_cursor_surface = NULL; cursor_publish_hidden(); }
|
||||
if (g_grab == s) g_grab = NULL;
|
||||
if (g_key_target == s) g_key_target = NULL;
|
||||
if (g_ime_click == s) g_ime_click = NULL;
|
||||
@@ -2385,9 +2479,23 @@ static uint32_t now_ms(void) {
|
||||
return (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
|
||||
}
|
||||
|
||||
/* wl_pointer.set_cursor: the client tells us its pointer image, or asks for none. A NULL surface
|
||||
* means "no cursor" and is authoritative. The surface itself is snapshotted on its next commit. */
|
||||
static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint32_t serial,
|
||||
struct wl_resource *surface, int32_t hx, int32_t hy) {
|
||||
/* The app draws its own pointer; cursor surfaces stay role-less and aren't drawn. */
|
||||
if (!surface) {
|
||||
if (g_cursor_surface) g_cursor_surface->role = ROLE_NONE;
|
||||
g_cursor_surface = NULL;
|
||||
cursor_publish_hidden();
|
||||
return;
|
||||
}
|
||||
struct surface *s = wl_resource_get_user_data(surface);
|
||||
if (!s) return;
|
||||
if (s->role != ROLE_NONE && s->role != ROLE_CURSOR) return; /* already has another role */
|
||||
s->role = ROLE_CURSOR;
|
||||
g_cursor_surface = s;
|
||||
g_cursor_hx = hx;
|
||||
g_cursor_hy = hy;
|
||||
}
|
||||
static void pointer_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static const struct wl_pointer_interface pointer_impl = {
|
||||
@@ -3102,23 +3210,32 @@ static void touch_down(int id, double x, double y) {
|
||||
struct surface *target = touch_target_at(x, y);
|
||||
if (!target) return;
|
||||
struct wl_client *client = wl_resource_get_client(target->resource);
|
||||
/* A down on an id that is still held means that sequence's up was lost: end it first. The
|
||||
* fingers still down are counted only after that - counted before, a lost up left any_active
|
||||
* set, and on the pointer path every later touch was dropped (a tap or swipe did nothing). */
|
||||
if (g_touch_points[id].surface) touch_cancel_client(client);
|
||||
int any_active = 0;
|
||||
for (int i = 0; i < MAX_TOUCH_POINTS; i++) {
|
||||
struct surface *active = g_touch_points[i].surface;
|
||||
if (!active) continue;
|
||||
any_active = 1;
|
||||
if (active != target) {
|
||||
touch_cancel_all();
|
||||
any_active = 0;
|
||||
break;
|
||||
}
|
||||
any_active = 1;
|
||||
}
|
||||
if (g_touch_points[id].surface) touch_cancel_client(client);
|
||||
struct seat_touch *st;
|
||||
int has_touch = 0;
|
||||
for_each_touch_of(client, st) has_touch = 1;
|
||||
/* One line per gesture (first finger), so a test can see where a touch went. */
|
||||
if (!any_active) {
|
||||
char name[160];
|
||||
describe(target, name, sizeof(name));
|
||||
banner_log("touch", "%s gets %s", name, has_touch ? "touch" : "the pointer (it takes no touch)");
|
||||
}
|
||||
if (!has_touch) {
|
||||
if (any_active) return;
|
||||
if (any_active) return; /* one finger drives the pointer; a second one is ignored */
|
||||
g_touch_points[id].surface = target;
|
||||
g_touch_points[id].pointer_fallback = 1;
|
||||
pointer_event(x, y, BTN_LEFT, 1);
|
||||
|
||||
@@ -1910,6 +1910,104 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* A client's GPU cursor read back to the CPU, for the app's pointer overlay (compositor.c,
|
||||
* wl_pointer.set_cursor). wlroots hands a nested compositor its cursor as a dma-buf from the parent's
|
||||
* formats - on Adreno usually UBWC, which the CPU cannot read - so it is blitted into a small linear,
|
||||
* host-visible image first. Rare (a cursor changes shape, it is not redrawn per frame) and waited
|
||||
* for on the CPU. out: w*h pixels, B8G8R8A8 in memory = 0xAARRGGBB ints. 0 = ok. */
|
||||
static struct vkp_image *g_rb; /* the readback image, kept for the next shape */
|
||||
|
||||
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
|
||||
if (!src || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
|
||||
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) {
|
||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||
if (!img) return -1;
|
||||
img->w = src->w; img->h = src->h;
|
||||
VkImageCreateInfo ici = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D,
|
||||
.format = VK_FORMAT_B8G8R8A8_UNORM, .extent = {src->w, src->h, 1}, .mipLevels = 1,
|
||||
.arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_LINEAR,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
if (g_vk.CreateImage(g_dev, &ici, NULL, &img->image) != VK_SUCCESS) { free(img); return -1; }
|
||||
VkMemoryRequirements req;
|
||||
g_vk.GetImageMemoryRequirements(g_dev, img->image, &req);
|
||||
int idx = memory_type(req.memoryTypeBits,
|
||||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
|
||||
.allocationSize = req.size, .memoryTypeIndex = (uint32_t)idx};
|
||||
if (idx < 0 || g_vk.AllocateMemory(g_dev, &mai, NULL, &img->mem) != VK_SUCCESS) {
|
||||
g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return -1;
|
||||
}
|
||||
g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
|
||||
VkImageSubresource subr = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0};
|
||||
VkSubresourceLayout lay;
|
||||
g_vk.GetImageSubresourceLayout(g_dev, img->image, &subr, &lay);
|
||||
img->offset = lay.offset;
|
||||
img->row_pitch = lay.rowPitch;
|
||||
if (g_vk.MapMemory(g_dev, img->mem, 0, req.size, 0, &img->map) != VK_SUCCESS) {
|
||||
vkp_image_destroy(img); return -1;
|
||||
}
|
||||
g_rb = img;
|
||||
}
|
||||
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||
VkCommandBuffer cmd = g_cmds[0];
|
||||
g_vk.ResetCommandBuffer(cmd, 0);
|
||||
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
|
||||
g_vk.BeginCommandBuffer(cmd, &bi);
|
||||
VkImageMemoryBarrier acq[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
|
||||
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
0, 0, NULL, 0, NULL, 2, acq);
|
||||
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.srcOffsets = {{0, 0, 0}, {src->w, src->h, 1}},
|
||||
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.dstOffsets = {{0, 0, 0}, {src->w, src->h, 1}}};
|
||||
g_vk.CmdBlitImage(cmd, src->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
g_rb->image, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST);
|
||||
VkImageMemoryBarrier done[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
|
||||
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT},
|
||||
/* the client's buffer goes back to it */
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.srcQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
|
||||
0, 0, NULL, 0, NULL, 2, done);
|
||||
g_vk.EndCommandBuffer(cmd);
|
||||
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
|
||||
g_vk.ResetFences(g_dev, 1, &g_fence);
|
||||
VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
|
||||
if (qr != VK_SUCCESS) {
|
||||
if (qr == VK_ERROR_DEVICE_LOST) device_lost("cursor readback");
|
||||
return -1;
|
||||
}
|
||||
VkResult fr = timed_wait(g_fence, 1000000000ULL);
|
||||
if (fr == VK_ERROR_DEVICE_LOST) { device_lost("cursor readback"); return -1; }
|
||||
if (fr != VK_SUCCESS) return -1;
|
||||
for (int y = 0; y < src->h; y++)
|
||||
memcpy(out + (size_t)y * src->w, (const uint8_t *)g_rb->map + g_rb->offset + (size_t)y * g_rb->row_pitch,
|
||||
(size_t)src->w * 4);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- the compositor pass, off-screen
|
||||
*
|
||||
* Layer mode with screen effects on: the game's frame still has to go through the compositor pass
|
||||
|
||||
@@ -146,6 +146,9 @@ int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
* wait_fd: a sync_file the copy must wait for before writing dst (the display's release fence of that
|
||||
* buffer), -1 = none. Always consumed (handed to the GPU, or waited for and closed). */
|
||||
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd);
|
||||
/* A client's GPU cursor (an imported dma-buf, often UBWC) read back as w*h 0xAARRGGBB pixels through a
|
||||
* linear host-visible copy; waited for on the CPU. Compositor thread, between frames. 0 = ok. */
|
||||
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px);
|
||||
/* Refresh the scene -> output mapping for this scene size without presenting (creates the
|
||||
* swapchain if needed, since the mapping is in output pixels). 0 = mapping valid. */
|
||||
int vkp_update_map(int scene_w, int scene_h);
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
extern int banner_wayland_run(void);
|
||||
extern void banner_wayland_send_pointer(int action, int x, int y);
|
||||
extern void banner_wayland_send_touch(int action, int pointer_id, int x, int y);
|
||||
extern int banner_cursor_snapshot(int *out, int cap);
|
||||
extern void banner_wayland_send_key(int evdev, int state);
|
||||
extern void banner_wayland_send_scene_input(int type, int a, int b);
|
||||
extern void banner_wayland_vsync(int64_t frame_time_ns);
|
||||
@@ -278,6 +279,21 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendTouch(
|
||||
banner_wayland_send_touch(action, pointer_id, x, y);
|
||||
}
|
||||
|
||||
/* The client's pointer image and whether it wants one at all (wl_pointer.set_cursor).
|
||||
* out = [serial, hidden, w, h, hotspotX, hotspotY, ARGB pixels...]; returns ints written, 0 if the
|
||||
* array is too small. The app polls the serial and only rebuilds its overlay when it changes. */
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
|
||||
JNIEnv *env, jclass clazz, jintArray out) {
|
||||
if (!out) return 0;
|
||||
jint cap = (*env)->GetArrayLength(env, out);
|
||||
jint *buf = (*env)->GetIntArrayElements(env, out, NULL);
|
||||
if (!buf) return 0;
|
||||
int n = banner_cursor_snapshot((int *)buf, (int)cap);
|
||||
(*env)->ReleaseIntArrayElements(env, out, buf, 0);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Inject a key event. evdev = Linux input keycode (KEY_A=30…); state 1=down 0=up. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey(
|
||||
|
||||
@@ -29,6 +29,7 @@ import com.droiddeck.launcher.gpu.LsfgNative
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
import com.droiddeck.launcher.runtime.DeckyManager
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.ui.PackageRow
|
||||
import com.droiddeck.launcher.session.OfflineMode
|
||||
@@ -45,6 +46,10 @@ import com.droiddeck.launcher.ui.ModeSettings
|
||||
import com.droiddeck.launcher.ui.ModeSettingsActions
|
||||
import com.droiddeck.launcher.ui.DriverRow
|
||||
import com.droiddeck.launcher.ui.ConfirmDialog
|
||||
import com.droiddeck.launcher.ui.ControllerActions
|
||||
import com.droiddeck.launcher.ui.ControllerMappingPage
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.input.ControllerEditorActivity
|
||||
import com.droiddeck.launcher.ui.CreditsDialog
|
||||
import com.droiddeck.launcher.ui.FrontEndScreen
|
||||
import com.droiddeck.launcher.ui.FrontEndState
|
||||
@@ -84,6 +89,15 @@ class MainActivity : ComponentActivity() {
|
||||
private var steamDeckMode by mutableStateOf(false)
|
||||
private var showCredits by mutableStateOf(false)
|
||||
private var showProtons by mutableStateOf(false)
|
||||
private var deckyInstalled by mutableStateOf<String?>(null)
|
||||
private var deckyReleases by mutableStateOf<List<DeckyManager.Release>>(emptyList())
|
||||
private var deckyChecking by mutableStateOf(false)
|
||||
private var deckyStage by mutableStateOf<String?>(null)
|
||||
private var deckyPercent by mutableIntStateOf(-1)
|
||||
private var deckySupervisor by mutableStateOf(false)
|
||||
private var deckyReleaseRequest = 0
|
||||
private var showMapping by mutableStateOf(false)
|
||||
private var controllerSettings by mutableStateOf<ControllerPrefs.Settings?>(null)
|
||||
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
|
||||
private var catalogLoading by mutableStateOf(false)
|
||||
private var packageRows by mutableStateOf<List<PackageRow>?>(null)
|
||||
@@ -233,6 +247,7 @@ class MainActivity : ComponentActivity() {
|
||||
sm != null -> { { ModeSettingsHost(sm) } }
|
||||
showPerformance -> { { PerformanceHost() } }
|
||||
showProtons -> { { ProtonHost() } }
|
||||
showMapping -> { { MappingHost() } }
|
||||
else -> null
|
||||
}
|
||||
FrontEndScreen(
|
||||
@@ -245,7 +260,7 @@ class MainActivity : ComponentActivity() {
|
||||
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
|
||||
frameGenEngine = FrameGen.engine(this), frameGenMultiplier = FrameGen.multiplier(this),
|
||||
lsfgReady = LsfgNative.isInstalled(this),
|
||||
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else null,
|
||||
pageKey = sm?.let { "settings:$it" } ?: if (showPerformance) "performance" else if (showProtons) "protons" else if (showMapping) "controller-mapping" else null,
|
||||
theme = theme,
|
||||
isHomeApp = homeAppSelected,
|
||||
homeScreenEnabled = homeScreenEnabled,
|
||||
@@ -260,11 +275,16 @@ class MainActivity : ComponentActivity() {
|
||||
sessionRunning = SessionState.running,
|
||||
backActionsInverted = backActionsInverted,
|
||||
buildLabel = BuildConfig.BUILD_LABEL,
|
||||
oscMode = oscMode,
|
||||
controller = controllerSettings,
|
||||
),
|
||||
FrontEndActions(
|
||||
onPlay = { startSession(Intent(this, SessionActivity::class.java)) },
|
||||
// Steam's desktop client as a window on the desktop: under gamescope the
|
||||
// client puts itself into Big Picture whatever it is started with.
|
||||
onPlayDesktopUi = {
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"))
|
||||
},
|
||||
onSteamGame = { g ->
|
||||
@@ -295,7 +315,7 @@ class MainActivity : ComponentActivity() {
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
},
|
||||
onProtons = { openProtons() },
|
||||
onPerformance = { refreshCores(); showProtons = false; showPerformance = true },
|
||||
onPerformance = { refreshCores(); showProtons = false; showMapping = false; showPerformance = true },
|
||||
onRoms = { showRoms = true },
|
||||
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
|
||||
onLogs = {
|
||||
@@ -316,7 +336,7 @@ class MainActivity : ComponentActivity() {
|
||||
offline = OfflineMode.enabled(this)
|
||||
},
|
||||
onCredits = { showCredits = true },
|
||||
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false },
|
||||
onPageBack = { settingsMode = null; showPerformance = false; showProtons = false; showMapping = false },
|
||||
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
|
||||
onHomeApp = { manageHomeApp() },
|
||||
onHomeScreen = { on ->
|
||||
@@ -331,6 +351,18 @@ class MainActivity : ComponentActivity() {
|
||||
onCheckLatestBuild = {
|
||||
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/The412Banner/DroidDeck/actions/workflows/build.yml")))
|
||||
},
|
||||
controller = ControllerActions(
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
onTint = { t -> ControllerPrefs.setTint(this, t); refreshController() },
|
||||
onOpacity = { o -> ControllerPrefs.setOpacity(this, o); refreshController() },
|
||||
onSize = { v -> ControllerPrefs.setSize(this, v); refreshController() },
|
||||
onStickClick = { on -> ControllerPrefs.setStickClick(this, on); refreshController() },
|
||||
onAdaptiveSticks = { on -> ControllerPrefs.setAdaptiveSticks(this, on); refreshController() },
|
||||
onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) },
|
||||
onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() },
|
||||
onMapping = { settingsMode = null; showPerformance = false; showProtons = false; showMapping = true },
|
||||
onResetAll = { ControllerPrefs.resetAll(this); refreshController() },
|
||||
),
|
||||
),
|
||||
page = page,
|
||||
)
|
||||
@@ -379,14 +411,22 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
|
||||
// A session folder left without its ending - the process was killed - gets it now.
|
||||
if (!SessionState.running) Thread({ SessionArtifacts.finishAbandoned(this) }, "finish-abandoned").start()
|
||||
if (!SessionState.running) Thread({
|
||||
SessionArtifacts.finishAbandoned(this)
|
||||
SessionArtifacts.scrubOlder(this)
|
||||
}, "finish-abandoned").start()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
refreshController()
|
||||
refreshHomeAppState()
|
||||
refreshSecondScreenDisplays()
|
||||
refresh()
|
||||
deckyInstalled = DeckyManager.installed(this)
|
||||
DeckyManager.syncCefMarker(this)
|
||||
deckySupervisor = DeckyManager.supervisorEnabled(this)
|
||||
// Added games' art (a store lookup for what the folders lack) starts here, not only when
|
||||
// the cog opens.
|
||||
refreshAddedGames()
|
||||
@@ -452,10 +492,57 @@ class MainActivity : ComponentActivity() {
|
||||
private fun openProtons() {
|
||||
settingsMode = null
|
||||
showPerformance = false
|
||||
showMapping = false
|
||||
showProtons = true
|
||||
refreshProtons()
|
||||
}
|
||||
|
||||
private fun refreshDecky() {
|
||||
val request = ++deckyReleaseRequest
|
||||
deckyChecking = true
|
||||
Thread({
|
||||
val channels = runCatching { DeckyManager.releaseChannels(this) }
|
||||
.getOrElse { DeckyManager.ReleaseChannels(emptyList(), emptyList()) }
|
||||
ui.post {
|
||||
if (request == deckyReleaseRequest) {
|
||||
// Use the newest compatible stable build, or the newest compatible
|
||||
// prerelease when the fork has not published a stable ARM64 asset.
|
||||
deckyReleases = channels.stable.ifEmpty { channels.prerelease }
|
||||
deckyChecking = false
|
||||
}
|
||||
}
|
||||
}, "decky-releases").start()
|
||||
}
|
||||
|
||||
private fun installDecky(release: DeckyManager.Release) {
|
||||
if (deckyStage != null || SessionState.running) return
|
||||
deckyStage = "Starting…"; deckyPercent = -1
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
DeckyManager.install(this, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } }
|
||||
}.getOrElse { error -> "Decky install failed: ${error.message ?: error.javaClass.simpleName}" }
|
||||
ui.post {
|
||||
deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(this)
|
||||
if (problem != null) android.widget.Toast.makeText(this, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}, "install-decky").start()
|
||||
}
|
||||
|
||||
private fun refreshController() {
|
||||
controllerSettings = ControllerPrefs.read(this)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MappingHost() {
|
||||
val settings = controllerSettings ?: return
|
||||
ControllerMappingPage(
|
||||
mapping = settings.mapping,
|
||||
onPick = { id, target -> ControllerPrefs.setTarget(this, id, target); refreshController() },
|
||||
onReset = { ControllerPrefs.resetMapping(this); refreshController() },
|
||||
onBack = { showMapping = false },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProtonHost() {
|
||||
ProtonPage(
|
||||
@@ -578,6 +665,10 @@ class MainActivity : ComponentActivity() {
|
||||
addedGamesArt = addedGamesArt,
|
||||
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, releaseStatus = releaseStatus,
|
||||
releaseChecking = releaseChecking, canRestoreBundled = canRestoreBundled,
|
||||
deckyInstalled = if (mode == SessionService.MODE_STEAM) deckyInstalled else null,
|
||||
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) deckyReleases.firstOrNull() else null,
|
||||
deckyChecking = deckyChecking, deckyStage = deckyStage, deckyPercent = deckyPercent,
|
||||
deckyEnabled = deckySupervisor, deckySessionRunning = SessionState.running,
|
||||
),
|
||||
ModeSettingsActions(
|
||||
onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
|
||||
@@ -627,6 +718,14 @@ class MainActivity : ComponentActivity() {
|
||||
pendingAddedGame = folder
|
||||
pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), "Choose the game's .exe", folder))
|
||||
},
|
||||
onDeckyInstall = { release -> installDecky(release) },
|
||||
onDeckyCheck = { refreshDecky() },
|
||||
onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); deckySupervisor = enabled },
|
||||
onDeckyUninstall = {
|
||||
DeckyManager.uninstall(this, wipeData = false)
|
||||
deckyInstalled = null
|
||||
deckySupervisor = false
|
||||
},
|
||||
onDismiss = { settingsMode = null },
|
||||
),
|
||||
)
|
||||
@@ -682,6 +781,7 @@ class MainActivity : ComponentActivity() {
|
||||
private fun openModeSettings(mode: String) {
|
||||
showPerformance = false
|
||||
showProtons = false
|
||||
showMapping = false
|
||||
refreshDrivers()
|
||||
resolutionCap = SessionPrefs.resolutionCap(this, mode)
|
||||
customResolution = SessionPrefs.customResolution(this, mode)
|
||||
@@ -703,6 +803,11 @@ class MainActivity : ComponentActivity() {
|
||||
renderer = SessionPrefs.desktopRenderer(this)
|
||||
gameStorage = SessionPrefs.gameStorage(this)
|
||||
storageOptions = GameStorage.options(this).map { it.label to it.path }
|
||||
if (mode == SessionService.MODE_STEAM) {
|
||||
deckyInstalled = DeckyManager.installed(this)
|
||||
deckySupervisor = DeckyManager.supervisorEnabled(this)
|
||||
refreshDecky()
|
||||
}
|
||||
settingsMode = mode
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.LsfgNative
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
@@ -50,12 +51,14 @@ import com.droiddeck.launcher.session.PerfMode
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.session.SessionArtifacts
|
||||
import com.droiddeck.launcher.session.SessionLogShare
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.wayland.HdrSupport
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.ui.CursorOverlay
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import com.droiddeck.launcher.ui.DrawerActions
|
||||
import com.droiddeck.launcher.ui.HudText
|
||||
import com.droiddeck.launcher.ui.LoadingOverlay
|
||||
@@ -93,6 +96,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var cursorPos by mutableStateOf(androidx.compose.ui.geometry.Offset(-100f, -100f))
|
||||
private var cursorVisible by mutableStateOf(false)
|
||||
private val cursorHide = Runnable { cursorVisible = false }
|
||||
/** When the pad or the on-screen controls were last used (uptimeMillis); see [showCursor]. */
|
||||
private var lastPadInputMs = 0L
|
||||
// The program's own pointer, from wl_pointer.set_cursor (see syncClientCursor): its image in
|
||||
// session pixels, hotspot, and whether it asked for no pointer at all.
|
||||
private val cursorBuf = IntArray(WaylandCompositor.CURSOR_BUF_INTS)
|
||||
private var cursorSerial = 0
|
||||
private var clientHidesCursor = false
|
||||
private var cursorImage by mutableStateOf<androidx.compose.ui.graphics.ImageBitmap?>(null)
|
||||
private var cursorHotX by mutableStateOf(0)
|
||||
private var cursorHotY by mutableStateOf(0)
|
||||
private var cursorImageScale by mutableStateOf(1f)
|
||||
/** labwc changes the shape a moment after the move that reached an edge: look again then. */
|
||||
private val cursorResync = Runnable { if (syncClientCursor() && clientHidesCursor) cursorVisible = false }
|
||||
private val uiHandler = Handler(Looper.getMainLooper())
|
||||
private var pendingBackAction: Runnable? = null
|
||||
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
|
||||
@@ -135,6 +151,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var frameGenEngine by mutableStateOf(FrameGen.ENGINE_OFF)
|
||||
private var frameGenMultiplier by mutableStateOf(2)
|
||||
private var fexPreset by mutableStateOf("")
|
||||
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
|
||||
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
|
||||
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
|
||||
private var secondScreenMode by mutableStateOf(SecondScreenMode.NONE)
|
||||
@@ -195,6 +212,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
|
||||
padBridge = bridge
|
||||
// A player on the pad or the on-screen controls has no use for the mouse arrow; the next
|
||||
// touchpad or mouse move brings it back (showCursor), once the pad has been quiet a moment.
|
||||
bridge.setOnPlayerInput {
|
||||
lastPadInputMs = android.os.SystemClock.uptimeMillis()
|
||||
uiHandler.removeCallbacks(cursorHide)
|
||||
cursorVisible = false
|
||||
}
|
||||
onScreenControls = OnScreenControls(this, bridge).also { root.addView(it) }
|
||||
keyboard = KeyboardHost(this).also { root.addView(it) }
|
||||
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
|
||||
@@ -229,7 +253,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
isFocusableInTouchMode = true
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density)
|
||||
CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density,
|
||||
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
|
||||
if (hud.text.isNotEmpty()) HudText(hud.text)
|
||||
if (loading.visible) LoadingOverlay(loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended)
|
||||
// Opening the drawer takes the controller away from the game: release its pad.
|
||||
@@ -260,7 +285,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null,
|
||||
frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier,
|
||||
lsfgReady = LsfgNative.isInstalled(this@SessionActivity),
|
||||
oscMode = oscMode, touchMode = touchMode,
|
||||
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
|
||||
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
|
||||
shapeMode = shapeMode, fexPreset = fexPreset,
|
||||
secondScreenMode = secondScreenMode,
|
||||
@@ -277,12 +302,27 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen },
|
||||
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
|
||||
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
|
||||
// The desktop with Steam's desktop client in it, in this session's place: the
|
||||
// session ends with status 0 and onSessionEnded starts the relaunch (Stop's
|
||||
// finish() would skip it).
|
||||
onSwitchToDesktop = if (SessionState.mode == SessionService.MODE_STEAM) ({
|
||||
drawerOpen = false
|
||||
SessionState.relaunch = Intent(this@SessionActivity, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop")
|
||||
SessionService.stop(this@SessionActivity)
|
||||
}) else null,
|
||||
backActionsInverted = backActionsInverted,
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
||||
backActionsInverted = inverted
|
||||
},
|
||||
onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() },
|
||||
onSuspendPolicy = { policy ->
|
||||
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
|
||||
suspendPolicy = policy
|
||||
SessionService.suspendPolicyChanged(this@SessionActivity)
|
||||
},
|
||||
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
||||
onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() },
|
||||
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
|
||||
@@ -299,6 +339,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
},
|
||||
onBackground = { drawerOpen = false; moveTaskToBack(true) },
|
||||
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
|
||||
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
||||
onClose = { drawerOpen = false },
|
||||
))
|
||||
@@ -383,6 +424,30 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
|
||||
}
|
||||
|
||||
private fun shareCurrentSessionLogs() {
|
||||
val folder = SessionPaths.current()
|
||||
if (folder == null || !folder.isDirectory) {
|
||||
Toast.makeText(this, "No logs for this session.", Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
Thread({
|
||||
val zip = runCatching { SessionLogShare.zipFolder(this, folder) }
|
||||
.onFailure { Log.w(TAG, "could not package current session logs", it) }
|
||||
.getOrNull()
|
||||
uiHandler.post {
|
||||
if (zip == null) {
|
||||
Toast.makeText(this, "Could not create the session log archive.", Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
runCatching { startActivity(SessionLogShare.shareIntent(this, zip)) }
|
||||
.onFailure {
|
||||
Log.w(TAG, "could not share current session logs", it)
|
||||
Toast.makeText(this, "Could not share the session logs.", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}, "share-session-logs").start()
|
||||
}
|
||||
|
||||
private fun readPrefs() {
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
fillScreen = SessionPrefs.forceFullscreen(this)
|
||||
@@ -391,6 +456,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
frameGenEngine = FrameGen.engine(this)
|
||||
frameGenMultiplier = FrameGen.multiplier(this)
|
||||
fexPreset = SessionPrefs.fexPreset(this)
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
shapeMode = SessionPrefs.shapeMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
@@ -516,7 +582,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// was 16:9 - the picture came back squashed sideways. While a session runs, keep its size.
|
||||
val size = if (SessionState.running) SessionState.outputSize else outputSize()
|
||||
SessionState.outputSize = size
|
||||
onScreenControls?.setPicture(drawnRect())
|
||||
if (!SessionState.running) SessionState.refreshHz = refreshHz()
|
||||
// Letterbox, never stretch or crop: the output can be a different shape from the panel,
|
||||
// and a game's picture must keep its proportions with bars, not lose its edges.
|
||||
@@ -592,8 +657,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val resized = surfaceW != 0 && (width != surfaceW || height != surfaceH)
|
||||
surfaceW = width
|
||||
surfaceH = height
|
||||
// The on-screen controls follow the picture: into the bars beside or under it when there are any.
|
||||
onScreenControls?.setPicture(drawnRect())
|
||||
if (resized) {
|
||||
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
|
||||
CompositorHost.resize(holder.surface) { applyFrameGen() }
|
||||
@@ -642,7 +705,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
|
||||
// A custom resolution is taken as given; the compositor fits it to the panel.
|
||||
SessionPrefs.customResolution(this, mode)?.let { return it }
|
||||
val cap = SessionPrefs.resolutionCap(this, mode)
|
||||
// An emulator whose frames cost next to nothing (Library.drawsAtPanel) gets the panel,
|
||||
// unless the user chose a resolution for the mode.
|
||||
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
val cap = if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
|
||||
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode)) 0
|
||||
else SessionPrefs.resolutionCap(this, mode)
|
||||
val height = (if (cap <= 0) panelH else minOf(panelH, cap.toFloat())).toInt()
|
||||
val width = (height * aspect).toInt()
|
||||
// Odd sizes upset the scaler; both dimensions even is what every mode here would be.
|
||||
@@ -698,11 +766,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (status == 0) {
|
||||
runOnUiThread {
|
||||
if (isFinishing || isDestroyed) return@runOnUiThread
|
||||
// A session the guest asked for (the desktop's Steam launchers) takes this one's
|
||||
// place: the compositor stays, a new activity attaches and starts the service.
|
||||
// A session asked for in this one's place (the desktop's Steam launchers, the
|
||||
// drawer's DESKTOP) starts here: this activity restarts on its intent, as an agent
|
||||
// start does. startActivity(next) could not do it - the activity is singleTop, so
|
||||
// the request landed in this instance's onNewIntent and went with its finish().
|
||||
SessionState.relaunch?.let { next ->
|
||||
SessionState.relaunch = null
|
||||
startActivity(next)
|
||||
setIntent(next)
|
||||
recreate()
|
||||
return@runOnUiThread
|
||||
}
|
||||
finish()
|
||||
}
|
||||
@@ -974,14 +1046,59 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
showCursor(x.coerceIn(left, left + drawnW), y.coerceIn(top, top + drawnH))
|
||||
}
|
||||
|
||||
/** The arrow stays on a desktop; in a Steam session it shows for a moment after each move. */
|
||||
/**
|
||||
* The arrow stays on a desktop; in a Steam session it shows for a moment after each move. While
|
||||
* a controller is driving (input in the last [CURSOR_PAD_HOLD_MS]) it stays hidden, so a touch
|
||||
* during play does not flash it up - Bannerlator's rule for its Wayland pointer.
|
||||
*/
|
||||
private fun showCursor(x: Float, y: Float) {
|
||||
cursorPos = androidx.compose.ui.geometry.Offset(x, y)
|
||||
syncClientCursor()
|
||||
uiHandler.removeCallbacks(cursorResync)
|
||||
uiHandler.postDelayed(cursorResync, 60)
|
||||
// A program that asked for no pointer (a mouse-look game) wins over everything below.
|
||||
if (clientHidesCursor) { cursorVisible = false; return }
|
||||
if (android.os.SystemClock.uptimeMillis() - lastPadInputMs < CURSOR_PAD_HOLD_MS) return
|
||||
cursorVisible = true
|
||||
uiHandler.removeCallbacks(cursorHide)
|
||||
if (SessionState.mode == SessionService.MODE_STEAM && SessionState.steamUi != "desktop") uiHandler.postDelayed(cursorHide, 2500)
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls the program's pointer (wl_pointer.set_cursor) if it changed: labwc's resize arrows at a
|
||||
* window's edges and corners, a text field's I-beam, or a request for no pointer. Serial 0 = no
|
||||
* program has set one yet, and the built-in arrow stays. Returns true when something changed.
|
||||
*/
|
||||
private fun syncClientCursor(): Boolean {
|
||||
if (!CompositorHost.isStarted) return false
|
||||
val n = WaylandCompositor.nativeCursorSnapshot(cursorBuf)
|
||||
if (n < 6) return false
|
||||
val serial = cursorBuf[0]
|
||||
if (serial == 0 || serial == cursorSerial) return false
|
||||
cursorSerial = serial
|
||||
clientHidesCursor = cursorBuf[1] != 0
|
||||
if (clientHidesCursor) return true
|
||||
val w = cursorBuf[2]
|
||||
val h = cursorBuf[3]
|
||||
if (w <= 0 || h <= 0 || n < 6 + w * h) return false
|
||||
val bitmap = try {
|
||||
android.graphics.Bitmap.createBitmap(cursorBuf, 6, w, w, h, android.graphics.Bitmap.Config.ARGB_8888)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "cursor bitmap failed", e)
|
||||
return false
|
||||
}
|
||||
cursorImage = bitmap.asImageBitmap()
|
||||
cursorHotX = cursorBuf[4]
|
||||
cursorHotY = cursorBuf[5]
|
||||
// Session pixels -> screen pixels, as the session's picture is scaled (movePointer).
|
||||
val width = surfaceView.width.takeIf { it > 0 }
|
||||
val height = surfaceView.height.takeIf { it > 0 }
|
||||
val out = SessionState.outputSize
|
||||
if (width != null && height != null)
|
||||
cursorImageScale = minOf(width / out.first.toFloat(), height / out.second.toFloat())
|
||||
return true
|
||||
}
|
||||
|
||||
private fun refreshSecondScreenDisplays() {
|
||||
if (!::displayManager.isInitialized) return
|
||||
val primaryId = display?.displayId ?: windowManager.defaultDisplay.displayId
|
||||
@@ -1114,7 +1231,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
WaylandCompositor.nativeSendTouch(action, event.getPointerId(index), (x * 1919f).toInt(), (y * 1079f).toInt())
|
||||
}
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> sendTouch(0, event.actionIndex)
|
||||
// A first finger starts a new gesture, and Android has ended every earlier one: whatever
|
||||
// the compositor still holds (an up lost to the drawer opening mid-touch) goes first.
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
|
||||
sendTouch(0, event.actionIndex)
|
||||
}
|
||||
MotionEvent.ACTION_POINTER_DOWN -> sendTouch(0, event.actionIndex)
|
||||
MotionEvent.ACTION_MOVE -> for (index in 0 until event.pointerCount) sendTouch(1, index)
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> sendTouch(2, event.actionIndex)
|
||||
MotionEvent.ACTION_CANCEL -> WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
|
||||
@@ -1222,6 +1345,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
(getSystemService(INPUT_SERVICE) as? InputManager)
|
||||
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
|
||||
onScreenControls?.reload()
|
||||
updateOnScreenControls()
|
||||
readPrefs()
|
||||
if (CompositorHost.isStarted) applyFrameGen()
|
||||
@@ -1236,6 +1360,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return
|
||||
val decor = window.decorView
|
||||
decor.requestUnbufferedDispatch(UNBUFFERED_SOURCES)
|
||||
decor.viewTreeObserver.addOnGlobalFocusChangeListener { _, _ -> decor.post { decor.requestUnbufferedDispatch(UNBUFFERED_SOURCES) } }
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) goFullscreen()
|
||||
@@ -1283,7 +1415,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionActivity"
|
||||
private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION
|
||||
private const val BACK_DOUBLE_PRESS_TIMEOUT_MS = 500L
|
||||
private const val CURSOR_PAD_HOLD_MS = 1200L
|
||||
private const val DRAWER_HAT_THRESHOLD = 0.5f
|
||||
private const val DRAWER_STICK_ENTER_THRESHOLD = 0.55f
|
||||
private const val DRAWER_STICK_EXIT_THRESHOLD = 0.35f
|
||||
|
||||
@@ -12,9 +12,16 @@ package com.droiddeck.launcher.core
|
||||
* client logs; the account-name registration is left out because this app never learns it.
|
||||
*
|
||||
* What is deliberately KEPT, because it is what makes a log worth reading: EResult codes, CM host
|
||||
* names and IP addresses, timings, token expiry dates, app IDs, pids, connection-state changes and
|
||||
* file paths. A SteamID is masked rather than deleted - first four and last four digits survive -
|
||||
* so a reader can still tell two accounts' lines apart without the value identifying either.
|
||||
* names and Valve's server addresses, timings, token expiry dates, app IDs, pids, connection-state
|
||||
* changes and file paths. A SteamID is masked rather than deleted - first four and last four digits
|
||||
* survive - so a reader can still tell two accounts' lines apart without the value identifying either.
|
||||
*
|
||||
* The device's OWN addresses are not kept: the client's IPv6 check logs "external address <ours>"
|
||||
* about twenty times a session, and a public IPv6 address is the user's. [learnOwnAddresses] reads
|
||||
* the link the session was given (etc/bannerlator-net) and every address on the same /64 - privacy
|
||||
* addresses rotate inside it - or an own public IPv4 is replaced wherever it appears. Likewise every
|
||||
* Steam account and persona name on the device ([learnAccounts]), for users who sign in with an
|
||||
* account name rather than an email.
|
||||
*/
|
||||
object LogRedactor {
|
||||
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
|
||||
@@ -48,6 +55,145 @@ object LogRedactor {
|
||||
private val LONG_TOKEN = Regex("[A-Za-z0-9_\\-]{88,}")
|
||||
private val STEAMID64 = Regex("\\b(76561)(\\d{8})(\\d{4})\\b")
|
||||
private val STEAMID3 = Regex("\\[U:1:(\\d+)]")
|
||||
/** "external address 2607:..." / "external IP: 203.0.113.9" - the client stating ours. */
|
||||
private val EXTERNAL_ADDR = Regex("(?i)(external\\s+(?:ip\\s+)?address\\s*[:=]?\\s*|external\\s+ip\\s*[:=]?\\s*)([0-9A-Fa-f:.]{7,})")
|
||||
private val IPV4 = Regex("(?<![0-9.])(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})(?![0-9.])")
|
||||
/** An IPv6 literal: "::" somewhere, or all eight groups (a clock's 10:03:05 is neither). */
|
||||
private val IPV6 = Regex("(?<![0-9A-Za-z:])[0-9A-Fa-f]{0,4}(?::[0-9A-Fa-f]{0,4}){2,7}(?:%[A-Za-z0-9_.]+)?(?![0-9A-Za-z:])")
|
||||
|
||||
/**
|
||||
* The account a Steam UI login line names ("Login: OnLoginStateChange <account> 2 1 0 0"): a
|
||||
* user who signs in with a plain account name, not an email, had it in every log. The single
|
||||
* space then a non-space keeps "OnLoginStateChange 0 1 0 0" (no account yet) as it is.
|
||||
*/
|
||||
private val LOGIN_STATE = Regex("(OnLoginStateChange )(\\S+)")
|
||||
private val LOGIN_USERS = Regex("(OnLoginUsersChanged )(\\S.*)$")
|
||||
|
||||
/** The device's Steam accounts and persona names as patterns (see [learnAccounts]). */
|
||||
@Volatile
|
||||
private var accounts: List<Regex> = emptyList()
|
||||
|
||||
/**
|
||||
* Learns every Steam account on the device from the client's loginusers.vdf - its AccountName
|
||||
* and PersonaName - so they are replaced wherever a log mentions them, whoever the user is.
|
||||
* Names under three characters are skipped: blanking every "a" would ruin a log.
|
||||
*/
|
||||
fun learnAccounts(loginUsers: java.io.File) {
|
||||
val found = ArrayList<Regex>()
|
||||
try {
|
||||
if (loginUsers.isFile) {
|
||||
val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"")
|
||||
kv.findAll(loginUsers.readText()).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.distinct().forEach { name ->
|
||||
found += Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])")
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
return
|
||||
}
|
||||
accounts = found
|
||||
}
|
||||
|
||||
/** Everything the session's runtime can tell about whose logs these are: addresses and accounts. */
|
||||
fun learnFromRuntime(root: java.io.File) {
|
||||
learnOwnAddresses(java.io.File(root, "etc/bannerlator-net"))
|
||||
learnAccounts(java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"))
|
||||
}
|
||||
|
||||
/** This device's public addresses as patterns (see [learnOwnAddresses]); empty until learned. */
|
||||
@Volatile
|
||||
private var own: List<Regex> = emptyList()
|
||||
|
||||
/**
|
||||
* Learns the device's addresses from the link file the app writes for the session
|
||||
* (`addr <address> <prefix>` lines). Global IPv6 become their /64, public IPv4 stay exact;
|
||||
* private, link-local and loopback addresses identify nobody and are left out.
|
||||
*/
|
||||
fun learnOwnAddresses(linkFile: java.io.File) {
|
||||
val found = ArrayList<Regex>()
|
||||
try {
|
||||
if (linkFile.isFile) linkFile.forEachLine { line ->
|
||||
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine
|
||||
when (kind(addr)) {
|
||||
"public IPv6" -> {
|
||||
val groups = expand6(addr)?.take(4) ?: return@forEachLine
|
||||
// Any spelling of an address in this /64: leading zeros dropped, :: anywhere after.
|
||||
val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) }
|
||||
found += Regex("(?i)(?<![0-9A-Fa-f:])$prefix(?::[0-9A-Fa-f]{0,4}){1,4}(?:%[A-Za-z0-9_.]+)?")
|
||||
}
|
||||
"public IPv4" -> found += Regex("(?<![0-9.])" + Regex.escape(addr) + "(?![0-9.])")
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
return
|
||||
}
|
||||
own = found
|
||||
}
|
||||
|
||||
/** "public IPv6", "private IPv4", "link-local IPv6", ... for an address literal; null if it is not one. */
|
||||
fun kind(address: String): String? {
|
||||
val a = address.substringBefore('%')
|
||||
IPV4.matchEntire(a)?.let { m ->
|
||||
val o = m.groupValues.drop(1).map { it.toInt() }
|
||||
if (o.any { it > 255 }) return null
|
||||
return when {
|
||||
o[0] == 127 -> "loopback IPv4"
|
||||
o[0] == 10 || (o[0] == 172 && o[1] in 16..31) || (o[0] == 192 && o[1] == 168) -> "private IPv4"
|
||||
o[0] == 169 && o[1] == 254 -> "link-local IPv4"
|
||||
o[0] == 100 && o[1] in 64..127 -> "carrier-NAT IPv4"
|
||||
else -> "public IPv4"
|
||||
}
|
||||
}
|
||||
val g = expand6(a) ?: return null
|
||||
val first = g[0].toInt(16)
|
||||
return when {
|
||||
g.all { it.toInt(16) == 0 } || (g.take(7).all { it.toInt(16) == 0 } && g[7].toInt(16) == 1) -> "loopback IPv6"
|
||||
first and 0xffc0 == 0xfe80 -> "link-local IPv6"
|
||||
first and 0xfe00 == 0xfc00 -> "private IPv6"
|
||||
else -> "public IPv6"
|
||||
}
|
||||
}
|
||||
|
||||
/** The eight groups of an IPv6 literal, or null. */
|
||||
private fun expand6(address: String): List<String>? {
|
||||
val a = address.substringBefore('%')
|
||||
if (!a.contains(':') || a.count { it == ':' } > 7 || a.contains(":::")) return null
|
||||
if (!a.all { it.isDigit() || it in 'a'..'f' || it in 'A'..'F' || it == ':' }) return null
|
||||
val parts = if (a.contains("::")) {
|
||||
val (head, tail) = a.split("::", limit = 2)
|
||||
val h = if (head.isEmpty()) emptyList() else head.split(':')
|
||||
val t = if (tail.isEmpty()) emptyList() else tail.split(':')
|
||||
if (h.size + t.size > 7) return null
|
||||
h + List(8 - h.size - t.size) { "0" } + t
|
||||
} else a.split(':')
|
||||
if (parts.size != 8 || parts.any { it.isEmpty() || it.length > 4 }) return null
|
||||
return parts.map { it.lowercase() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Every IP address in [text] replaced by what kind it is ("<public IPv6>"), for reports whose
|
||||
* point is the shape of the network, not its numbers.
|
||||
*/
|
||||
fun describeAddresses(text: String): String {
|
||||
var out = IPV6.replace(text) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
|
||||
out = IPV4.replace(out) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
|
||||
return out
|
||||
}
|
||||
|
||||
/** A file worth scrubbing: text (no NUL in its first 4 KB) and not huge. */
|
||||
fun isText(file: java.io.File): Boolean = try {
|
||||
file.isFile && file.length() < 64L * 1024 * 1024 && file.inputStream().use { input ->
|
||||
val buf = ByteArray(4096)
|
||||
val n = input.read(buf)
|
||||
n <= 0 || (0 until n).none { buf[it].toInt() == 0 }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
|
||||
/** [src]'s lines, scrubbed, to [out]. */
|
||||
fun scrubTo(src: java.io.File, out: java.io.Writer) {
|
||||
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
|
||||
}
|
||||
|
||||
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
|
||||
fun redact(line: String): String {
|
||||
@@ -66,6 +212,11 @@ object LogRedactor {
|
||||
val id = m.groupValues[1]
|
||||
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
|
||||
}
|
||||
out = EXTERNAL_ADDR.replace(out) { "${it.groupValues[1]}<redacted:ip>" }
|
||||
for (r in own) out = r.replace(out, "<redacted:ip>")
|
||||
out = LOGIN_STATE.replace(out) { "${it.groupValues[1]}<redacted:account>" }
|
||||
out = LOGIN_USERS.replace(out) { "${it.groupValues[1]}<redacted:account>" }
|
||||
for (r in accounts) out = r.replace(out, "<redacted:account>")
|
||||
out = EMAIL.replace(out, "<redacted:email>")
|
||||
out = RESIDUAL.replace(out) { "${it.groupValues[1]}=<redacted:token>" }
|
||||
out = LONG_TOKEN.replace(out, "<redacted:token>")
|
||||
|
||||
@@ -27,7 +27,12 @@ object NetworkReport {
|
||||
|
||||
fun write(context: Context, target: File) {
|
||||
try {
|
||||
target.writeText(build(context))
|
||||
// Addresses as their kind ("<public IPv6>"), never the numbers: a public address is the
|
||||
// user's, and this file goes into shared session logs. The session's made-up hardware
|
||||
// address is stable per device (seeded from ANDROID_ID), so it is masked too.
|
||||
val text = LogRedactor.describeAddresses(build(context))
|
||||
.replace(Regex("(?m)^(\\s*mac )\\S+"), "$1<masked>")
|
||||
target.writeText(text)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not write $target", e)
|
||||
}
|
||||
@@ -36,7 +41,7 @@ object NetworkReport {
|
||||
private fun build(context: Context): String = buildString {
|
||||
append("Network as the session starts\n")
|
||||
append("=============================\n")
|
||||
append("The SSID is deliberately not recorded. Transport, address families and DNS are.\n\n")
|
||||
append("The SSID is deliberately not recorded, and addresses appear as their kind, not their numbers.\n\n")
|
||||
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
|
||||
val network = cm?.activeNetwork
|
||||
if (cm == null || network == null) {
|
||||
|
||||
@@ -26,7 +26,35 @@ object Library {
|
||||
}
|
||||
|
||||
/** The client's own tools and runtimes live in steamapps beside the games; they are not titles. */
|
||||
private val NOT_GAMES = setOf(228980, 1493710, 3127680, 4183110, 4427310, 4185400)
|
||||
private val NOT_GAMES = setOf(
|
||||
858280, // Proton 3.7
|
||||
961940, // Proton 3.16
|
||||
993090, // Lossless Scaling
|
||||
1054830, // Proton 4.2
|
||||
1070560, // Steam Linux Runtime 1.0
|
||||
1113280, // Proton 4.11
|
||||
1245040, // Proton 5.0
|
||||
1391110, // Steam Linux Runtime 2.0
|
||||
1420170, // Proton 5.13
|
||||
1493710, // Proton Experimental
|
||||
1580130, // Proton 6.3
|
||||
1628350, // Steam Linux Runtime 3.0
|
||||
1887720, // Proton 7
|
||||
2180100, // Proton Hotfix
|
||||
228980, // Steamworks Common Redistributables
|
||||
2348590, // Proton 8
|
||||
2805730, // Proton 9
|
||||
3029110, // Lepton
|
||||
3127680, // FEX
|
||||
3658110, // Proton 10
|
||||
4183110, // Steam Linux Runtime 4.0
|
||||
4185400, // Steam Linux Runtime 4.0 for ARM64
|
||||
4427310, // Proton Experimental for ARM64
|
||||
4628710, // Proton 11 / Proton Next
|
||||
4628740, // Proton 11 for ARM64
|
||||
4690330, // Legacy Steam Runtime
|
||||
)
|
||||
private val STEAM_CAPSULES = listOf("library_capsule.jpg", "library_600x900.jpg")
|
||||
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
|
||||
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
|
||||
|
||||
@@ -49,16 +77,25 @@ object Library {
|
||||
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
||||
// StateFlags 4 = fully installed; anything else is downloading, updating or broken.
|
||||
if (name.isEmpty() || flags and 4 == 0) return@forEach
|
||||
val dir = File(cache, appId.toString())
|
||||
val art = listOf("library_600x900.jpg", "logo.png", "library_header.jpg", "header.jpg")
|
||||
.map { File(dir, it) }.firstOrNull { it.isFile }
|
||||
val art = steamCapsule(cache, appId)
|
||||
out[appId] = SteamGame(appId, name, art, label)
|
||||
}
|
||||
}
|
||||
return out.values.toList()
|
||||
}
|
||||
|
||||
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>)
|
||||
/** Steam stores current library capsules inside hash-named folders under the app's cache dir. */
|
||||
private fun steamCapsule(cache: File, appId: Int): File? {
|
||||
val appDir = File(cache, appId.toString())
|
||||
val dirs = listOf(appDir) + appDir.listFiles()
|
||||
.orEmpty().filter { it.isDirectory }.sortedBy { it.name }
|
||||
return STEAM_CAPSULES.asSequence()
|
||||
.flatMap { name -> dirs.asSequence().map { File(it, name) } }
|
||||
.firstOrNull { it.isFile && it.length() > 0L }
|
||||
}
|
||||
|
||||
/** [atPanel]: frames cheap enough to draw at the panel's own size (see [drawsAtPanel]). */
|
||||
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>, val atPanel: Boolean = false)
|
||||
private val specs = listOf(
|
||||
Spec("rpcs3", "RPCS3", "PS3", "/opt/appimages/rpcs3.AppImage", listOf("ps3"), setOf("iso")),
|
||||
// PS2: ARMSX2, the PCSX2 fork with ARM64 recompilers. Upstream PCSX2 interprets the PS2's
|
||||
@@ -66,7 +103,7 @@ object Library {
|
||||
Spec("armsx2", "ARMSX2", "PS2", "/opt/appimages/armsx2.AppImage", listOf("ps2"), setOf("iso", "chd", "cso", "gz")),
|
||||
Spec("dolphin", "Dolphin", "GameCube / Wii", "/opt/appimages/dolphin.AppImage", listOf("gc", "gamecube", "wii"), setOf("iso", "rvz", "gcz", "wbfs", "ciso")),
|
||||
Spec("duckstation", "DuckStation", "PS1", "/opt/appimages/duckstation.AppImage", listOf("ps1", "psx"), setOf("cue", "chd", "pbp", "iso", "bin", "img", "ecm", "m3u")),
|
||||
Spec("melonds", "melonDS", "DS", "/opt/appimages/melonds.AppImage", listOf("ds", "nds"), setOf("nds", "dsi")),
|
||||
Spec("melonds", "melonDS", "DS", "/opt/appimages/melonds.AppImage", listOf("ds", "nds"), setOf("nds", "dsi"), atPanel = true),
|
||||
Spec("cemu", "Cemu", "Wii U", "/opt/appimages/cemu.AppImage", listOf("wiiu", "wii u"), setOf("wua", "wud", "wux", "rpx")),
|
||||
Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
|
||||
Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()),
|
||||
@@ -89,6 +126,14 @@ object Library {
|
||||
/** The emulator's name for a program path from the rail ("ARMSX2"), or null. */
|
||||
fun nameForProgram(program: String?): String? = specs.firstOrNull { it.program == program }?.name
|
||||
|
||||
/**
|
||||
* Whether a program from the rail runs at the panel's own resolution rather than the session's
|
||||
* 720p default. melonDS draws two 256x192 screens on the CPU: the panel's size costs it
|
||||
* nothing, and 720p scaled up to the panel blurs the sharp pixels its screen layout is set
|
||||
* up for (bannerlator-pad-defaults).
|
||||
*/
|
||||
fun drawsAtPanel(program: String?): Boolean = specs.any { it.program == program && it.atPanel }
|
||||
|
||||
/** Desktop catalog package that supplies this emulator. */
|
||||
fun packageId(emulatorId: String): String? = installedIds[emulatorId]
|
||||
|
||||
@@ -234,6 +279,9 @@ object Library {
|
||||
"-e", guestPath,
|
||||
)
|
||||
"cemu" -> listOf("-g", guestPath)
|
||||
// Full screen (CLI.cpp --fullscreen); the guide button leaves it for melonDS's menus and
|
||||
// comes back (HK_FullscreenToggle, bannerlator-pad-defaults).
|
||||
"melonds" -> listOf("-f", guestPath)
|
||||
else -> listOf(guestPath)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import android.widget.FrameLayout
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.LocalPalette
|
||||
|
||||
class ControllerEditorActivity : ComponentActivity() {
|
||||
private lateinit var controls: OnScreenControls
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
immersive()
|
||||
val root = FrameLayout(this)
|
||||
root.setBackgroundColor(0xFF0B0F14.toInt())
|
||||
controls = OnScreenControls(this, null, editing = true)
|
||||
root.addView(controls, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
|
||||
val bar = ComposeView(this).apply {
|
||||
setContent {
|
||||
DroidDeckTheme {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier
|
||||
.background(MaterialTheme.colorScheme.surface.copy(alpha = 0.9f), RoundedCornerShape(50))
|
||||
.padding(start = 14.dp, end = 5.dp, top = 5.dp, bottom = 5.dp),
|
||||
) {
|
||||
Text("Drag to move", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(end = 4.dp))
|
||||
EditorButton("Reset", false) { controls.resetLayout() }
|
||||
EditorButton("Cancel", false) { finish() }
|
||||
EditorButton("Save", true) {
|
||||
controls.saveLayout()
|
||||
finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
root.addView(bar, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER))
|
||||
setContentView(root)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EditorButton(label: String, primary: Boolean, onClick: () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
Text(
|
||||
label, fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = if (primary) Color.White else MaterialTheme.colorScheme.onBackground,
|
||||
modifier = Modifier.clip(RoundedCornerShape(50))
|
||||
.background(if (primary) pal.signal else Color.White.copy(alpha = 0.06f))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) immersive()
|
||||
}
|
||||
|
||||
private fun immersive() {
|
||||
@Suppress("DEPRECATION")
|
||||
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
|
||||
or View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
|
||||
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
|
||||
if (Build.VERSION.SDK_INT >= 28) {
|
||||
window.attributes = window.attributes.apply {
|
||||
layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
|
||||
object ControllerPrefs {
|
||||
const val STEAM_BLUE = 0xFF1A9FFF.toInt()
|
||||
const val OFF = "off"
|
||||
|
||||
val tints = listOf(
|
||||
STEAM_BLUE to "Steam blue",
|
||||
0xFF66C0F4.toInt() to "Sky",
|
||||
0xFFE8EEF4.toInt() to "White",
|
||||
0xFFC77DFF.toInt() to "Violet",
|
||||
0xFF3DDC84.toInt() to "Green",
|
||||
0xFFFFA726.toInt() to "Amber",
|
||||
0xFFFF5252.toInt() to "Red",
|
||||
0xFFFF6FB5.toInt() to "Pink",
|
||||
)
|
||||
|
||||
val opacities = listOf(40, 60, 80, 100)
|
||||
|
||||
val sizes = listOf(80, 90, 100, 110, 125)
|
||||
|
||||
val mappable = listOf(
|
||||
"a" to "A button", "b" to "B button", "x" to "X button", "y" to "Y button",
|
||||
"lb" to "Left bumper", "rb" to "Right bumper", "lt" to "Left trigger", "rt" to "Right trigger",
|
||||
"select" to "View button", "start" to "Menu button",
|
||||
)
|
||||
|
||||
val targets = listOf(
|
||||
"a" to "A", "b" to "B", "x" to "X", "y" to "Y",
|
||||
"lb" to "LB", "rb" to "RB", "lt" to "LT", "rt" to "RT",
|
||||
"l3" to "L3", "r3" to "R3", "select" to "View", "start" to "Menu", "guide" to "Steam",
|
||||
"up" to "D-pad up", "down" to "D-pad down", "left" to "D-pad left", "right" to "D-pad right",
|
||||
OFF to "Hidden",
|
||||
)
|
||||
|
||||
class Settings(
|
||||
val tint: Int,
|
||||
val opacity: Int,
|
||||
val size: Int,
|
||||
val stickClick: Boolean,
|
||||
val adaptiveSticks: Boolean,
|
||||
val customLayout: Boolean,
|
||||
val mapping: Map<String, String>,
|
||||
)
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("controller", Context.MODE_PRIVATE)
|
||||
|
||||
fun read(context: Context): Settings {
|
||||
val p = prefs(context)
|
||||
return Settings(
|
||||
tint = p.getInt("tint", STEAM_BLUE),
|
||||
opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100,
|
||||
size = p.getInt("size", 100).takeIf { it in sizes } ?: 100,
|
||||
stickClick = p.getBoolean("stickClick", true),
|
||||
adaptiveSticks = p.getBoolean("adaptiveSticks", true),
|
||||
customLayout = p.all.keys.any { it.startsWith("layout.") },
|
||||
mapping = mappable.associate { (id, _) -> id to target(context, id) },
|
||||
)
|
||||
}
|
||||
|
||||
fun target(context: Context, id: String): String =
|
||||
prefs(context).getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id
|
||||
|
||||
fun setTarget(context: Context, id: String, target: String) {
|
||||
prefs(context).edit().putString("map.$id", target).apply()
|
||||
}
|
||||
|
||||
fun resetMapping(context: Context) {
|
||||
val p = prefs(context)
|
||||
p.edit().apply { p.all.keys.filter { it.startsWith("map.") }.forEach { remove(it) } }.apply()
|
||||
}
|
||||
|
||||
fun setTint(context: Context, tint: Int) {
|
||||
prefs(context).edit().putInt("tint", tint).apply()
|
||||
}
|
||||
|
||||
fun setOpacity(context: Context, percent: Int) {
|
||||
prefs(context).edit().putInt("opacity", percent).apply()
|
||||
}
|
||||
|
||||
fun setSize(context: Context, percent: Int) {
|
||||
prefs(context).edit().putInt("size", percent).apply()
|
||||
}
|
||||
|
||||
fun setStickClick(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("stickClick", on).apply()
|
||||
}
|
||||
|
||||
fun setAdaptiveSticks(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("adaptiveSticks", on).apply()
|
||||
}
|
||||
|
||||
fun layout(context: Context, width: Int, height: Int): Map<String, Pair<Float, Float>> {
|
||||
val raw = prefs(context).getString("layout.${width}x$height", null) ?: return emptyMap()
|
||||
return raw.split(';').mapNotNull { entry ->
|
||||
val (group, pos) = entry.split(':').takeIf { it.size == 2 } ?: return@mapNotNull null
|
||||
val (x, y) = pos.split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 2 } ?: return@mapNotNull null
|
||||
group to (x to y)
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
fun setLayout(context: Context, width: Int, height: Int, positions: Map<String, Pair<Float, Float>>) {
|
||||
val raw = positions.entries.joinToString(";") { (group, pos) -> "$group:${pos.first},${pos.second}" }
|
||||
prefs(context).edit().putString("layout.${width}x$height", raw).apply()
|
||||
}
|
||||
|
||||
fun resetLayout(context: Context, width: Int, height: Int) {
|
||||
prefs(context).edit().remove("layout.${width}x$height").apply()
|
||||
}
|
||||
|
||||
fun resetAll(context: Context) {
|
||||
prefs(context).edit().clear().apply()
|
||||
}
|
||||
|
||||
fun resetAllLayouts(context: Context) {
|
||||
val p = prefs(context)
|
||||
p.edit().apply { p.all.keys.filter { it.startsWith("layout.") }.forEach { remove(it) } }.apply()
|
||||
}
|
||||
}
|
||||
@@ -5,251 +5,437 @@ import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import android.os.Build
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.WindowInsets
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* A pad drawn on the screen for devices that have no controller attached.
|
||||
*
|
||||
* It writes into the same [PadBridge] a physical pad does, so the Steam client sees one Xbox pad
|
||||
* whichever is being used, and the two can be used at once. A d-pad, two sticks, the four face
|
||||
* buttons, the bumpers, and the three centre buttons: enough to drive Big Picture and to play,
|
||||
* and no control editor.
|
||||
*
|
||||
* Where the controls go follows the picture. The compositor letterboxes the session's output onto
|
||||
* the panel, and a foldable or a wide phone has bars beside or above and below it that are empty
|
||||
* black: the controls take the bars first, and only overlay the picture when there are none wide
|
||||
* enough. Only the controls themselves take touches; everything else falls through to the
|
||||
* activity, where it moves the mouse pointer.
|
||||
*/
|
||||
@SuppressLint("ViewConstructor")
|
||||
class OnScreenControls(context: Context, private val pad: PadBridge) : View(context) {
|
||||
class OnScreenControls(context: Context, private val pad: PadBridge?, private val editing: Boolean = false) : View(context) {
|
||||
|
||||
private class Control(
|
||||
val id: String,
|
||||
val label: String,
|
||||
/** A PadState button number, or -1. */
|
||||
val button: Int,
|
||||
/** A d-pad direction (0 up, 1 right, 2 down, 3 left), or -1. */
|
||||
val dpad: Int,
|
||||
/** 0 = left stick, 1 = right stick, -1 = a button. */
|
||||
val group: String,
|
||||
val stick: Int,
|
||||
val radius: Float,
|
||||
val radiusDp: Float,
|
||||
val offsetXDp: Float,
|
||||
val offsetYDp: Float,
|
||||
) {
|
||||
var target = id
|
||||
var radius = 0f
|
||||
var cx = 0f
|
||||
var cy = 0f
|
||||
var pressedBy = -1 // the pointer id holding it, or -1
|
||||
/** A stick's knob offset from its centre, in [-radius, radius]. */
|
||||
var pressedBy = -1
|
||||
var kx = 0f
|
||||
var ky = 0f
|
||||
/** A stick that moved or was let go: its axes are written once, then left alone. */
|
||||
var ax = 0f
|
||||
var ay = 0f
|
||||
var dirty = false
|
||||
fun contains(x: Float, y: Float, radius: Float = this.radius): Boolean {
|
||||
var clicked = false
|
||||
var lastUp = 0L
|
||||
val wide = id in shoulderIds
|
||||
val halfW get() = if (wide) radius * SHOULDER_WIDTH else radius
|
||||
val halfH get() = if (wide) radius * SHOULDER_HEIGHT else radius
|
||||
|
||||
fun contains(x: Float, y: Float, r: Float): Boolean {
|
||||
val dx = x - cx
|
||||
val dy = y - cy
|
||||
// A generous hit area: a finger on glass is not a mouse, and a miss in Big Picture
|
||||
// means the user thinks the pad does not work.
|
||||
val r = radius * 1.25f
|
||||
return dx * dx + dy * dy <= r * r
|
||||
if (wide) return abs(dx) <= halfW + r * 0.25f && abs(dy) <= halfH + r * 0.25f
|
||||
val hit = r * 1.25f
|
||||
return dx * dx + dy * dy <= hit * hit
|
||||
}
|
||||
/** Moves the knob towards the finger, clamped to the base. */
|
||||
|
||||
fun drag(x: Float, y: Float) {
|
||||
var dx = x - cx
|
||||
var dy = y - cy
|
||||
var dx = x - ax
|
||||
var dy = y - ay
|
||||
val d = sqrt(dx * dx + dy * dy)
|
||||
if (d > radius) { dx = dx / d * radius; dy = dy / d * radius }
|
||||
kx = dx; ky = dy; dirty = true
|
||||
}
|
||||
}
|
||||
|
||||
private val density = resources.displayMetrics.density
|
||||
private fun dp(value: Float) = value * density
|
||||
|
||||
private val controls = listOf(
|
||||
Control("up", "▲", -1, 0, -1, dp(26f)),
|
||||
Control("right", ">", -1, 1, -1, dp(26f)),
|
||||
Control("down", "▼", -1, 2, -1, dp(26f)),
|
||||
Control("left", "<", -1, 3, -1, dp(26f)),
|
||||
Control("ls", "L", -1, -1, 0, dp(48f)),
|
||||
Control("rs", "R", -1, -1, 1, dp(48f)),
|
||||
Control("a", "A", 0, -1, -1, dp(30f)),
|
||||
Control("b", "B", 1, -1, -1, dp(30f)),
|
||||
Control("x", "X", 2, -1, -1, dp(30f)),
|
||||
Control("y", "Y", 3, -1, -1, dp(30f)),
|
||||
Control("lb", "LB", 4, -1, -1, dp(24f)),
|
||||
Control("rb", "RB", 5, -1, -1, dp(24f)),
|
||||
Control("select", "⧉", 6, -1, -1, dp(20f)),
|
||||
Control("start", "☰", 7, -1, -1, dp(20f)),
|
||||
// The client's own in-game menu; the interposer publishes it as BTN_MODE.
|
||||
Control("guide", "◉", PadState.GUIDE, -1, -1, dp(22f)),
|
||||
Control("qam", "⋯", -1, -1, -1, dp(22f)),
|
||||
Control("up", "dpad", -1, 26f, 0f, -52f),
|
||||
Control("right", "dpad", -1, 26f, 52f, 0f),
|
||||
Control("down", "dpad", -1, 26f, 0f, 52f),
|
||||
Control("left", "dpad", -1, 26f, -52f, 0f),
|
||||
Control("ls", "ls", 0, 48f, 0f, 0f),
|
||||
Control("rs", "rs", 1, 48f, 0f, 0f),
|
||||
Control("a", "face", -1, 30f, 0f, 50f),
|
||||
Control("b", "face", -1, 30f, 50f, 0f),
|
||||
Control("x", "face", -1, 30f, -50f, 0f),
|
||||
Control("y", "face", -1, 30f, 0f, -50f),
|
||||
Control("lb", "lb", -1, 24f, 0f, 0f),
|
||||
Control("rb", "rb", -1, 24f, 0f, 0f),
|
||||
Control("lt", "lt", -1, 24f, 0f, 0f),
|
||||
Control("rt", "rt", -1, 24f, 0f, 0f),
|
||||
Control("select", "select", -1, 20f, 0f, 0f),
|
||||
Control("start", "start", -1, 20f, 0f, 0f),
|
||||
Control("guide", "guide", -1, 22f, 0f, 0f),
|
||||
Control("qam", "qam", -1, 22f, 0f, 0f),
|
||||
)
|
||||
|
||||
private val groups = controls.map { it.group }.distinct()
|
||||
|
||||
private var buttonsOnly = false
|
||||
private var settings = ControllerPrefs.read(context)
|
||||
private var safe = Rect()
|
||||
private var selected: String? = null
|
||||
private var grabX = 0f
|
||||
private var grabY = 0f
|
||||
private var ignoreSaved = false
|
||||
private var fit = 1f
|
||||
|
||||
private var idleFill = 0
|
||||
private var heldFill = 0
|
||||
private var idleStroke = 0
|
||||
private var heldStroke = 0
|
||||
private var idleText = 0
|
||||
private var stickFill = 0
|
||||
private var knobFill = 0
|
||||
|
||||
private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
|
||||
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = dp(1.5f)
|
||||
}
|
||||
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
||||
private val arrow = Path()
|
||||
private val box = RectF()
|
||||
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textAlign = Paint.Align.CENTER
|
||||
typeface = android.graphics.Typeface.DEFAULT_BOLD
|
||||
}
|
||||
|
||||
/** Where the session's picture is drawn on this view, or null when the whole view is picture. */
|
||||
private var picture: RectF? = null
|
||||
init {
|
||||
applySettings()
|
||||
}
|
||||
|
||||
/** The activity tells the controls where the picture lands; the layout follows it. */
|
||||
fun setPicture(rect: RectF?) {
|
||||
val same = (rect == null && picture == null) || (rect != null && picture != null && rect == picture)
|
||||
if (same) return
|
||||
picture = rect?.let { RectF(it) }
|
||||
if (width > 0 && height > 0) { layoutControls(width.toFloat(), height.toFloat()); invalidate() }
|
||||
private fun dp(value: Float) = value * resources.displayMetrics.density
|
||||
|
||||
private fun scaled(value: Float) = dp(value) * settings.size / 100f * fit
|
||||
|
||||
private fun fitScale(): Float {
|
||||
val metrics = resources.displayMetrics
|
||||
val heightMm = (height - safe.top - safe.bottom) / pxPerMm(metrics.ydpi)
|
||||
val faceMm = dp(60f) / pxPerMm(metrics.xdpi)
|
||||
val floor = (MIN_FACE_MM / faceMm).coerceAtMost(1f)
|
||||
return (heightMm / FULL_SIZE_HEIGHT_MM).coerceIn(floor, 1f)
|
||||
}
|
||||
|
||||
fun reload() {
|
||||
releaseAll()
|
||||
settings = ControllerPrefs.read(context)
|
||||
applySettings()
|
||||
relayout()
|
||||
}
|
||||
|
||||
private fun applySettings() {
|
||||
for (control in controls) control.target = settings.mapping[control.id] ?: control.id
|
||||
val tint = settings.tint
|
||||
val alpha = settings.opacity / 100f
|
||||
fun shade(a: Int, f: Float) = Color.argb((a * alpha).toInt(), (Color.red(tint) * f).toInt(), (Color.green(tint) * f).toInt(), (Color.blue(tint) * f).toInt())
|
||||
fun light(a: Int, f: Float) = Color.argb(
|
||||
(a * alpha).toInt(),
|
||||
(Color.red(tint) + (255 - Color.red(tint)) * f).toInt(),
|
||||
(Color.green(tint) + (255 - Color.green(tint)) * f).toInt(),
|
||||
(Color.blue(tint) + (255 - Color.blue(tint)) * f).toInt(),
|
||||
)
|
||||
idleFill = shade(80, 0.12f)
|
||||
heldFill = shade(160, 1f)
|
||||
idleStroke = light(150, 0.25f)
|
||||
heldStroke = light(230, 0.7f)
|
||||
idleText = light(210, 0.75f)
|
||||
stickFill = shade(60, 0.12f)
|
||||
knobFill = shade(120, 0.35f)
|
||||
stroke.strokeWidth = dp(1.5f)
|
||||
}
|
||||
|
||||
fun setButtonsOnly(enabled: Boolean) {
|
||||
if (buttonsOnly == enabled) return
|
||||
releaseAll()
|
||||
buttonsOnly = enabled
|
||||
if (width > 0 && height > 0) layoutControls(width.toFloat(), height.toFloat())
|
||||
invalidate()
|
||||
relayout()
|
||||
}
|
||||
|
||||
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
|
||||
super.onSizeChanged(w, h, oldw, oldh)
|
||||
layoutControls(w.toFloat(), h.toFloat())
|
||||
relayout()
|
||||
}
|
||||
|
||||
/**
|
||||
* Three layouts: side bars (a wide panel showing 16:9), bottom band (a squarer panel showing
|
||||
* a wide picture), and the overlay when neither bar is wide enough for a cluster. Thumbs reach
|
||||
* the bottom corners in every one; nothing is placed where a game's own HUD usually is.
|
||||
*/
|
||||
private fun layoutControls(w: Float, h: Float) {
|
||||
if (buttonsOnly) {
|
||||
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
|
||||
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
|
||||
val fresh = Rect(cutout?.safeInsetLeft ?: 0, cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
|
||||
if (fresh != safe) { safe = fresh; relayout() }
|
||||
return super.onApplyWindowInsets(insets)
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
releaseAll()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
private fun relayout() {
|
||||
if (width <= 0 || height <= 0) return
|
||||
fit = if (buttonsOnly && !editing) 1f else fitScale()
|
||||
for (control in controls) control.radius = if (buttonsOnly && !editing && (control.id == "guide" || control.id == "qam")) dp(30f) else scaled(control.radiusDp)
|
||||
if (buttonsOnly && !editing) {
|
||||
val inset = dp(44f)
|
||||
place("guide", inset, h - inset)
|
||||
place("qam", w - inset, h - inset)
|
||||
return
|
||||
put("guide", safe.left + inset, height - safe.bottom - inset)
|
||||
put("qam", width - safe.right - inset, height - safe.bottom - inset)
|
||||
} else {
|
||||
placeAuto(width.toFloat(), height.toFloat())
|
||||
if (!ignoreSaved) for ((group, pos) in ControllerPrefs.layout(context, width, height)) {
|
||||
if (group in groups) put(group, pos.first * width, pos.second * height)
|
||||
}
|
||||
}
|
||||
val p = picture
|
||||
val sideBar = if (p != null) minOf(p.left, w - p.right) else 0f
|
||||
val bottomBand = if (p != null) h - p.bottom else 0f
|
||||
val margin = dp(34f)
|
||||
when {
|
||||
// A cluster (d-pad or face buttons) is ~156 dp across; a stick above it needs the height.
|
||||
sideBar >= dp(160f) && p != null -> {
|
||||
val lx = p.left / 2f
|
||||
val rx = p.right + (w - p.right) / 2f
|
||||
val bottom = h - margin - dp(74f)
|
||||
dpadAt(lx, bottom)
|
||||
faceAt(rx, bottom)
|
||||
place("ls", lx, bottom - dp(196f))
|
||||
place("rs", rx, bottom - dp(196f))
|
||||
place("lb", lx, bottom - dp(196f) - dp(96f))
|
||||
place("rb", rx, bottom - dp(196f) - dp(96f))
|
||||
place("select", lx, h - margin + dp(8f))
|
||||
place("start", rx, h - margin + dp(8f))
|
||||
place("guide", w / 2f, h - dp(22f))
|
||||
}
|
||||
bottomBand >= dp(190f) && p != null -> {
|
||||
val cy = p.bottom + bottomBand / 2f + dp(12f)
|
||||
val dx = margin + dp(74f)
|
||||
val fx = w - margin - dp(74f)
|
||||
dpadAt(dx, cy)
|
||||
faceAt(fx, cy)
|
||||
place("ls", dx + dp(150f), cy)
|
||||
place("rs", fx - dp(150f), cy)
|
||||
place("lb", dx, p.bottom + dp(30f))
|
||||
place("rb", fx, p.bottom + dp(30f))
|
||||
val centre = w / 2f
|
||||
place("select", centre - dp(60f), h - dp(30f))
|
||||
place("guide", centre, h - dp(30f))
|
||||
place("start", centre + dp(60f), h - dp(30f))
|
||||
}
|
||||
else -> {
|
||||
val dx = margin + dp(74f)
|
||||
val fx = w - margin - dp(74f)
|
||||
val bottom = h - margin - dp(74f)
|
||||
dpadAt(dx, bottom)
|
||||
faceAt(fx, bottom)
|
||||
place("ls", dx + dp(142f), bottom)
|
||||
place("rs", fx - dp(142f), bottom)
|
||||
place("lb", margin + dp(46f), h - margin - dp(196f))
|
||||
place("rb", w - margin - dp(46f), h - margin - dp(196f))
|
||||
val centre = w / 2f
|
||||
place("select", centre - dp(60f), h - margin - dp(26f))
|
||||
place("guide", centre, h - margin - dp(26f))
|
||||
place("start", centre + dp(60f), h - margin - dp(26f))
|
||||
groups.forEach { clamp(it) }
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun pxPerMm(dpi: Float): Float {
|
||||
val nominal = resources.displayMetrics.densityDpi.toFloat()
|
||||
return (if (dpi > nominal * 0.6f && dpi < nominal * 1.6f) dpi else nominal) / 25.4f
|
||||
}
|
||||
|
||||
private fun placeAuto(w: Float, h: Float) {
|
||||
val metrics = resources.displayMetrics
|
||||
val mmX = pxPerMm(metrics.xdpi)
|
||||
val mmY = pxPerMm(metrics.ydpi)
|
||||
val usableW = w - safe.left - safe.right
|
||||
val usableH = h - safe.top - safe.bottom
|
||||
val inboard = (0.17f * usableW / mmX).coerceIn(24f, 40f) * mmX
|
||||
val lift = (0.285f * usableH / mmY).coerceIn(22f, 45f) * mmY
|
||||
val gap = dp(12f)
|
||||
val floor = BOTTOM_MARGIN_MM * mmY
|
||||
val drop = max(drop("dpad", "ls", gap), drop("rs", "face", gap))
|
||||
val restY = min(h - safe.bottom - lift, h - safe.bottom - floor - drop)
|
||||
put("ls", safe.left + inboard, restY)
|
||||
put("face", w - safe.right - inboard, restY)
|
||||
besideBelow("dpad", "ls", 1f, gap, floor)
|
||||
besideBelow("rs", "face", -1f, gap, floor)
|
||||
val phone = usableH / mmY < PHONE_MAX_HEIGHT_MM
|
||||
val shoulderY = if (phone) safe.top + floor + halfH("lb")
|
||||
else min(centre("ls").second - extent("ls"), centre("face").second - extent("face")) - gap - halfH("lb")
|
||||
shoulders("ls", "lb", "lt", 1f, gap, shoulderY)
|
||||
shoulders("face", "rb", "rt", -1f, gap, shoulderY)
|
||||
val bottom = h - safe.bottom - floor - extent("guide")
|
||||
val spread = extent("guide") + gap / 2f
|
||||
put("guide", w / 2f - spread, bottom)
|
||||
put("qam", w / 2f + spread, bottom)
|
||||
val inner = max(centre("dpad").first + extent("dpad"), w - centre("rs").first + extent("rs")) + gap + extent("select")
|
||||
put("select", inner, restY)
|
||||
put("start", w - inner, restY)
|
||||
if (phone) {
|
||||
val top = max(centre("lb").first + extent("lb"), w - centre("rb").first + extent("rb")) + gap * 2.5f + extent("select")
|
||||
put("select", top, shoulderY)
|
||||
put("start", w - top, shoulderY)
|
||||
}
|
||||
if (crowded("select", gap) || crowded("start", gap)) {
|
||||
above("select", "dpad", gap)
|
||||
val (sx, sy) = centre("select")
|
||||
put("start", w - sx, sy)
|
||||
if (crowded("start", gap)) above("start", "rs", gap)
|
||||
}
|
||||
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
|
||||
val row = centre("select").second
|
||||
put("guide", w / 2f - spread, row)
|
||||
put("qam", w / 2f + spread, row)
|
||||
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
|
||||
val top = safe.top + dp(8f) + extent("guide")
|
||||
put("guide", w / 2f - spread, top)
|
||||
put("qam", w / 2f + spread, top)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun dpadAt(x: Float, y: Float) {
|
||||
val step = dp(52f)
|
||||
place("up", x, y - step)
|
||||
place("down", x, y + step)
|
||||
place("left", x - step, y)
|
||||
place("right", x + step, y)
|
||||
private fun drop(group: String, anchor: String, gap: Float): Float =
|
||||
(extent(anchor) + extent(group) + gap) * sin(Math.toRadians(DROP_DEGREES)).toFloat() + extent(group)
|
||||
|
||||
private fun besideBelow(group: String, anchor: String, inward: Float, gap: Float, margin: Float) {
|
||||
val (ax, ay) = centre(anchor)
|
||||
val reach = extent(anchor) + extent(group) + gap
|
||||
val floor = height - safe.bottom - margin - extent(group)
|
||||
val dy = min(reach * sin(Math.toRadians(DROP_DEGREES)).toFloat(), floor - ay)
|
||||
val dx = sqrt(max(0f, reach * reach - dy * dy))
|
||||
put(group, ax + inward * dx, ay + dy)
|
||||
}
|
||||
|
||||
private fun faceAt(x: Float, y: Float) {
|
||||
val step = dp(50f)
|
||||
place("a", x, y + step)
|
||||
place("b", x + step, y)
|
||||
place("x", x - step, y)
|
||||
place("y", x, y - step)
|
||||
private fun shoulders(anchor: String, bumper: String, trigger: String, inward: Float, gap: Float, y: Float) {
|
||||
val (ax, _) = centre(anchor)
|
||||
val spread = extent(bumper) + gap / 2f
|
||||
put(bumper, ax + inward * spread, y)
|
||||
put(trigger, ax - inward * spread, y)
|
||||
}
|
||||
|
||||
private fun place(id: String, x: Float, y: Float) {
|
||||
val control = controls.firstOrNull { it.id == id } ?: return
|
||||
control.cx = x
|
||||
control.cy = y
|
||||
private fun above(group: String, anchor: String, gap: Float) {
|
||||
val (ax, ay) = centre(anchor)
|
||||
put(group, ax, ay - extent(anchor) - gap - extent(group))
|
||||
}
|
||||
|
||||
private fun crowded(group: String, gap: Float, space: Float = gap / 2f, except: String? = null): Boolean {
|
||||
val (x, y) = centre(group)
|
||||
return groups.any { other ->
|
||||
if (other == group || other == except) return@any false
|
||||
val (ox, oy) = centre(other)
|
||||
val dx = x - ox
|
||||
val dy = y - oy
|
||||
sqrt(dx * dx + dy * dy) < extent(group) + extent(other) + space
|
||||
}
|
||||
}
|
||||
|
||||
private fun members(group: String) = controls.filter { it.group == group }
|
||||
|
||||
private fun centre(group: String): Pair<Float, Float> {
|
||||
val first = members(group).first()
|
||||
return (first.cx - scaled(first.offsetXDp)) to (first.cy - scaled(first.offsetYDp))
|
||||
}
|
||||
|
||||
private fun extent(group: String): Float = members(group).maxOf { control ->
|
||||
sqrt(scaled(control.offsetXDp).let { it * it } + scaled(control.offsetYDp).let { it * it }) + control.halfW
|
||||
}
|
||||
|
||||
private fun halfH(group: String): Float = members(group).maxOf { abs(scaled(it.offsetYDp)) + it.halfH }
|
||||
|
||||
private fun put(group: String, x: Float, y: Float) {
|
||||
for (control in members(group)) {
|
||||
control.cx = x + scaled(control.offsetXDp)
|
||||
control.cy = y + scaled(control.offsetYDp)
|
||||
}
|
||||
}
|
||||
|
||||
private fun clamp(group: String) {
|
||||
val list = members(group)
|
||||
val margin = dp(4f)
|
||||
val minX = list.minOf { it.cx - it.halfW } - safe.left - margin
|
||||
val maxX = list.maxOf { it.cx + it.halfW } - (width - safe.right - margin)
|
||||
val minY = list.minOf { it.cy - it.halfH } - safe.top - margin
|
||||
val maxY = list.maxOf { it.cy + it.halfH } - (height - safe.bottom - margin)
|
||||
val dx = if (minX < 0) -minX else if (maxX > 0) -maxX else 0f
|
||||
val dy = if (minY < 0) -minY else if (maxY > 0) -maxY else 0f
|
||||
if (dx == 0f && dy == 0f) return
|
||||
for (control in list) { control.cx += dx; control.cy += dy }
|
||||
}
|
||||
|
||||
fun saveLayout() {
|
||||
if (width <= 0 || height <= 0) return
|
||||
if (ignoreSaved) { ControllerPrefs.resetLayout(context, width, height); return }
|
||||
ControllerPrefs.setLayout(context, width, height, groups.associateWith { group ->
|
||||
val (x, y) = centre(group)
|
||||
x / width to y / height
|
||||
})
|
||||
}
|
||||
|
||||
fun resetLayout() {
|
||||
ControllerPrefs.resetLayout(context, width, height)
|
||||
ignoreSaved = true
|
||||
selected = null
|
||||
relayout()
|
||||
}
|
||||
|
||||
private fun label(control: Control): String = when (control.target) {
|
||||
"ls" -> "L"
|
||||
"rs" -> "R"
|
||||
"select" -> "⧉"
|
||||
"start" -> "☰"
|
||||
"guide" -> if (buttonsOnly && !editing) "Steam" else "◉"
|
||||
"qam" -> "⋯"
|
||||
else -> control.target.uppercase()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
for (control in controls) {
|
||||
if (!isVisible(control)) continue
|
||||
val held = control.pressedBy != -1
|
||||
val radius = controlRadius(control)
|
||||
val radius = control.radius
|
||||
if (control.stick >= 0) {
|
||||
// The base, then the knob where the finger holds it.
|
||||
fill.color = if (held) Color.argb(60, 199, 125, 255) else Color.argb(50, 20, 12, 30)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, fill)
|
||||
stroke.color = if (held) Color.argb(200, 235, 212, 255) else Color.argb(90, 201, 160, 255)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, stroke)
|
||||
val bx = if (held) control.ax else control.cx
|
||||
val by = if (held) control.ay else control.cy
|
||||
fill.color = if (held) heldFill else stickFill
|
||||
canvas.drawCircle(bx, by, radius, fill)
|
||||
stroke.color = if (held) heldStroke else idleStroke
|
||||
canvas.drawCircle(bx, by, radius, stroke)
|
||||
val knob = radius * 0.46f
|
||||
fill.color = if (held) Color.argb(170, 199, 125, 255) else Color.argb(110, 60, 40, 90)
|
||||
canvas.drawCircle(control.cx + control.kx, control.cy + control.ky, knob, fill)
|
||||
stroke.color = if (held) Color.argb(230, 245, 230, 255) else Color.argb(140, 201, 160, 255)
|
||||
canvas.drawCircle(control.cx + control.kx, control.cy + control.ky, knob, stroke)
|
||||
text.color = if (held) Color.WHITE else Color.argb(150, 225, 210, 245)
|
||||
fill.color = if (held || control.clicked) heldFill else knobFill
|
||||
canvas.drawCircle(bx + control.kx, by + control.ky, knob, fill)
|
||||
stroke.color = if (held) heldStroke else idleStroke
|
||||
canvas.drawCircle(bx + control.kx, by + control.ky, knob, stroke)
|
||||
text.color = if (held) Color.WHITE else idleText
|
||||
text.textSize = knob * 0.8f
|
||||
canvas.drawText(control.label, control.cx + control.kx, control.cy + control.ky + text.textSize * 0.35f, text)
|
||||
continue
|
||||
canvas.drawText(label(control), bx + control.kx, by + control.ky + text.textSize * 0.35f, text)
|
||||
} else if (control.wide) {
|
||||
box.set(control.cx - control.halfW, control.cy - control.halfH, control.cx + control.halfW, control.cy + control.halfH)
|
||||
val corner = control.halfH * 0.55f
|
||||
fill.color = if (held) heldFill else idleFill
|
||||
canvas.drawRoundRect(box, corner, corner, fill)
|
||||
stroke.color = if (held) heldStroke else idleStroke
|
||||
canvas.drawRoundRect(box, corner, corner, stroke)
|
||||
text.color = if (held) Color.WHITE else idleText
|
||||
text.textSize = control.halfH * 0.8f
|
||||
canvas.drawText(label(control), control.cx, control.cy + text.textSize * 0.35f, text)
|
||||
} else {
|
||||
fill.color = if (held) heldFill else idleFill
|
||||
canvas.drawCircle(control.cx, control.cy, radius, fill)
|
||||
stroke.color = if (held) heldStroke else idleStroke
|
||||
canvas.drawCircle(control.cx, control.cy, radius, stroke)
|
||||
text.color = if (held) Color.WHITE else idleText
|
||||
val direction = directions.indexOf(control.target)
|
||||
if (direction >= 0) {
|
||||
drawArrow(canvas, control.cx, control.cy, radius * 0.34f, direction)
|
||||
continue
|
||||
}
|
||||
val name = label(control)
|
||||
text.textSize = if (name.length > 2) dp(11f) else radius * if (name.length == 2) 0.62f else 0.85f
|
||||
canvas.drawText(name, control.cx, control.cy + text.textSize * 0.35f, text)
|
||||
}
|
||||
fill.color = if (held) Color.argb(150, 199, 125, 255) else Color.argb(70, 20, 12, 30)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, fill)
|
||||
stroke.color = if (held) Color.argb(220, 235, 212, 255) else Color.argb(110, 201, 160, 255)
|
||||
canvas.drawCircle(control.cx, control.cy, radius, stroke)
|
||||
text.color = if (held) Color.WHITE else Color.argb(190, 225, 210, 245)
|
||||
val label = if (buttonsOnly && control.id == "guide") "Steam" else control.label
|
||||
text.textSize = if (buttonsOnly && control.id == "guide") dp(11f) else radius * 0.85f
|
||||
canvas.drawText(label, control.cx, control.cy + text.textSize * 0.35f, text)
|
||||
}
|
||||
val group = selected ?: return
|
||||
val (x, y) = centre(group)
|
||||
stroke.color = heldStroke
|
||||
val single = members(group).singleOrNull()
|
||||
if (single?.wide == true) {
|
||||
val pad = dp(6f)
|
||||
box.set(x - single.halfW - pad, y - single.halfH - pad, x + single.halfW + pad, y + single.halfH + pad)
|
||||
canvas.drawRoundRect(box, single.halfH, single.halfH, stroke)
|
||||
} else canvas.drawCircle(x, y, extent(group) + dp(6f), stroke)
|
||||
}
|
||||
|
||||
private fun drawArrow(canvas: Canvas, x: Float, y: Float, size: Float, direction: Int) {
|
||||
val (fx, fy) = when (direction) {
|
||||
0 -> 0f to -1f
|
||||
1 -> 1f to 0f
|
||||
2 -> 0f to 1f
|
||||
else -> -1f to 0f
|
||||
}
|
||||
arrow.reset()
|
||||
arrow.moveTo(x + fx * size, y + fy * size)
|
||||
arrow.lineTo(x - fx * size * 0.7f - fy * size, y - fy * size * 0.7f + fx * size)
|
||||
arrow.lineTo(x - fx * size * 0.7f + fy * size, y - fy * size * 0.7f - fx * size)
|
||||
arrow.close()
|
||||
fill.color = text.color
|
||||
canvas.drawPath(arrow, fill)
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (editing) return onEditTouch(event)
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
val index = event.actionIndex
|
||||
val control = controlAt(event.getX(index), event.getY(index)) ?: return false
|
||||
control.pressedBy = event.getPointerId(index)
|
||||
if (control.stick >= 0) control.drag(event.getX(index), event.getY(index))
|
||||
if (control.stick >= 0) {
|
||||
control.clicked = settings.stickClick && event.eventTime - control.lastUp < DOUBLE_TAP_MS
|
||||
val adaptive = settings.adaptiveSticks
|
||||
control.ax = if (adaptive) event.getX(index) else control.cx
|
||||
control.ay = if (adaptive) event.getY(index) else control.cy
|
||||
control.drag(event.getX(index), event.getY(index))
|
||||
}
|
||||
requestUnbufferedDispatch(event)
|
||||
apply()
|
||||
return true
|
||||
}
|
||||
@@ -259,11 +445,8 @@ class OnScreenControls(context: Context, private val pad: PadBridge) : View(cont
|
||||
val pointer = event.getPointerId(index)
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
// A stick keeps its finger wherever it goes: the knob follows, clamped.
|
||||
val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
|
||||
if (stick != null) { stick.drag(x, y); changed = true; continue }
|
||||
// A finger that slides off a button releases it, and one that slides onto
|
||||
// another presses that - which is how a d-pad is used in practice.
|
||||
val over = controlAt(x, y)?.takeIf { it.stick < 0 }
|
||||
for (control in controls) {
|
||||
if (control.stick < 0 && control.pressedBy == pointer && control !== over) {
|
||||
@@ -285,7 +468,9 @@ class OnScreenControls(context: Context, private val pad: PadBridge) : View(cont
|
||||
for (control in controls) {
|
||||
if (control.pressedBy == pointer || event.actionMasked == MotionEvent.ACTION_CANCEL) {
|
||||
if (control.pressedBy != -1) changed = true
|
||||
if (control.stick >= 0 && control.pressedBy != -1) control.lastUp = if (control.clicked) 0L else event.eventTime
|
||||
control.pressedBy = -1
|
||||
control.clicked = false
|
||||
if (control.stick >= 0 && (control.kx != 0f || control.ky != 0f)) control.dirty = true
|
||||
control.kx = 0f; control.ky = 0f
|
||||
}
|
||||
@@ -297,45 +482,114 @@ class OnScreenControls(context: Context, private val pad: PadBridge) : View(cont
|
||||
return false
|
||||
}
|
||||
|
||||
private fun onEditTouch(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
val control = controlAt(event.x, event.y)
|
||||
selected = control?.group
|
||||
val group = selected ?: run { invalidate(); return false }
|
||||
val (x, y) = centre(group)
|
||||
grabX = x - event.x
|
||||
grabY = y - event.y
|
||||
invalidate()
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val group = selected ?: return true
|
||||
ignoreSaved = false
|
||||
put(group, event.x + grabX, event.y + grabY)
|
||||
clamp(group)
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun controlAt(x: Float, y: Float): Control? =
|
||||
controls.firstOrNull { isVisible(it) && it.contains(x, y, controlRadius(it)) }
|
||||
controls.firstOrNull { isVisible(it) && it.contains(x, y, it.radius) }
|
||||
|
||||
private fun isVisible(control: Control): Boolean =
|
||||
!buttonsOnly || control.id == "guide" || control.id == "qam"
|
||||
|
||||
private fun controlRadius(control: Control): Float =
|
||||
if (buttonsOnly && (control.id == "guide" || control.id == "qam")) dp(30f) else control.radius
|
||||
private fun isVisible(control: Control): Boolean = when {
|
||||
buttonsOnly && !editing -> control.id == "guide" || control.id == "qam"
|
||||
else -> control.target != ControllerPrefs.OFF
|
||||
}
|
||||
|
||||
private fun apply() {
|
||||
val bridge = pad
|
||||
if (bridge == null || editing) { invalidate(); return }
|
||||
val qamHeld = controls.any { it.id == "qam" && it.pressedBy != -1 }
|
||||
if (buttonsOnly) {
|
||||
val guidePressed = controls.first { it.id == "guide" }.pressedBy != -1
|
||||
val qamPressed = controls.first { it.id == "qam" }.pressedBy != -1
|
||||
pad.setSystemButtons(guidePressed, qamPressed)
|
||||
bridge.setSystemButtons(controls.any { it.id == "guide" && it.pressedBy != -1 }, qamHeld)
|
||||
} else {
|
||||
pad.setSystemButtons(false, false)
|
||||
pad.applyTouch { state ->
|
||||
bridge.setSystemButtons(false, qamHeld)
|
||||
bridge.applyTouch { state ->
|
||||
val used = HashSet<String>()
|
||||
val held = HashSet<String>()
|
||||
for (control in controls) {
|
||||
val held = control.pressedBy != -1
|
||||
when {
|
||||
control.stick >= 0 && !control.dirty -> {}
|
||||
control.stick == 0 -> { state.leftX = control.kx / control.radius; state.leftY = control.ky / control.radius; control.dirty = false }
|
||||
control.stick == 1 -> { state.rightX = control.kx / control.radius; state.rightY = control.ky / control.radius; control.dirty = false }
|
||||
control.dpad == 0 -> state.up = held
|
||||
control.dpad == 1 -> state.right = held
|
||||
control.dpad == 2 -> state.down = held
|
||||
control.dpad == 3 -> state.left = held
|
||||
control.button >= 0 -> state.press(control.button, held)
|
||||
control.stick >= 0 -> {
|
||||
val click = if (control.stick == 0) "l3" else "r3"
|
||||
if (settings.stickClick) used.add(click)
|
||||
if (control.clicked) held.add(click)
|
||||
if (!control.dirty) continue
|
||||
if (control.stick == 0) { state.leftX = control.kx / control.radius; state.leftY = control.ky / control.radius }
|
||||
else { state.rightX = control.kx / control.radius; state.rightY = control.ky / control.radius }
|
||||
control.dirty = false
|
||||
}
|
||||
control.id == "qam" || control.target == ControllerPrefs.OFF -> {}
|
||||
else -> {
|
||||
used.add(control.target)
|
||||
if (control.pressedBy != -1) held.add(control.target)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (target in used) write(state, target, target in held)
|
||||
}
|
||||
}
|
||||
invalidate()
|
||||
}
|
||||
|
||||
/** Everything up, for when the controls are hidden mid-press. */
|
||||
private fun write(state: PadState, target: String, down: Boolean) {
|
||||
when (target) {
|
||||
"a" -> state.press(PadState.A, down)
|
||||
"b" -> state.press(PadState.B, down)
|
||||
"x" -> state.press(PadState.X, down)
|
||||
"y" -> state.press(PadState.Y, down)
|
||||
"lb" -> state.press(PadState.LB, down)
|
||||
"rb" -> state.press(PadState.RB, down)
|
||||
"select" -> state.press(PadState.SELECT, down)
|
||||
"start" -> state.press(PadState.START, down)
|
||||
"l3" -> state.press(PadState.L3, down)
|
||||
"r3" -> state.press(PadState.R3, down)
|
||||
"guide" -> state.press(PadState.GUIDE, down)
|
||||
"lt" -> state.leftTrigger = if (down) 1f else 0f
|
||||
"rt" -> state.rightTrigger = if (down) 1f else 0f
|
||||
"up" -> state.up = down
|
||||
"right" -> state.right = down
|
||||
"down" -> state.down = down
|
||||
"left" -> state.left = down
|
||||
}
|
||||
}
|
||||
|
||||
fun releaseAll() {
|
||||
if (controls.none { it.pressedBy != -1 } && !buttonsOnly) return
|
||||
controls.forEach { it.pressedBy = -1; if (it.stick >= 0 && (it.kx != 0f || it.ky != 0f)) it.dirty = true; it.kx = 0f; it.ky = 0f }
|
||||
if (controls.none { it.pressedBy != -1 || it.clicked } && !buttonsOnly) return
|
||||
controls.forEach {
|
||||
it.pressedBy = -1
|
||||
it.clicked = false
|
||||
if (it.stick >= 0 && (it.kx != 0f || it.ky != 0f)) it.dirty = true
|
||||
it.kx = 0f; it.ky = 0f
|
||||
}
|
||||
apply()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val DOUBLE_TAP_MS = 300L
|
||||
const val MIN_FACE_MM = 9.5f
|
||||
const val FULL_SIZE_HEIGHT_MM = 85f
|
||||
const val BOTTOM_MARGIN_MM = 5f
|
||||
const val DROP_DEGREES = 35.0
|
||||
const val PHONE_MAX_HEIGHT_MM = 90f
|
||||
const val SHOULDER_WIDTH = 1.45f
|
||||
const val SHOULDER_HEIGHT = 0.8f
|
||||
val shoulderIds = setOf("lb", "rb", "lt", "rt")
|
||||
val directions = listOf("up", "right", "down", "left")
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,9 @@ public final class PadBridge {
|
||||
private boolean qamChordActive;
|
||||
private boolean qamSyntheticAPressed;
|
||||
private int qamChordGeneration;
|
||||
/** Told on the main thread when a player uses the pad or the on-screen controls; see [setOnPlayerInput]. */
|
||||
private volatile Runnable onPlayerInput;
|
||||
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
|
||||
public PadBridge(File fakeInputDir) {
|
||||
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT);
|
||||
@@ -87,6 +90,24 @@ public final class PadBridge {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called (main thread) when a player presses a button, pushes a stick, trigger or d-pad past
|
||||
* halfway, or uses the on-screen controls - the session hides its mouse cursor then. Resting
|
||||
* sticks and trigger noise do not count.
|
||||
*/
|
||||
public void setOnPlayerInput(Runnable listener) {
|
||||
onPlayerInput = listener;
|
||||
}
|
||||
|
||||
private void notePlayerInput() {
|
||||
Runnable listener = onPlayerInput;
|
||||
if (listener == null || !playerInputPosted.compareAndSet(false, true)) return;
|
||||
mainHandler.post(() -> {
|
||||
playerInputPosted.set(false);
|
||||
listener.run();
|
||||
});
|
||||
}
|
||||
|
||||
/** @return true when the event was a pad button and has been consumed. */
|
||||
public synchronized boolean onKeyEvent(KeyEvent event) {
|
||||
if (!isFromController(event.getDevice())) return false;
|
||||
@@ -116,6 +137,7 @@ public final class PadBridge {
|
||||
case KeyEvent.KEYCODE_DPAD_LEFT: state.left = pressed; break;
|
||||
default: return false;
|
||||
}
|
||||
if (pressed) notePlayerInput();
|
||||
publish();
|
||||
return true;
|
||||
}
|
||||
@@ -143,6 +165,10 @@ public final class PadBridge {
|
||||
state.right = hatX > 0.5f;
|
||||
state.down = hatY > 0.5f;
|
||||
state.left = hatX < -0.5f;
|
||||
if (Math.max(Math.max(Math.abs(state.leftX), Math.abs(state.leftY)), Math.max(Math.abs(state.rightX), Math.abs(state.rightY))) > 0.5f
|
||||
|| lt > 0.5f || rt > 0.5f || state.up || state.right || state.down || state.left) {
|
||||
notePlayerInput();
|
||||
}
|
||||
publish();
|
||||
return true;
|
||||
}
|
||||
@@ -153,6 +179,7 @@ public final class PadBridge {
|
||||
*/
|
||||
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
|
||||
mutation.accept(state);
|
||||
notePlayerInput();
|
||||
publish();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.security.MessageDigest
|
||||
import org.json.JSONArray
|
||||
|
||||
/** Optional Decky Loader installation for the ARM64 Linux guest. */
|
||||
object DeckyManager {
|
||||
private const val TAG = "DeckyManager"
|
||||
const val REPOSITORY = "Droid-Deck/decky-loader"
|
||||
private const val RELEASES = "https://api.github.com/repos/$REPOSITORY/releases?per_page=30"
|
||||
private const val PATH = "root/homebrew/services/PluginLoader"
|
||||
private const val VERSION = "root/homebrew/services/.droiddeck-decky-version"
|
||||
private const val CEF_REMOTE_DEBUG_MARKER = "root/.local/share/Steam/.cef-enable-remote-debugging"
|
||||
|
||||
data class Release(val tag: String, val prerelease: Boolean, val asset: String, val url: String, val digest: String?, val shaUrl: String?, val size: Long, val machine: Int)
|
||||
data class ReleaseChannels(val stable: List<Release>, val prerelease: List<Release>)
|
||||
|
||||
fun installed(context: Context): String? {
|
||||
val loader = loader(context)
|
||||
if (!loader.isFile || !loader.canExecute()) return null
|
||||
return File(LinuxRuntime.rootDir(context), VERSION).takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: "Installed"
|
||||
}
|
||||
|
||||
fun loader(context: Context) = File(LinuxRuntime.rootDir(context), PATH)
|
||||
fun supervisorEnabled(context: Context) = File(LinuxRuntime.rootDir(context), "root/.droiddeck-decky-enabled").isFile
|
||||
|
||||
/** Remove the legacy install-time debugger marker unless the user opted into Decky. */
|
||||
fun syncCefMarker(context: Context) {
|
||||
val marker = File(LinuxRuntime.rootDir(context), CEF_REMOTE_DEBUG_MARKER)
|
||||
if (!supervisorEnabled(context)) {
|
||||
marker.delete()
|
||||
return
|
||||
}
|
||||
runCatching {
|
||||
marker.parentFile?.mkdirs()
|
||||
marker.createNewFile()
|
||||
}
|
||||
}
|
||||
|
||||
fun setSupervisorEnabled(context: Context, enabled: Boolean) {
|
||||
val marker = File(LinuxRuntime.rootDir(context), "root/.droiddeck-decky-enabled")
|
||||
val cefMarker = File(LinuxRuntime.rootDir(context), CEF_REMOTE_DEBUG_MARKER)
|
||||
if (enabled) {
|
||||
marker.parentFile?.mkdirs()
|
||||
marker.writeText("enabled\n")
|
||||
cefMarker.parentFile?.mkdirs()
|
||||
cefMarker.createNewFile()
|
||||
} else {
|
||||
marker.delete()
|
||||
cefMarker.delete()
|
||||
}
|
||||
}
|
||||
|
||||
fun releases(context: Context, prerelease: Boolean): List<Release> {
|
||||
val channels = releaseChannels(context)
|
||||
return if (prerelease) channels.prerelease else channels.stable
|
||||
}
|
||||
|
||||
fun releaseChannels(context: Context): ReleaseChannels {
|
||||
val body = Downloader.downloadString(RELEASES) ?: return ReleaseChannels(emptyList(), emptyList())
|
||||
return try {
|
||||
val array = JSONArray(body)
|
||||
val stable = mutableListOf<Release>()
|
||||
val prerelease = mutableListOf<Release>()
|
||||
for (i in 0 until array.length()) {
|
||||
val release = array.getJSONObject(i)
|
||||
if (release.optBoolean("draft", false)) continue
|
||||
val isPrerelease = release.optBoolean("prerelease", false)
|
||||
val assets = release.optJSONArray("assets") ?: continue
|
||||
val rows = (0 until assets.length()).map { assets.getJSONObject(it) }
|
||||
val arm = rows.firstOrNull { it.optString("name") == "PluginLoader-arm64" }
|
||||
val guest = LinuxRuntime.rootDir(context)
|
||||
val fexReady = File(guest, "usr/share/guestos/fex-mesa").isDirectory && File(guest, "usr/bin/FEX").canExecute()
|
||||
val binary = arm ?: if (fexReady) rows.firstOrNull { it.optString("name") == "PluginLoader" } else null
|
||||
val name = binary?.optString("name") ?: continue
|
||||
val url = binary.optString("browser_download_url").takeIf { it.startsWith("https://") } ?: continue
|
||||
val checksum = rows.firstOrNull {
|
||||
val n = it.optString("name")
|
||||
(n == "$name.sha256" || n == "$name.sha256sum" || n == "$name.sha256.txt") && it.optString("browser_download_url").startsWith("https://")
|
||||
}?.optString("browser_download_url")?.takeIf { it.startsWith("https://") }
|
||||
val digest = binary.optString("digest").takeIf { it.matches(Regex("(?i)sha256:[0-9a-f]{64}")) }
|
||||
if (digest == null && checksum == null) continue
|
||||
val size = binary.optLong("size", 0)
|
||||
if (size <= 0) continue
|
||||
val row = Release(release.optString("tag_name", "unknown"), isPrerelease, name, url, digest, checksum, size, if (name == "PluginLoader-arm64") 183 else 62)
|
||||
(if (isPrerelease) prerelease else stable).add(row)
|
||||
}
|
||||
ReleaseChannels(stable, prerelease)
|
||||
} catch (e: Exception) { Log.w(TAG, "release metadata", e); ReleaseChannels(emptyList(), emptyList()) }
|
||||
}
|
||||
|
||||
/** Downloads to a sibling temp file and atomically renames only after size, digest and ELF checks. */
|
||||
fun install(context: Context, release: Release, progress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return "Stop the active session before installing Decky Loader"
|
||||
val target = loader(context)
|
||||
target.parentFile?.mkdirs()
|
||||
val temp = File(target.parentFile, "PluginLoader.download")
|
||||
val ok = Downloader.downloadFile(release.url, temp, false) { f -> progress("Downloading ${release.tag}", if (f < 0) -1 else (f * 100).toInt().coerceIn(0, 100)) }
|
||||
if (!ok) { temp.delete(); return "Decky Loader download failed" }
|
||||
if (temp.length() != release.size) { temp.delete(); return "Decky Loader size did not match the release metadata" }
|
||||
val expected = release.digest?.substringAfter(':') ?: release.shaUrl?.let { checksumUrl ->
|
||||
val checksumBody = Downloader.downloadString(checksumUrl) ?: run { temp.delete(); return "Could not download the release checksum" }
|
||||
Regex("(?i)\\b[0-9a-f]{64}\\b").find(checksumBody)?.value
|
||||
} ?: run { temp.delete(); return "Release checksum is missing" }
|
||||
if (!expected.matches(Regex("(?i)[0-9a-f]{64}"))) { temp.delete(); return "Release checksum is invalid" }
|
||||
if (!expected.equals(sha256(temp), true)) { temp.delete(); return "Decky Loader checksum mismatch" }
|
||||
if (!validElf(temp, release.machine)) { temp.delete(); return "Release asset is not a compatible 64-bit Linux executable" }
|
||||
if (SessionState.running) { temp.delete(); return "A session started during the download; stop it before installing Decky Loader" }
|
||||
if (!temp.setExecutable(true, false)) { temp.delete(); return "Could not mark PluginLoader executable" }
|
||||
// Decky needs Steam's local CEF debugger only when its session supervisor is enabled.
|
||||
val cefMarker = File(LinuxRuntime.rootDir(context), CEF_REMOTE_DEBUG_MARKER)
|
||||
val cefReady = !supervisorEnabled(context) || cefMarker.isFile || runCatching {
|
||||
cefMarker.parentFile?.mkdirs()
|
||||
cefMarker.createNewFile() || cefMarker.isFile
|
||||
}.getOrDefault(false)
|
||||
if (!cefReady) { temp.delete(); return "Could not enable Steam CEF remote debugging" }
|
||||
val staged = File(target.parentFile, "PluginLoader.new")
|
||||
staged.delete()
|
||||
if (!temp.renameTo(staged)) { temp.delete(); return "Could not stage PluginLoader" }
|
||||
val old = File(target.parentFile, "PluginLoader.old")
|
||||
old.delete()
|
||||
if (target.exists() && !target.renameTo(old)) { staged.delete(); return "Could not preserve the existing PluginLoader" }
|
||||
if (!staged.renameTo(target)) {
|
||||
if (old.exists()) old.renameTo(target)
|
||||
staged.delete()
|
||||
return "Could not activate the new PluginLoader"
|
||||
}
|
||||
old.delete()
|
||||
File(target.parentFile, ".droiddeck-decky-version").writeText(release.tag + "\n")
|
||||
File(target.parentFile, ".droiddeck-decky-arch").writeText(if (release.machine == 183) "arm64\n" else "x86_64\n")
|
||||
if (!supervisorEnabled(context)) cefMarker.delete()
|
||||
return null
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, wipeData: Boolean) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
setSupervisorEnabled(context, false)
|
||||
File(root, PATH).delete()
|
||||
File(root, VERSION).delete()
|
||||
File(root, "root/homebrew/services/.droiddeck-decky-arch").delete()
|
||||
File(root, CEF_REMOTE_DEBUG_MARKER).delete()
|
||||
if (wipeData) File(root, "root/homebrew").deleteRecursively()
|
||||
}
|
||||
|
||||
private fun sha256(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
FileInputStream(file).buffered().use { input ->
|
||||
val buffer = ByteArray(1024 * 1024)
|
||||
while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) }
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 255) }
|
||||
}
|
||||
|
||||
private fun validElf(file: File, machine: Int): Boolean = runCatching {
|
||||
file.inputStream().use { input ->
|
||||
val h = ByteArray(20)
|
||||
if (input.read(h) != h.size) return false
|
||||
h[0] == 0x7f.toByte() && h[1] == 'E'.code.toByte() && h[2] == 'L'.code.toByte() && h[3] == 'F'.code.toByte() &&
|
||||
h[4] == 2.toByte() && h[5] == 1.toByte() && (h[18].toInt() and 255) + ((h[19].toInt() and 255) shl 8) == machine
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import android.os.Process;
|
||||
import android.system.ErrnoException;
|
||||
import android.system.Os;
|
||||
import android.system.StructStat;
|
||||
import android.system.StructUtsname;
|
||||
|
||||
|
||||
import java.io.File;
|
||||
@@ -32,6 +33,7 @@ public final class LinuxRuntime {
|
||||
/** Shortcut extra naming which of the modes above a Linux entry launches. */
|
||||
public static final String EXTRA_LINUX_MODE = "linux_mode";
|
||||
private static final String KGSL_DEVICE = "/dev/kgsl-3d0";
|
||||
private static final String GUEST_HOSTNAME = "DroidDeck";
|
||||
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
|
||||
public static final String DEBUG_LOG_DIR = "DroidDeck";
|
||||
|
||||
@@ -116,6 +118,8 @@ public final class LinuxRuntime {
|
||||
List<String> cmd = new ArrayList<>();
|
||||
cmd.add(prootBinary(context).getPath());
|
||||
cmd.add("--kill-on-exit");
|
||||
// Preserve the host kernel identity while giving the guest the app's branded host name.
|
||||
cmd.add("--kernel-release=" + guestUtsname());
|
||||
// Android's app seccomp policy traps the whole set*id family. Xwayland's Popen() calls
|
||||
// setgid()/setuid() before it execs xkbcomp and _exit(127)s when they fail, so without
|
||||
// this the keymap never compiles and Xwayland dies. -i makes proot answer those calls
|
||||
@@ -245,6 +249,13 @@ public final class LinuxRuntime {
|
||||
cmd.add(spec);
|
||||
}
|
||||
|
||||
/** PRoot's complex -k format: sysname, nodename, release, version, machine, domain, HWCAP. */
|
||||
private static String guestUtsname() {
|
||||
StructUtsname host = Os.uname();
|
||||
return "\\" + host.sysname + "\\" + GUEST_HOSTNAME + "\\" + host.release
|
||||
+ "\\" + host.version + "\\" + host.machine + "\\localdomain\\-1\\";
|
||||
}
|
||||
|
||||
/** X access control and Steam look the session user up by uid: the app uid is root inside. */
|
||||
public static void writeAccounts(Context context) throws IOException {
|
||||
File root = rootDir(context);
|
||||
|
||||
@@ -31,6 +31,9 @@ object SessionArtifacts {
|
||||
/** Written last; a folder without it did not get its ending. */
|
||||
const val COMPLETE_MARKER = ".complete"
|
||||
|
||||
/** Every file in the folder has been through the redactor, own addresses and accounts included (-2: accounts added). */
|
||||
private const val SCRUBBED_MARKER = ".scrubbed-2"
|
||||
|
||||
/** Everything the end of a session gathers, into [dir]. Safe to call for a dead session. */
|
||||
fun collect(context: Context, dir: File, reason: String) {
|
||||
try {
|
||||
@@ -40,9 +43,12 @@ object SessionArtifacts {
|
||||
src.copyTo(wayland, overwrite = true)
|
||||
}
|
||||
}
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
copySteamLogs(context, dir)
|
||||
// A session the system killed leaves its trace here and nowhere else.
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
scrubFolder(dir)
|
||||
try { File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n") } catch (e: Exception) {}
|
||||
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
|
||||
} catch (e: Exception) {
|
||||
@@ -50,6 +56,47 @@ object SessionArtifacts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Once, for session folders written before every file was scrubbed and before the device's own
|
||||
* addresses were (network.txt listed them; the client's IPv6 check logs "external address"
|
||||
* into steam/connection_log.txt): the whole folder, steam/ included, through the redactor.
|
||||
* A marker records it. Runs at app start with [finishAbandoned].
|
||||
*/
|
||||
@Synchronized
|
||||
fun scrubOlder(context: Context) {
|
||||
val current = SessionPaths.current()
|
||||
val dirs = LinuxRuntime.debugLogDir().listFiles { f ->
|
||||
f.isDirectory && f.name.startsWith("session-") && f != current && !File(f, SCRUBBED_MARKER).exists()
|
||||
} ?: return
|
||||
if (dirs.isEmpty()) return
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
dirs.forEach { dir ->
|
||||
scrubFolder(dir)
|
||||
File(dir, "steam").takeIf { it.isDirectory }?.let { scrubFolder(it) }
|
||||
try { File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n") } catch (e: Exception) {}
|
||||
}
|
||||
Log.i(TAG, "scrubbed ${dirs.size} older session folder(s)")
|
||||
}
|
||||
|
||||
/**
|
||||
* The session's own files (session.log, app.log, desktop.log, the Steam desktop client's
|
||||
* steam-desktop.log, ...) were written as they happened, unscrubbed; this pass puts every one
|
||||
* through the redactor before the folder can be shared. A file is rewritten only if a line
|
||||
* changed. steam/ was scrubbed on the way in.
|
||||
*/
|
||||
private fun scrubFolder(dir: File) {
|
||||
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") }?.forEach { f ->
|
||||
if (!LogRedactor.isText(f)) return@forEach
|
||||
try {
|
||||
val tmp = File(dir, ".${f.name}.scrub")
|
||||
tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) }
|
||||
if (tmp.length() != f.length() || tmp.readBytes().contentEquals(f.readBytes()).not()) tmp.renameTo(f) else tmp.delete()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not scrub ${f.name}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Steam's logs: redacted into steam/, never copied verbatim. */
|
||||
private fun copySteamLogs(context: Context, dir: File) {
|
||||
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
|
||||
@@ -81,6 +128,7 @@ object SessionArtifacts {
|
||||
}?.sortedBy { it.name } ?: return
|
||||
if (abandoned.isEmpty()) return
|
||||
val current = SessionPaths.current()
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
abandoned.forEachIndexed { i, dir ->
|
||||
if (dir == current) return@forEachIndexed
|
||||
val newest = i == abandoned.lastIndex
|
||||
@@ -100,6 +148,7 @@ object SessionArtifacts {
|
||||
}
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
|
||||
scrubFolder(dir)
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
|
||||
Log.i(TAG, "finished the abandoned session folder $dir")
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -43,6 +43,8 @@ object SessionFiles {
|
||||
// the three under /usr/bin, all no-ops that answer "nothing to do" (see each file).
|
||||
"usr/bin/steamos-update" to "usr/bin/steamos-update",
|
||||
"usr/bin/steamos-select-branch" to "usr/bin/steamos-select-branch",
|
||||
// Big Picture's "Switch to Desktop": asks the app for the desktop with Steam in it.
|
||||
"usr/bin/steamos-session-select" to "usr/bin/steamos-session-select",
|
||||
"usr/bin/jupiter-biosupdate" to "usr/bin/jupiter-biosupdate",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-priv-write" to "usr/bin/steamos-polkit-helpers/steamos-priv-write",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-set-timezone" to "usr/bin/steamos-polkit-helpers/steamos-set-timezone",
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.content.ClipData
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.content.FileProvider
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.util.zip.ZipEntry
|
||||
@@ -22,14 +23,28 @@ object SessionLogShare {
|
||||
.maxByOrNull { it.name }
|
||||
|
||||
/** Builds the zip (blocking). Returns null when there is no session to share. */
|
||||
fun zipLatest(context: Context): File? {
|
||||
val folder = latest(context) ?: return null
|
||||
fun zipLatest(context: Context): File? = latest(context)?.let { zipFolder(context, it) }
|
||||
|
||||
/** Builds a zip for one specific session folder (blocking). */
|
||||
fun zipFolder(context: Context, folder: File): File? {
|
||||
if (!folder.isDirectory) return null
|
||||
val files = folder.walkTopDown().filter { it.isFile }.toList()
|
||||
if (files.isEmpty()) return null
|
||||
val out = File(context.cacheDir, "shared-logs").apply { deleteRecursively(); mkdirs() }
|
||||
val zip = File(out, "DroidDeck-${folder.name}.zip")
|
||||
// Scrubbed on the way into the zip: a session shared while it runs has not had its end-of-
|
||||
// session pass yet, and the redactor changes nothing in a line that is already clean.
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { z ->
|
||||
folder.walkTopDown().filter { it.isFile }.forEach { f ->
|
||||
files.forEach { f ->
|
||||
z.putNextEntry(ZipEntry(folder.name + "/" + f.relativeTo(folder).path))
|
||||
f.inputStream().use { it.copyTo(z) }
|
||||
if (LogRedactor.isText(f)) {
|
||||
val w = z.bufferedWriter()
|
||||
LogRedactor.scrubTo(f, w)
|
||||
w.flush()
|
||||
} else {
|
||||
f.inputStream().use { it.copyTo(z) }
|
||||
}
|
||||
z.closeEntry()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,6 +282,10 @@ object SessionPrefs {
|
||||
*/
|
||||
fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", defaultResolutionCap(mode))
|
||||
|
||||
/** Whether the user chose the mode's resolution (a cap or a custom size) rather than the default. */
|
||||
fun resolutionChosen(context: Context, mode: String): Boolean =
|
||||
prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null
|
||||
|
||||
/** The FEXCore preset for the games the client launches (core/FexPreset ids); "" = FEX's defaults. */
|
||||
fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", "") ?: ""
|
||||
|
||||
|
||||
@@ -144,6 +144,13 @@ class SessionService : Service() {
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_SUSPEND_POLICY_CHANGED -> {
|
||||
if (!SessionState.running) return START_NOT_STICKY
|
||||
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_RESUME -> {
|
||||
activityVisible = true
|
||||
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn
|
||||
@@ -462,6 +469,9 @@ class SessionService : Service() {
|
||||
// The second library's name, for bannerlator-steam-library; the bind itself is made below.
|
||||
GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
|
||||
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("BL_STEAM_UI=desktop")
|
||||
// The desktop asked for with Steam in it (the front end's "Steam Desktop UI", Big Picture's
|
||||
// "Switch to Desktop"): the desktop's autostart opens the client's desktop UI there.
|
||||
if (SessionState.mode == MODE_DESKTOP && SessionState.steamUi == "desktop") guest.add("BL_DESKTOP_STEAM=1")
|
||||
val shellGuest = ArrayList(guest).apply {
|
||||
add("SHELL=/bin/bash")
|
||||
add("TERM=xterm-256color")
|
||||
@@ -594,7 +604,9 @@ class SessionService : Service() {
|
||||
components.add(networkLink)
|
||||
components.forEach { it.start() }
|
||||
|
||||
val line = command.joinToString(" ") { it.replace(" ", "\\ ") }
|
||||
val line = command.joinToString(" ") {
|
||||
it.replace("\\", "\\\\").replace(" ", "\\ ")
|
||||
}
|
||||
watchLaunchRequests(sessionRoot)
|
||||
// One session replacing another (the desktop's Steam launchers): the old proot is killed
|
||||
// by the teardown a second after the new one has started, and its exit used to arrive
|
||||
@@ -725,6 +737,8 @@ class SessionService : Service() {
|
||||
* The desktop's Steam launchers cannot start the client where they are (no dma-buf on the
|
||||
* desktop), so they leave `steam-launch` in the session directory instead: which UI, and a
|
||||
* steam:// URL or nothing. This ends the session and hands the activity the one to start.
|
||||
* `session=desktop` (Big Picture's "Switch to Desktop", steamos-session-select) asks for the
|
||||
* desktop instead, with Steam's desktop client started in it.
|
||||
*/
|
||||
private var launchWatcher: android.os.FileObserver? = null
|
||||
|
||||
@@ -739,15 +753,18 @@ class SessionService : Service() {
|
||||
file.delete()
|
||||
var ui = "desktop"
|
||||
var url = ""
|
||||
var session = MODE_STEAM
|
||||
text.lineSequence().forEach { line ->
|
||||
when {
|
||||
line.startsWith("ui=") -> ui = line.removePrefix("ui=").trim()
|
||||
line.startsWith("url=") -> url = line.removePrefix("url=").trim()
|
||||
line.startsWith("session=") && line.removePrefix("session=").trim() == "desktop" -> session = MODE_DESKTOP
|
||||
}
|
||||
}
|
||||
Log.i(TAG, "launch request from the session: Steam $ui" + (if (url.isNotEmpty()) " $url" else ""))
|
||||
Log.i(TAG, "launch request from the session: " + (if (session == MODE_DESKTOP) "the desktop with " else "") +
|
||||
"Steam $ui" + (if (url.isNotEmpty()) " $url" else ""))
|
||||
val next = Intent(this@SessionService, com.droiddeck.launcher.SessionActivity::class.java)
|
||||
.putExtra(EXTRA_MODE, MODE_STEAM)
|
||||
.putExtra(EXTRA_MODE, session)
|
||||
.putExtra(EXTRA_STEAM_UI, ui)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (url.isNotEmpty()) next.putExtra(EXTRA_STEAM_URL, url)
|
||||
@@ -1016,6 +1033,7 @@ class SessionService : Service() {
|
||||
const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION"
|
||||
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
|
||||
const val ACTION_AGENT_START = "com.droiddeck.launcher.AGENT_START"
|
||||
private const val ACTION_SUSPEND_POLICY_CHANGED = "com.droiddeck.launcher.SUSPEND_POLICY_CHANGED"
|
||||
private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE"
|
||||
private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN"
|
||||
private const val ACTION_TRACK_AUXILIARY = "com.droiddeck.launcher.TRACK_AUXILIARY"
|
||||
@@ -1038,7 +1056,8 @@ class SessionService : Service() {
|
||||
const val EXTRA_PROGRAM = "program"
|
||||
/** MODE_RUN: arguments after the program (a game to boot). */
|
||||
const val EXTRA_PROGRAM_ARGS = "programArgs"
|
||||
/** MODE_STEAM: "desktop" for the client's desktop UI (default Big Picture); a steam:// URL to hand it. */
|
||||
/** MODE_STEAM: "desktop" for the client's desktop UI (default Big Picture); a steam:// URL to hand it.
|
||||
* MODE_DESKTOP: "desktop" = open Steam's desktop client in the desktop once it is up. */
|
||||
const val EXTRA_STEAM_UI = "steamUi"
|
||||
const val EXTRA_STEAM_URL = "steamUrl"
|
||||
|
||||
@@ -1070,6 +1089,11 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_RESUME))
|
||||
}
|
||||
|
||||
fun suspendPolicyChanged(context: Context) {
|
||||
if (!SessionState.running) return
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SUSPEND_POLICY_CHANGED))
|
||||
}
|
||||
|
||||
/** Let the session service clean up the PTY's proot tree if the control screen closes. */
|
||||
fun stopTerminalProcess(context: Context, pid: Int) {
|
||||
if (pid > 1) context.startService(
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
class ControllerActions(
|
||||
val onOsc: (String) -> Unit,
|
||||
val onTint: (Int) -> Unit,
|
||||
val onOpacity: (Int) -> Unit,
|
||||
val onSize: (Int) -> Unit,
|
||||
val onStickClick: (Boolean) -> Unit,
|
||||
val onAdaptiveSticks: (Boolean) -> Unit,
|
||||
val onEditLayout: () -> Unit,
|
||||
val onResetLayout: () -> Unit,
|
||||
val onMapping: () -> Unit,
|
||||
val onResetAll: () -> Unit,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun Swatch(color: Int) {
|
||||
Box(Modifier.size(14.dp).background(Color(color), CircleShape).border(1.dp, Color.White.copy(alpha = 0.35f), CircleShape))
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ColumnScope.ControllerRows(host: MenuHost, oscMode: String, c: ControllerPrefs.Settings, a: ControllerActions) {
|
||||
ChoiceRow(
|
||||
host, "controller-osc", "On-screen controls", "When the touch pad appears in a session",
|
||||
listOf(SessionPrefs.OSC_AUTO to "Auto", SessionPrefs.OSC_ALWAYS to "Always", SessionPrefs.OSC_STEAM_QAM to "Steam + QAM", SessionPrefs.OSC_NEVER to "Never"),
|
||||
oscMode, note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc,
|
||||
)
|
||||
val tintOpen = host.open == "controller-tint"
|
||||
SettingsRow("Colour", "Tint of the on-screen buttons", highlighted = tintOpen) {
|
||||
Box {
|
||||
ValueChip(ControllerPrefs.tints.firstOrNull { it.first == c.tint }?.second ?: "Custom", tintOpen) {
|
||||
host.open = if (tintOpen) null else "controller-tint"
|
||||
}
|
||||
AnchoredMenu(tintOpen, onDismiss = { if (host.open == "controller-tint") host.open = null }, title = "Colour") { firstItemFocus ->
|
||||
ControllerPrefs.tints.forEachIndexed { index, (color, name) ->
|
||||
MenuItem(name, checked = c.tint == color, leading = { Swatch(color) }, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
a.onTint(color)
|
||||
host.open = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ChoiceRow(host, "controller-opacity", "Opacity", null, ControllerPrefs.opacities.map { it to "$it%" }, c.opacity, onPick = a.onOpacity)
|
||||
ChoiceRow(host, "controller-size", "Button size", "100% keeps the standard size", ControllerPrefs.sizes.map { it to "$it%" }, c.size, onPick = a.onSize)
|
||||
ToggleRow(host, "controller-stick-click", "Stick click", "Double-tap a stick and hold for L3 or R3", c.stickClick, onChange = a.onStickClick)
|
||||
ToggleRow(host, "controller-adaptive", "Adaptive sticks", "A stick centres where your thumb lands and returns home when you let go", c.adaptiveSticks, onChange = a.onAdaptiveSticks)
|
||||
SettingsRow("Layout", if (c.customLayout) "Custom positions saved" else "Placed for this screen's size and your grip") {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
SecondaryButton("Edit") { a.onEditLayout() }
|
||||
SecondaryButton("Reset", enabled = c.customLayout) { a.onResetLayout() }
|
||||
}
|
||||
}
|
||||
val remapped = c.mapping.count { (id, target) -> id != target }
|
||||
ActionRow("Button mapping", if (remapped == 0) "Every button sends its own input" else "$remapped of ${c.mapping.size} buttons remapped", "Configure", a.onMapping)
|
||||
ActionRow("Reset controller", "Restore the default colour, opacity, size, stick behaviour, mapping and layout", "Reset", a.onResetAll)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ControllerMappingPage(mapping: Map<String, String>, onPick: (String, String) -> Unit, onReset: () -> Unit, onBack: () -> Unit) {
|
||||
val host = rememberMenuHost()
|
||||
SettingsPage(
|
||||
host, title = "Button mapping", eyebrow = "Controller",
|
||||
lede = "Choose what each on-screen button sends to the game. Hidden removes the button.",
|
||||
onBack = onBack,
|
||||
) {
|
||||
SettingsGroup("On-screen buttons") {
|
||||
for ((id, name) in ControllerPrefs.mappable) {
|
||||
ChoiceRow(host, "map-$id", name, null, ControllerPrefs.targets, mapping[id] ?: id) { onPick(id, it) }
|
||||
}
|
||||
}
|
||||
SettingsGroup("Defaults") {
|
||||
ActionRow("Reset mapping", "Every button sends its own input again", "Reset", onReset)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,35 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.FilterQuality
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
|
||||
/**
|
||||
* The session's pointer. [image]: the program's own cursor (wl_pointer.set_cursor - labwc's resize
|
||||
* arrows, a text field's I-beam), in session pixels, drawn [imageScale] times larger with its hotspot
|
||||
* ([hotX], [hotY]) on [position]; null = the program has not set one, and the built-in arrow is drawn.
|
||||
*/
|
||||
@Composable
|
||||
fun CursorOverlay(position: Offset, visible: Boolean, scale: Float) {
|
||||
fun CursorOverlay(
|
||||
position: Offset, visible: Boolean, scale: Float,
|
||||
image: ImageBitmap? = null, hotX: Int = 0, hotY: Int = 0, imageScale: Float = 1f,
|
||||
) {
|
||||
if (!visible) return
|
||||
Canvas(modifier = Modifier.fillMaxSize()) {
|
||||
if (image != null) {
|
||||
val w = (image.width * imageScale).toInt().coerceAtLeast(1)
|
||||
val h = (image.height * imageScale).toInt().coerceAtLeast(1)
|
||||
drawImage(
|
||||
image,
|
||||
dstOffset = androidx.compose.ui.unit.IntOffset(
|
||||
(position.x - hotX * imageScale).toInt(), (position.y - hotY * imageScale).toInt()),
|
||||
dstSize = androidx.compose.ui.unit.IntSize(w, h),
|
||||
filterQuality = FilterQuality.Low,
|
||||
)
|
||||
return@Canvas
|
||||
}
|
||||
val s = 11f * scale
|
||||
val path = Path().apply {
|
||||
moveTo(position.x, position.y)
|
||||
|
||||
@@ -4,7 +4,6 @@ import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
@@ -38,7 +37,9 @@ import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
@@ -75,9 +76,12 @@ import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Menu
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
@@ -110,6 +114,7 @@ import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.positionInRoot
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalWindowInfo
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
@@ -169,6 +174,8 @@ class FrontEndState(
|
||||
val sessionRunning: Boolean = false,
|
||||
val backActionsInverted: Boolean = false,
|
||||
val buildLabel: String = "local",
|
||||
val oscMode: String = SessionPrefs.OSC_AUTO,
|
||||
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
||||
)
|
||||
|
||||
class FrontEndActions(
|
||||
@@ -200,6 +207,7 @@ class FrontEndActions(
|
||||
val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> },
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onCheckLatestBuild: () -> Unit = {},
|
||||
val controller: ControllerActions? = null,
|
||||
)
|
||||
|
||||
|
||||
@@ -266,9 +274,10 @@ private fun Modifier.shine(trigger: Boolean, strength: Float = 0.22f): Modifier
|
||||
*/
|
||||
private class FrontFocus {
|
||||
val rail = HashMap<String, FocusRequester>()
|
||||
val menuToggle = FocusRequester()
|
||||
val primary = FocusRequester()
|
||||
var primaryAttached by mutableStateOf(0)
|
||||
var railFocused by mutableStateOf(false)
|
||||
var focusedRail by mutableStateOf<String?>(null)
|
||||
fun railFor(key: String): FocusRequester = rail.getOrPut(key) { FocusRequester() }
|
||||
// The pane's controls by id (a tile's key, a button's label), how many of each are on screen,
|
||||
// and the last one focused.
|
||||
@@ -333,6 +342,7 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -
|
||||
@Composable
|
||||
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) {
|
||||
var selected by rememberSaveable { mutableStateOf("steam") }
|
||||
var navOpen by rememberSaveable { mutableStateOf(false) }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val ctx = LocalContext.current
|
||||
@@ -354,38 +364,30 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
|
||||
var anyFocused by remember { mutableStateOf(false) }
|
||||
BoxWithConstraints(modifier = Modifier.fillMaxSize().background(colors.background).systemBarsPadding().onFocusChanged { anyFocused = it.hasFocus }) {
|
||||
val wide = maxWidth >= 640.dp
|
||||
val drawerWidth = minOf(280.dp, maxWidth * 0.82f)
|
||||
val railSelection = when {
|
||||
s.pageKey == "performance" || s.pageKey == "protons" -> "setup"
|
||||
s.pageKey == "performance" || s.pageKey == "protons" || s.pageKey == "controller-mapping" -> "setup"
|
||||
s.pageKey?.startsWith("settings:steam") == true -> "steam"
|
||||
s.pageKey?.startsWith("settings:") == true -> "desktop"
|
||||
selected.startsWith("app:") -> "steam"
|
||||
selected.startsWith("emu:") || selected.startsWith("rom:") -> "desktop"
|
||||
else -> s.pageKey ?: selected
|
||||
}
|
||||
val rail: @Composable () -> Unit = {
|
||||
Rail(
|
||||
s, railSelection,
|
||||
onSelect = { key ->
|
||||
if (s.pageKey != null) a.onPageBack()
|
||||
selected = key
|
||||
},
|
||||
a,
|
||||
modifier = if (wide) Modifier.width(236.dp).fillMaxHeight() else Modifier.fillMaxWidth().height(maxHeight * 0.42f),
|
||||
)
|
||||
val onRailSelect: (String) -> Unit = { key ->
|
||||
if (s.pageKey != null) a.onPageBack()
|
||||
selected = key
|
||||
navOpen = false
|
||||
}
|
||||
// The app opens with the selected rail item focused, so a controller sees where it is. An
|
||||
// app starts in touch mode, where clickables refuse focus, so leave it first (a touch goes
|
||||
// straight back to it); a request before the window has focus is dropped, so wait for
|
||||
// that and retry until it sticks.
|
||||
// Start controllers on the current page's main action; the rail is initially collapsed.
|
||||
val window = LocalWindowInfo.current
|
||||
val inputMode = LocalInputModeManager.current
|
||||
LaunchedEffect(Unit) {
|
||||
snapshotFlow { window.isWindowFocused }.first { it }
|
||||
repeat(20) {
|
||||
if (frontFocus.railFocused) return@LaunchedEffect
|
||||
if (anyFocused) return@LaunchedEffect
|
||||
if (inputMode.inputMode != InputMode.Keyboard) inputMode.requestInputMode(InputMode.Keyboard)
|
||||
runCatching { frontFocus.railFor(railSelection).requestFocus() }
|
||||
val target = if (frontFocus.primaryAttached > 0) frontFocus.primary else frontFocus.menuToggle
|
||||
runCatching { target.requestFocus() }
|
||||
kotlinx.coroutines.delay(100)
|
||||
}
|
||||
}
|
||||
@@ -397,17 +399,28 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
kotlinx.coroutines.delay(450)
|
||||
if (!anyFocused && inputModeManager.inputMode == InputMode.Keyboard) runCatching {
|
||||
if (frontFocus.primaryAttached > 0) frontFocus.primary.requestFocus()
|
||||
else frontFocus.railFor(railSelection).requestFocus()
|
||||
else frontFocus.menuToggle.requestFocus()
|
||||
}
|
||||
}
|
||||
val back = if (wide) FocusDirection.Left else FocusDirection.Up
|
||||
val paneFocus = Modifier
|
||||
.focusProperties {
|
||||
enter = { frontFocus.paneEntry() }
|
||||
exit = { dir ->
|
||||
if (dir == back) frontFocus.rail[railSelection] ?: FocusRequester.Default else FocusRequester.Default
|
||||
LaunchedEffect(navOpen, railSelection) {
|
||||
if (navOpen) {
|
||||
frontFocus.focusedRail = null
|
||||
repeat(12) {
|
||||
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||
runCatching { frontFocus.railFor(railSelection).requestFocus() }
|
||||
if (frontFocus.focusedRail == railSelection) return@LaunchedEffect
|
||||
kotlinx.coroutines.delay(80)
|
||||
}
|
||||
} else {
|
||||
kotlinx.coroutines.delay(120)
|
||||
if (!anyFocused && inputModeManager.inputMode == InputMode.Keyboard) runCatching {
|
||||
if (frontFocus.primaryAttached > 0) frontFocus.paneEntry().requestFocus()
|
||||
else frontFocus.menuToggle.requestFocus()
|
||||
}
|
||||
}
|
||||
}
|
||||
val paneFocus = Modifier
|
||||
.focusProperties { enter = { frontFocus.paneEntry() } }
|
||||
.focusGroup()
|
||||
val content: @Composable (Modifier) -> Unit = { m ->
|
||||
Pane(s, selected, a, page, m.then(paneFocus), { selected = it }) { app ->
|
||||
@@ -415,8 +428,34 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
else appToChooseDisplay = app
|
||||
}
|
||||
}
|
||||
if (wide) Row(modifier = Modifier.fillMaxSize()) { rail(); content(Modifier.weight(1f).fillMaxHeight()) }
|
||||
else Column(modifier = Modifier.fillMaxSize()) { rail(); content(Modifier.weight(1f).fillMaxWidth()) }
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
LauncherTopBar(frontFocus.menuToggle) { navOpen = true }
|
||||
content(Modifier.weight(1f).fillMaxWidth())
|
||||
}
|
||||
AnimatedVisibility(
|
||||
visible = navOpen,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
enter = fadeIn(Motion.tw(150)) + slideInHorizontally(Motion.tw(210)) { -it / 5 },
|
||||
exit = fadeOut(Motion.tw(130)) + slideOutHorizontally(Motion.tw(170)) { -it / 5 },
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize()
|
||||
.background(Color.Black.copy(alpha = 0.62f))
|
||||
.clickable { navOpen = false },
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier.align(Alignment.CenterStart)
|
||||
.width(drawerWidth).fillMaxHeight()
|
||||
.focusProperties { exit = { FocusRequester.Cancel } }
|
||||
.focusGroup().zIndex(1f),
|
||||
) {
|
||||
Rail(s, railSelection, onRailSelect, a, Modifier.fillMaxSize()) { navOpen = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
appToChooseDisplay?.let { app ->
|
||||
val secondaryDisplay = s.secondScreenDisplays.firstOrNull()
|
||||
@@ -435,13 +474,42 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
)
|
||||
}
|
||||
}
|
||||
BackHandler(enabled = navOpen) { navOpen = false }
|
||||
val hasBackTarget = (s.pageKey != null && page != null) ||
|
||||
((s.pageKey == null || page == null) &&
|
||||
(selected.startsWith("app:") || selected.startsWith("emu:") || selected.startsWith("rom:")))
|
||||
BackHandler(enabled = !navOpen && !hasBackTarget) { navOpen = true }
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun LauncherTopBar(menuRequester: FocusRequester, onMenu: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val palette = LocalPalette.current
|
||||
var menuFocused by remember { mutableStateOf(false) }
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().height(48.dp).background(colors.surface),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
IconButton(
|
||||
onClick = onMenu,
|
||||
modifier = Modifier.size(48.dp).focusRequester(menuRequester)
|
||||
.onFocusChanged { menuFocused = it.isFocused }
|
||||
.border(2.dp, if (menuFocused) palette.signal else Color.Transparent, Shape10),
|
||||
) {
|
||||
Icon(Icons.Filled.Menu, contentDescription = "Open navigation", tint = colors.onBackground)
|
||||
}
|
||||
Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(24.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("DroidDeck", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun Rail(
|
||||
s: FrontEndState, selected: String,
|
||||
onSelect: (String) -> Unit, a: FrontEndActions, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, a: FrontEndActions, modifier: Modifier, onDismiss: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(
|
||||
@@ -454,7 +522,7 @@ private fun Rail(
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 8.dp, bottom = 10.dp)) {
|
||||
Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(30.dp))
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("DroidDeck", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
val status = when {
|
||||
s.busy -> if (s.percent >= 0) "${s.stage} ${s.percent}%" else s.stage
|
||||
@@ -464,6 +532,9 @@ private fun Rail(
|
||||
}
|
||||
if (status != null) Text(status, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
IconButton(onClick = onDismiss, modifier = Modifier.size(40.dp)) {
|
||||
Icon(Icons.Filled.Close, contentDescription = "Close navigation", tint = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp))
|
||||
@@ -574,7 +645,10 @@ private fun NavItem(
|
||||
val focused by src.collectIsFocusedAsState()
|
||||
val frontFocus = if (register != null && key != "x") LocalFrontFocus.current else null
|
||||
val railRequester = frontFocus?.railFor(key)
|
||||
if (frontFocus != null) LaunchedEffect(focused) { if (focused) frontFocus.railFocused = true }
|
||||
if (frontFocus != null) LaunchedEffect(focused) {
|
||||
if (focused) frontFocus.focusedRail = key
|
||||
else if (frontFocus.focusedRail == key) frontFocus.focusedRail = null
|
||||
}
|
||||
val hovered by src.collectIsHoveredAsState()
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val fg by animateColorAsState(if (current) colors.onPrimary else if (muted) colors.onSurfaceVariant else colors.onBackground, Motion.tw(280), label = "navFg")
|
||||
@@ -713,6 +787,7 @@ private fun Content(
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
|
||||
Column(modifier = modifier.padding(horizontal = 22.dp, vertical = 18.dp)) {
|
||||
when {
|
||||
selected == "android-apps" && s.isHomeApp -> {
|
||||
@@ -745,7 +820,7 @@ private fun Content(
|
||||
}
|
||||
Rise(4) { SectionTitle("Installed", "${s.steamGames.size} game${if (s.steamGames.size == 1) "" else "s"}") }
|
||||
if (s.steamGames.isEmpty()) Rise(5) { Note("No games installed.") }
|
||||
else Rise(5, Modifier.weight(1f).fillMaxWidth()) { ArtGrid(s.steamGames.map { g -> Tile(g.name, g.library, g.art, "steam:${g.appId}", null) { onSelect("app:${g.appId}") } }) }
|
||||
else Rise(5, Modifier.weight(1f).fillMaxWidth()) { ArtGrid(s.steamGames.map { g -> Tile(g.name, g.library, g.art, "steam:${g.appId}", null, showFooter = false) { onSelect("app:${g.appId}") } }) }
|
||||
}
|
||||
selected.startsWith("app:") -> {
|
||||
val g = s.steamGames.firstOrNull { "app:${it.appId}" == selected }
|
||||
@@ -769,13 +844,13 @@ private fun Content(
|
||||
Chip(if (s.ready) "● ready" else "runtime missing", ok = s.ready)
|
||||
}
|
||||
}
|
||||
Poster(g.art, g.name, Modifier.width(120.dp))
|
||||
Poster(g.art, g.name, Modifier.width(detailPosterWidth))
|
||||
}
|
||||
}
|
||||
val others = s.steamGames.filter { it !== g }
|
||||
if (others.isNotEmpty()) {
|
||||
Rise(3) { SectionTitle("More from the library", null) }
|
||||
Rise(4, Modifier.weight(1f).fillMaxWidth()) { ArtGrid(others.map { x -> Tile(x.name, x.library, x.art, "steam:${x.appId}", null) { onSelect("app:${x.appId}") } }) }
|
||||
Rise(4, Modifier.weight(1f).fillMaxWidth()) { ArtGrid(others.map { x -> Tile(x.name, x.library, x.art, "steam:${x.appId}", null, showFooter = false) { onSelect("app:${x.appId}") } }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -891,7 +966,7 @@ private fun Content(
|
||||
Chip(g.hostPath.extension.uppercase().ifEmpty { "folder" }, ok = false)
|
||||
}
|
||||
}
|
||||
if (g.art != null) Poster(g.art, g.name, Modifier.width(120.dp))
|
||||
if (g.art != null) Poster(g.art, g.name, Modifier.width(detailPosterWidth))
|
||||
}
|
||||
}
|
||||
val others = e.games.filter { it !== g }
|
||||
@@ -930,6 +1005,10 @@ private fun SetupPanel(s: FrontEndState, a: FrontEndActions) {
|
||||
ActionRow("Performance", "CPU core assignment", "Configure", a.onPerformance)
|
||||
ActionRow("ROMs folder", s.romsDir ?: "Choose where emulator games are stored", "Choose", a.onRoms)
|
||||
}
|
||||
val controller = s.controller
|
||||
if (controller != null && a.controller != null) SettingsGroup("Controller") {
|
||||
ControllerRows(host, s.oscMode, controller, a.controller)
|
||||
}
|
||||
SettingsGroup("Session") {
|
||||
ChoiceRow(
|
||||
host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted),
|
||||
@@ -990,6 +1069,7 @@ private fun SetupPanel(s: FrontEndState, a: FrontEndActions) {
|
||||
private class Tile(
|
||||
val title: String, val sub: String?, val art: File?, val key: String,
|
||||
val iconRes: Int? = null, val dim: Boolean = false, val iconBitmap: Bitmap? = null,
|
||||
val showFooter: Boolean = true,
|
||||
val onClick: () -> Unit,
|
||||
)
|
||||
|
||||
@@ -1129,7 +1209,7 @@ private fun ArtGrid(tiles: List<Tile>, wide: Boolean = false) {
|
||||
val avail = maxWidth - 8.dp
|
||||
val cols = ((avail + gap) / (minSize + gap)).toInt().coerceAtLeast(1)
|
||||
val tileWidth = (avail - gap * (cols - 1)) / cols
|
||||
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(top = 6.dp, bottom = 14.dp, start = 4.dp, end = 4.dp)) {
|
||||
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(top = 16.dp, bottom = 14.dp, start = 4.dp, end = 4.dp)) {
|
||||
for (row in tiles.chunked(cols)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(gap), modifier = Modifier.fillMaxWidth().padding(bottom = gap)) {
|
||||
for (t in row) key(t.key) {
|
||||
@@ -1175,9 +1255,11 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera
|
||||
) { Text("›", fontSize = if (square) 16.sp else 20.sp, color = Color.White) }
|
||||
}
|
||||
}
|
||||
Column(modifier = Modifier.padding(horizontal = 6.dp, vertical = 5.dp)) {
|
||||
Text(t.title, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (t.sub != null) Text(t.sub, fontSize = 8.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (t.showFooter) {
|
||||
Column(modifier = Modifier.padding(horizontal = 6.dp, vertical = 5.dp)) {
|
||||
Text(t.title, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (t.sub != null) Text(t.sub, fontSize = 8.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -15,6 +21,7 @@ import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.core.FexPreset
|
||||
import com.droiddeck.launcher.runtime.DeckyManager
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
|
||||
@@ -70,6 +77,14 @@ class ModeSettings(
|
||||
val releaseChecking: Boolean = false,
|
||||
/** A bundled display driver was deleted: the page offers to restore it. */
|
||||
val canRestoreBundled: Boolean = false,
|
||||
/** Steam only: Decky Loader is managed from the Steam session settings. */
|
||||
val deckyInstalled: String? = null,
|
||||
val deckyLatestRelease: DeckyManager.Release? = null,
|
||||
val deckyChecking: Boolean = false,
|
||||
val deckyStage: String? = null,
|
||||
val deckyPercent: Int = -1,
|
||||
val deckyEnabled: Boolean = false,
|
||||
val deckySessionRunning: Boolean = false,
|
||||
)
|
||||
|
||||
/** One added game as the settings page shows it: its folder, the chosen .exe, the other .exe files it could be. */
|
||||
@@ -109,6 +124,10 @@ class ModeSettingsActions(
|
||||
val onAddedGamesArt: (Boolean) -> Unit = {},
|
||||
val onAddedGameExe: (folderPath: String, path: String) -> Unit = { _, _ -> },
|
||||
val onPickAddedGameExe: (folderPath: String) -> Unit = {},
|
||||
val onDeckyInstall: (DeckyManager.Release) -> Unit = {},
|
||||
val onDeckyCheck: () -> Unit = {},
|
||||
val onDeckyEnabled: (Boolean) -> Unit = {},
|
||||
val onDeckyUninstall: () -> Unit = {},
|
||||
val onDismiss: () -> Unit,
|
||||
)
|
||||
|
||||
@@ -116,6 +135,7 @@ class ModeSettingsActions(
|
||||
fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
val steam = s.mode == SessionService.MODE_STEAM
|
||||
val host = rememberMenuHost()
|
||||
var confirmDeckyRemoval by remember { mutableStateOf(false) }
|
||||
// The two driver lists open as full pages over this one ("rt" = runtime, "panel" = display).
|
||||
// Coming back restores this page as it was left: the same scroll position, and controller focus
|
||||
// on the driver box that opened the page.
|
||||
@@ -253,6 +273,58 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
onPick = a.onSuspendPolicy,
|
||||
)
|
||||
}
|
||||
if (steam) SettingsGroup("Decky") {
|
||||
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
|
||||
s.deckyInstalled != s.deckyLatestRelease.tag
|
||||
val status = when {
|
||||
s.deckyStage != null -> s.deckyStage
|
||||
s.deckyChecking -> "Checking compatible releases…"
|
||||
s.deckyInstalled == null && s.deckyLatestRelease != null -> "Ready to install ${s.deckyLatestRelease.tag}."
|
||||
s.deckyInstalled == null -> "No compatible build found. Check again later."
|
||||
s.deckyLatestRelease == null -> "Installed · ${s.deckyInstalled}"
|
||||
updateAvailable -> "Update available · ${s.deckyLatestRelease.tag}"
|
||||
else -> "Up to date · ${s.deckyInstalled}"
|
||||
}
|
||||
SettingsRow("Loader", status) {
|
||||
val action = when {
|
||||
s.deckyStage != null -> "Working…"
|
||||
s.deckyChecking -> "Checking…"
|
||||
s.deckyInstalled == null && s.deckyLatestRelease != null -> "Install latest"
|
||||
s.deckyInstalled != null && updateAvailable -> "Update"
|
||||
else -> "Check"
|
||||
}
|
||||
Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) {
|
||||
SecondaryButton(
|
||||
action,
|
||||
enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning,
|
||||
) {
|
||||
if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck()
|
||||
else s.deckyLatestRelease?.let(a.onDeckyInstall)
|
||||
}
|
||||
if (s.deckyInstalled != null) SecondaryButton(
|
||||
"Uninstall",
|
||||
enabled = s.deckyStage == null && !s.deckySessionRunning,
|
||||
) { confirmDeckyRemoval = true }
|
||||
}
|
||||
}
|
||||
if (s.deckyInstalled != null) SettingsRow(
|
||||
"Decky",
|
||||
if (s.deckyEnabled) "Starts with Steam. Other apps on this device may be able to control Steam while enabled."
|
||||
else "Off. Decky stays off and Steam's remote debugging port stays closed.",
|
||||
) {
|
||||
Switch(
|
||||
checked = s.deckyEnabled,
|
||||
onCheckedChange = a.onDeckyEnabled,
|
||||
enabled = !s.deckySessionRunning && s.deckyStage == null,
|
||||
)
|
||||
}
|
||||
if (s.deckyStage != null && s.deckyPercent >= 0) {
|
||||
LinearProgressIndicator(
|
||||
progress = { s.deckyPercent / 100f },
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (steam && s.steamChannel != null) SettingsGroup("Client") {
|
||||
ChoiceRow(
|
||||
host, "channel", "Client branch", "The Steam client build the session forces. Applies at the next session start; the client may update itself once.",
|
||||
@@ -349,6 +421,15 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
|
||||
)
|
||||
}
|
||||
}
|
||||
if (confirmDeckyRemoval) AlertDialog(
|
||||
onDismissRequest = { confirmDeckyRemoval = false },
|
||||
title = { Text("Uninstall Decky Loader?") },
|
||||
text = { Text("Remove the loader and keep your plugins and settings.") },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { confirmDeckyRemoval = false; a.onDeckyUninstall() }) { Text("Uninstall") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { confirmDeckyRemoval = false }) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
|
||||
/** The Resolution menu's "Custom…" entry. */
|
||||
|
||||
@@ -87,7 +87,7 @@ import com.droiddeck.launcher.input.SecondScreenMode
|
||||
import kotlinx.coroutines.flow.collect
|
||||
|
||||
private val drawerPageTitles = listOf("Now", "Controls", "Session")
|
||||
private val drawerPageEntries = listOf("hud", "touch", "shape")
|
||||
private val drawerPageEntries = listOf("hud", "touch", "suspend")
|
||||
|
||||
private class DrawerFocus {
|
||||
private val requesters = HashMap<String, FocusRequester>()
|
||||
@@ -194,6 +194,7 @@ class DrawerActions(
|
||||
val frameGenMultiplier: Int,
|
||||
val lsfgReady: Boolean,
|
||||
val oscMode: String,
|
||||
val suspendPolicy: String,
|
||||
val backActionsInverted: Boolean,
|
||||
val touchMode: String,
|
||||
val touchAuto: String,
|
||||
@@ -212,7 +213,10 @@ class DrawerActions(
|
||||
val onHardwareKeyboard: () -> Unit,
|
||||
val onSteamMenu: (() -> Unit)?,
|
||||
val onQam: (() -> Unit)?,
|
||||
/** Steam sessions: end Big Picture and open the desktop with Steam's desktop client in it. */
|
||||
val onSwitchToDesktop: (() -> Unit)? = null,
|
||||
val onOsc: (String) -> Unit,
|
||||
val onSuspendPolicy: (String) -> Unit,
|
||||
val onBackActionsInverted: (Boolean) -> Unit,
|
||||
val onTouch: (String) -> Unit,
|
||||
val onShape: (String) -> Unit,
|
||||
@@ -222,6 +226,7 @@ class DrawerActions(
|
||||
val onSecondScreenDisplay: (Int) -> Unit,
|
||||
val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit,
|
||||
val onBackground: () -> Unit,
|
||||
val onShareLogs: () -> Unit,
|
||||
val onStop: () -> Unit,
|
||||
val onClose: () -> Unit,
|
||||
)
|
||||
@@ -292,6 +297,11 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(a.title ?: if (a.steam) "Steam" else "Desktop", fontSize = 17.sp, fontWeight = FontWeight.Bold,
|
||||
color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
ShareSessionLogsButton(modifier = focus.track(page, "share-logs")) {
|
||||
host.open = null
|
||||
a.onShareLogs()
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
StopSessionButton(modifier = focus.track(page, "stop")) { host.open = null; confirmStop = true }
|
||||
}
|
||||
if (a.onSteamMenu != null && a.onQam != null) {
|
||||
@@ -344,6 +354,26 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
||||
) {
|
||||
Text("QAM", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
|
||||
}
|
||||
// Big Picture's own "Switch to Desktop" waits on SteamOS Manager for ever
|
||||
// here; this does the switch without the client.
|
||||
if (a.onSwitchToDesktop != null) {
|
||||
val deskSrc = remember { MutableInteractionSource() }
|
||||
val deskHot = deskSrc.collectIsFocusedAsState().value || deskSrc.collectIsHoveredAsState().value
|
||||
OutlinedButton(
|
||||
onClick = { host.open = null; a.onSwitchToDesktop.invoke() },
|
||||
interactionSource = deskSrc,
|
||||
modifier = Modifier.weight(1f).height(48.dp).then(focus.track(page, "desktop"))
|
||||
.semantics { contentDescription = "Switch to Desktop" }.controllerConfirm {
|
||||
host.open = null
|
||||
a.onSwitchToDesktop.invoke()
|
||||
},
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
border = BorderStroke(if (deskHot) 2.dp else 1.dp, if (deskHot) pal.signal else colors.outline),
|
||||
colors = ButtonDefaults.outlinedButtonColors(containerColor = if (deskHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent),
|
||||
) {
|
||||
Text("DESKTOP", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,6 +505,21 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsGroup("Session behavior") {
|
||||
ChoiceRow(
|
||||
host, "suspend", "Background behavior",
|
||||
"Applies now and to future sessions in this mode.",
|
||||
listOf(
|
||||
SessionPrefs.SUSPEND_AUTO to "Auto",
|
||||
SessionPrefs.SUSPEND_MANUAL to "Manual",
|
||||
SessionPrefs.SUSPEND_NEVER to "Never",
|
||||
),
|
||||
a.suspendPolicy,
|
||||
note = "Auto pauses in the background and resumes when visible. Manual pauses there and waits for Resume. Never keeps the session running.",
|
||||
chipModifier = focus.track(page, "suspend"),
|
||||
onPick = a.onSuspendPolicy,
|
||||
)
|
||||
}
|
||||
SettingsGroup("Next session") {
|
||||
ChoiceRow(host, "shape", "Screen ratio", null,
|
||||
SessionPrefs.shapeChoices, a.shapeMode,
|
||||
@@ -571,3 +616,24 @@ private fun StopSessionButton(modifier: Modifier = Modifier, onClick: () -> Unit
|
||||
.controllerConfirm(onClick = onClick),
|
||||
) { Text("×", fontSize = 25.sp, fontWeight = FontWeight.Medium, color = colors.error) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ShareSessionLogsButton(modifier: Modifier = Modifier, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.widthIn(min = 88.dp).height(42.dp)
|
||||
.semantics { contentDescription = "Send current session logs" }
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
|
||||
.border(1.dp, if (hot) pal.signal else colors.outline.copy(alpha = 0.5f), RoundedCornerShape(12.dp))
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick),
|
||||
) {
|
||||
Text("send logs", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = if (hot) pal.signal else colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,17 @@ public final class WaylandCompositor {
|
||||
|
||||
public static native void nativeSendTouch(int action, int pointerId, int x, int y);
|
||||
|
||||
/**
|
||||
* The client's pointer image, straight from wl_pointer.set_cursor (labwc's resize arrows, a text
|
||||
* field's I-beam). out = [serial, hidden, w, h, hotspotX, hotspotY, ARGB8888 pixels...]; returns
|
||||
* the number of ints written, or 0 if {@code out} is too small. Serial 0 = the client has not
|
||||
* set one yet; [1] = 1 means it asked for NO pointer.
|
||||
*/
|
||||
public static native int nativeCursorSnapshot(int[] out);
|
||||
|
||||
/** Enough for the header plus a 256x256 cursor, the largest the compositor snapshots. */
|
||||
public static final int CURSOR_BUF_INTS = 6 + 256 * 256;
|
||||
|
||||
/** Inject a key event. evdev = Linux input keycode (KEY_A=30…); state: 1=down, 0=up. */
|
||||
public static native void nativeSendKey(int evdev, int state);
|
||||
|
||||
|
||||
+148
-63
@@ -27,6 +27,66 @@ if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "Docker is required to cross-compile the glibc ARM64 preload libraries." >&2
|
||||
exit 1
|
||||
fi
|
||||
for tool in curl tar zstd shasum unzip; do
|
||||
if ! command -v "${tool}" >/dev/null 2>&1; then
|
||||
echo "${tool} is required to build the CI-equivalent APK." >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [[ -f "${repo_root}/tools/gamescope/release.env" || -f "${repo_root}/tools/wlroots/release.env" ]] \
|
||||
&& ! command -v gh >/dev/null 2>&1; then
|
||||
echo "GitHub CLI is required to download the pinned Gamescope and wlroots release assets." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ndk_version=${DROIDDECK_NDK_VERSION:-}
|
||||
if [[ -z "${ndk_version}" ]]; then
|
||||
ndk_path=$(find "${sdk_dir}/ndk" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
|
||||
ndk_version=${ndk_path##*/}
|
||||
fi
|
||||
if [[ -z "${ndk_version}" || ! -d "${sdk_dir}/ndk/${ndk_version}" ]]; then
|
||||
echo "No Android NDK found under ${sdk_dir}/ndk; set DROIDDECK_NDK_VERSION." >&2
|
||||
exit 1
|
||||
fi
|
||||
export ANDROID_HOME="${sdk_dir}"
|
||||
export ANDROID_SDK_ROOT="${sdk_dir}"
|
||||
export JAVA_HOME="${java_dir}"
|
||||
export NDK="${sdk_dir}/ndk/${ndk_version}"
|
||||
|
||||
staging_dir=$(mktemp -d "${TMPDIR:-/tmp}/droiddeck-build.XXXXXX")
|
||||
bundle_asset="${repo_root}/app/src/main/assets/pulseaudio.tzst"
|
||||
bundle_backup="${staging_dir}/pulseaudio.original.tzst"
|
||||
bundle_replaced=0
|
||||
linuxfs_dir="${repo_root}/app/src/main/assets/linuxfs"
|
||||
linuxfs_backup="${staging_dir}/linuxfs.original"
|
||||
linuxfs_preexisting=0
|
||||
linuxfs_replaced=0
|
||||
cleanup() {
|
||||
local exit_code=$?
|
||||
trap - EXIT
|
||||
if [[ "${bundle_replaced}" == 1 ]]; then
|
||||
cp -p "${bundle_backup}" "${bundle_asset}" || exit_code=1
|
||||
fi
|
||||
if [[ "${linuxfs_replaced}" == 1 ]]; then
|
||||
rm -rf -- "${linuxfs_dir}" || exit_code=1
|
||||
if [[ "${linuxfs_preexisting}" == 1 ]]; then
|
||||
mv "${linuxfs_backup}" "${linuxfs_dir}" || exit_code=1
|
||||
fi
|
||||
fi
|
||||
rm -rf -- "${staging_dir}" || exit_code=1
|
||||
exit "${exit_code}"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
if [[ -d "${linuxfs_dir}" ]]; then
|
||||
cp -a "${linuxfs_dir}" "${linuxfs_backup}"
|
||||
linuxfs_preexisting=1
|
||||
fi
|
||||
linuxfs_replaced=1
|
||||
rm -rf -- "${linuxfs_dir}"
|
||||
mkdir -p "${linuxfs_dir}"
|
||||
|
||||
if ! docker image inspect "${image_name}" >/dev/null 2>&1; then
|
||||
docker build --platform linux/amd64 -t "${image_name}" \
|
||||
@@ -49,7 +109,12 @@ docker run --rm --platform linux/amd64 \
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
install -Dm644 "$script" "$d/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
|
||||
[ -f "$f" ] && install -Dm644 "$f" "$d/${f#tools/linuxfs/overlay/}"
|
||||
done
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$d/usr/local/bin/droiddeck-desktop"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$d/usr/local/bin/droiddeck-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$d/usr/local/bin/droiddeck-desktop-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/autostart "$d/etc/xdg/labwc/autostart"
|
||||
install -Dm644 tools/linuxfs/desktop/rc.xml "$d/etc/xdg/labwc/rc.xml"
|
||||
install -Dm644 tools/linuxfs/desktop/panel.conf "$d/etc/xdg/lxqt/panel.conf"
|
||||
@@ -82,42 +147,56 @@ docker run --rm --platform linux/amd64 \
|
||||
test -f "$d/usr/local/bin/bannerlator-proton-extra"
|
||||
'
|
||||
|
||||
export ANDROID_HOME="${sdk_dir}"
|
||||
export ANDROID_SDK_ROOT="${sdk_dir}"
|
||||
export JAVA_HOME="${java_dir}"
|
||||
ndk_version=${DROIDDECK_NDK_VERSION:-}
|
||||
if [[ -z "${ndk_version}" ]]; then
|
||||
ndk_path=$(find "${sdk_dir}/ndk" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
|
||||
ndk_version=${ndk_path##*/}
|
||||
fi
|
||||
if [[ -z "${ndk_version}" || ! -d "${sdk_dir}/ndk/${ndk_version}" ]]; then
|
||||
echo "No Android NDK found under ${sdk_dir}/ndk; set DROIDDECK_NDK_VERSION." >&2
|
||||
exit 1
|
||||
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
|
||||
if [[ -z "${github_repo}" ]]; then
|
||||
origin_url=$(git -C "${repo_root}" remote get-url origin)
|
||||
case "${origin_url}" in
|
||||
https://github.com/*) github_repo=${origin_url#https://github.com/} ;;
|
||||
ssh://git@github.com/*) github_repo=${origin_url#ssh://git@github.com/} ;;
|
||||
git@github.com:*) github_repo=${origin_url#git@github.com:} ;;
|
||||
*)
|
||||
echo "Cannot determine the GitHub repository from origin: ${origin_url}" >&2
|
||||
echo "Set DROIDDECK_GITHUB_REPOSITORY=owner/repo." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
github_repo=${github_repo%.git}
|
||||
fi
|
||||
|
||||
for tool in curl tar zstd; do
|
||||
if ! command -v "${tool}" >/dev/null 2>&1; then
|
||||
echo "${tool} is required to build the bundled audio modules." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then
|
||||
. "${repo_root}/tools/gamescope/release.env"
|
||||
gamescope_archive="${staging_dir}/gamescope.tzst"
|
||||
gh release download "${GAMESCOPE_TAG}" -R "${github_repo}" -p gamescope.tzst -O "${gamescope_archive}"
|
||||
printf '%s %s\n' "${GAMESCOPE_SHA256}" "${gamescope_archive}" | shasum -a 256 -c -
|
||||
zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}"
|
||||
test -f "${linuxfs_dir}/usr/local/bin/gamescope"
|
||||
fi
|
||||
|
||||
if [[ -f "${repo_root}/tools/wlroots/release.env" ]]; then
|
||||
. "${repo_root}/tools/wlroots/release.env"
|
||||
wlroots_archive="${staging_dir}/wlroots.tzst"
|
||||
gh release download "${WLROOTS_TAG}" -R "${github_repo}" -p wlroots.tzst -O "${wlroots_archive}"
|
||||
printf '%s %s\n' "${WLROOTS_SHA256}" "${wlroots_archive}" | shasum -a 256 -c -
|
||||
zstd -dc "${wlroots_archive}" | tar -xf - -C "${linuxfs_dir}"
|
||||
test -f "${linuxfs_dir}/usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so"
|
||||
fi
|
||||
|
||||
mango_dir="${linuxfs_dir}/usr/local/lib/mangoapp"
|
||||
mango_pkgs="${staging_dir}/mango-pkgs"
|
||||
mkdir -p "${mango_dir}" "${mango_pkgs}"
|
||||
while read -r package_sha256 package_url; do
|
||||
[[ -n "${package_url}" ]] || continue
|
||||
package_archive="${staging_dir}/$(basename "${package_url}")"
|
||||
curl -fsSL --retry 3 -o "${package_archive}" "${package_url}"
|
||||
printf '%s %s\n' "${package_sha256}" "${package_archive}" | shasum -a 256 -c -
|
||||
zstd -dc "${package_archive}" | tar -xf - -C "${mango_pkgs}"
|
||||
done < <(grep -v '^#' "${repo_root}/tools/mangoapp/packages.txt")
|
||||
install -m644 "${mango_pkgs}/usr/bin/mangoapp" "${mango_dir}/mangoapp"
|
||||
for library in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1 libtracefs.so.1; do
|
||||
cp -L "${mango_pkgs}/usr/lib/${library}" "${mango_dir}/${library}"
|
||||
done
|
||||
|
||||
staging_dir=$(mktemp -d "${TMPDIR:-/tmp}/droiddeck-build.XXXXXX")
|
||||
bundle_asset="${repo_root}/app/src/main/assets/pulseaudio.tzst"
|
||||
bundle_backup="${staging_dir}/pulseaudio.original.tzst"
|
||||
bundle_replaced=0
|
||||
cleanup() {
|
||||
local exit_code=$?
|
||||
trap - EXIT
|
||||
if [[ "${bundle_replaced}" == 1 ]]; then
|
||||
cp -p "${bundle_backup}" "${bundle_asset}" || exit_code=1
|
||||
fi
|
||||
rm -rf -- "${staging_dir}" || exit_code=1
|
||||
exit "${exit_code}"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
mkdir -p "${linuxfs_dir}/usr/local/bin"
|
||||
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
|
||||
|
||||
pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
|
||||
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
|
||||
@@ -132,7 +211,6 @@ if [[ ! -f "${pa_source}/src/pulse/version.h.in" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export NDK="${sdk_dir}/ndk/${ndk_version}"
|
||||
sink_output="${staging_dir}/sink-out"
|
||||
"${repo_root}/tools/aaudio-sink/build.sh" "${pa_source}" "${sink_output}"
|
||||
"${repo_root}/tools/proot/build.sh" "${repo_root}/app/src/main/jniLibs/arm64-v8a"
|
||||
@@ -155,7 +233,7 @@ bundle_replaced=1
|
||||
mv "${staging_dir}/pulseaudio.tzst" "${bundle_asset}"
|
||||
|
||||
cd "${repo_root}"
|
||||
./gradlew assembleRelease -PndkVersion="${ndk_version}"
|
||||
./gradlew assembleRelease --console=plain -PndkVersion="${ndk_version}"
|
||||
cp -p "${bundle_backup}" "${bundle_asset}"
|
||||
bundle_replaced=0
|
||||
|
||||
@@ -173,33 +251,6 @@ for audio_file in \
|
||||
fi
|
||||
done
|
||||
|
||||
build_tools=$(find "${sdk_dir}/build-tools" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
|
||||
if [[ ! -x "${build_tools}/zipalign" || ! -x "${build_tools}/apksigner" ]]; then
|
||||
echo "Android build-tools with zipalign/apksigner are required under ${sdk_dir}/build-tools." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
"${build_tools}/zipalign" -p -f 4 "${apk}" "${staging_dir}/app-release.aligned.apk"
|
||||
"${build_tools}/apksigner" sign \
|
||||
--ks keystore/testkey.p12 --ks-type PKCS12 --ks-pass pass:android \
|
||||
--ks-key-alias testkey --key-pass pass:android \
|
||||
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true \
|
||||
--out "${apk}" "${staging_dir}/app-release.aligned.apk"
|
||||
|
||||
signature_output=$("${build_tools}/apksigner" verify --min-sdk-version 21 --verbose --print-certs "${apk}")
|
||||
printf '%s\n' "${signature_output}"
|
||||
for scheme in \
|
||||
'Verified using v1 scheme (JAR signing): true' \
|
||||
'Verified using v2 scheme (APK Signature Scheme v2): true' \
|
||||
'Verified using v3 scheme (APK Signature Scheme v3): true'; do
|
||||
grep -qF "${scheme}" <<<"${signature_output}" || {
|
||||
echo "APK signature check failed: ${scheme}" >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
grep -qF 'Signer #1 certificate DN: EMAILADDRESS=android@android.com, CN=Android, OU=Android, O=Android' \
|
||||
<<<"${signature_output}"
|
||||
|
||||
docker run --rm --platform linux/amd64 -v "${repo_root}:/src:ro" -w /src "${image_name}" \
|
||||
bash -lc '
|
||||
set -euo pipefail
|
||||
@@ -207,7 +258,7 @@ docker run --rm --platform linux/amd64 -v "${repo_root}:/src:ro" -w /src "${imag
|
||||
work=$(mktemp -d)
|
||||
unzip -q "$apk" "lib/arm64-v8a/*" -d "$work"
|
||||
cd "$work/lib/arm64-v8a"
|
||||
system="libc.so libm.so libdl.so liblog.so libandroid.so libz.so libvulkan.so
|
||||
system="libc.so libm.so libdl.so liblog.so libandroid.so libz.so libvulkan.so libstdc++.so
|
||||
libGLESv2.so libEGL.so libnativewindow.so libjnigraphics.so libaaudio.so
|
||||
libOpenSLES.so libmediandk.so libcamera2ndk.so libsync.so libneuralnetworks.so"
|
||||
fail=0
|
||||
@@ -223,6 +274,40 @@ docker run --rm --platform linux/amd64 -v "${repo_root}:/src:ro" -w /src "${imag
|
||||
echo "every NEEDED resolves"
|
||||
'
|
||||
|
||||
build_tools=$(find "${sdk_dir}/build-tools" -mindepth 1 -maxdepth 1 -type d -print | sort -V | tail -1)
|
||||
if [[ ! -x "${build_tools}/zipalign" || ! -x "${build_tools}/apksigner" ]]; then
|
||||
echo "Android build-tools with zipalign/apksigner are required under ${sdk_dir}/build-tools." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
"${build_tools}/zipalign" -p -f 4 "${apk}" "${apk}.aligned"
|
||||
"${build_tools}/apksigner" sign \
|
||||
--ks "${repo_root}/keystore/testkey.p12" --ks-type PKCS12 --ks-pass pass:android \
|
||||
--ks-key-alias testkey --key-pass pass:android \
|
||||
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true \
|
||||
--out "${apk}" "${apk}.aligned"
|
||||
rm -f "${apk}.aligned" "${apk}.idsig"
|
||||
|
||||
signature_output=$("${build_tools}/apksigner" verify --min-sdk-version 21 --verbose --print-certs "${apk}")
|
||||
printf '%s\n' "${signature_output}"
|
||||
if ! unzip -l "${apk}" | grep -qE 'META-INF/.*\.(SF|RSA|DSA)$'; then
|
||||
echo "APK signature check failed: JAR signature files are missing." >&2
|
||||
exit 1
|
||||
fi
|
||||
for scheme in \
|
||||
'Verified using v1 scheme (JAR signing): true' \
|
||||
'Verified using v2 scheme (APK Signature Scheme v2): true' \
|
||||
'Verified using v3 scheme (APK Signature Scheme v3): true'; do
|
||||
grep -qF "${scheme}" <<<"${signature_output}" || {
|
||||
echo "APK signature check failed: ${scheme}" >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
grep -qi 'CN=Android, OU=Android, O=Android' <<<"${signature_output}" || {
|
||||
echo "APK signature check failed: the signer is not the AOSP testkey." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
printf 'APK: %s\n' "${apk}"
|
||||
printf 'SHA-256: '
|
||||
shasum -a 256 "${apk}" | awk '{print $1}'
|
||||
@@ -16,6 +16,17 @@ library list, before anything is published.
|
||||
3.16.29: realtime-priority Vulkan queues on request (`GAMESCOPE_FORCE_VULKAN_REALTIME=1`)
|
||||
without CAP_SYS_NICE, which proot can never have; and the gamepad-driven cursor sprite following
|
||||
the X pointer that XTest moves (it sat frozen).
|
||||
- `0110-wayland-backend-touch.patch` - this app: the nested Wayland backend bound only the host's
|
||||
pointer and keyboard, so a finger on the phone's screen never reached Steam. It now binds
|
||||
`wl_touch` too and hands each finger to wlserver's touch path (`wlserver_touchdown` / `motion` /
|
||||
`up`) - the one a Steam Deck's touchscreen drives - so what a touch does follows the client's
|
||||
touch mode (Steam's Big Picture sets Passthrough: a real touch, rows scroll under a finger).
|
||||
Finger ids are offset by one, since the nested pointer already moves wlserver's touch 0.
|
||||
- `0111-wayland-pointer-warps-in-passthrough.patch` - this app: the nested pointer's motion goes to
|
||||
wlserver as touch 0, and in Passthrough (Big Picture's touch mode) a motion for a touch that is not
|
||||
down moves nothing - so in the app's touchpad mode the Steam client saw no hover and a click landed
|
||||
wherever the pointer had last been. The motion now always warps the real pointer as well
|
||||
(`bAlwaysWarpCursor`), which the other touch modes did already.
|
||||
|
||||
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
|
||||
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
|
||||
@@ -0,0 +1,121 @@
|
||||
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
|
||||
index d74268b..bf72267 100644
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -601,6 +601,17 @@ namespace gamescope
|
||||
void Wayland_Keyboard_RepeatInfo( wl_keyboard *pKeyboard, int32_t nRate, int32_t nDelay );
|
||||
static const wl_keyboard_listener s_KeyboardListener;
|
||||
|
||||
+ // Touch from the host compositor (DroidDeck): each finger goes to wlserver's touch path,
|
||||
+ // the one a Steam Deck's touchscreen drives, instead of being dropped.
|
||||
+ void Wayland_Touch_Down( wl_touch *pTouch, uint32_t uSerial, uint32_t uTime, wl_surface *pSurface, int32_t nId, wl_fixed_t fX, wl_fixed_t fY );
|
||||
+ void Wayland_Touch_Up( wl_touch *pTouch, uint32_t uSerial, uint32_t uTime, int32_t nId );
|
||||
+ void Wayland_Touch_Motion( wl_touch *pTouch, uint32_t uTime, int32_t nId, wl_fixed_t fX, wl_fixed_t fY );
|
||||
+ void Wayland_Touch_Frame( wl_touch *pTouch );
|
||||
+ void Wayland_Touch_Cancel( wl_touch *pTouch );
|
||||
+ static const wl_touch_listener s_TouchListener;
|
||||
+ bool TouchToOutput( wl_surface *pSurface, wl_fixed_t fX, wl_fixed_t fY, double *pflX, double *pflY );
|
||||
+ std::unordered_map<int32_t, wl_surface *> m_TouchSurfaces;
|
||||
+
|
||||
void Wayland_RelativePointer_RelativeMotion( zwp_relative_pointer_v1 *pRelativePointer, uint32_t uTimeHi, uint32_t uTimeLo, wl_fixed_t fDx, wl_fixed_t fDy, wl_fixed_t fDxUnaccel, wl_fixed_t fDyUnaccel );
|
||||
static const zwp_relative_pointer_v1_listener s_RelativePointerListener;
|
||||
};
|
||||
@@ -636,6 +647,16 @@ namespace gamescope
|
||||
.modifiers = WAYLAND_USERDATA_TO_THIS( CWaylandInputThread, Wayland_Keyboard_Modifiers ),
|
||||
.repeat_info = WAYLAND_USERDATA_TO_THIS( CWaylandInputThread, Wayland_Keyboard_RepeatInfo ),
|
||||
};
|
||||
+ const wl_touch_listener CWaylandInputThread::s_TouchListener =
|
||||
+ {
|
||||
+ .down = WAYLAND_USERDATA_TO_THIS( CWaylandInputThread, Wayland_Touch_Down ),
|
||||
+ .up = WAYLAND_USERDATA_TO_THIS( CWaylandInputThread, Wayland_Touch_Up ),
|
||||
+ .motion = WAYLAND_USERDATA_TO_THIS( CWaylandInputThread, Wayland_Touch_Motion ),
|
||||
+ .frame = WAYLAND_USERDATA_TO_THIS( CWaylandInputThread, Wayland_Touch_Frame ),
|
||||
+ .cancel = WAYLAND_USERDATA_TO_THIS( CWaylandInputThread, Wayland_Touch_Cancel ),
|
||||
+ .shape = WAYLAND_NULL(),
|
||||
+ .orientation = WAYLAND_NULL(),
|
||||
+ };
|
||||
const zwp_relative_pointer_v1_listener CWaylandInputThread::s_RelativePointerListener =
|
||||
{
|
||||
.relative_motion = WAYLAND_USERDATA_TO_THIS( CWaylandInputThread, Wayland_RelativePointer_RelativeMotion ),
|
||||
@@ -3067,6 +3088,81 @@ namespace gamescope
|
||||
wl_keyboard_add_listener( m_pKeyboard, &s_KeyboardListener, this );
|
||||
}
|
||||
}
|
||||
+
|
||||
+ if ( !!( uCapabilities & WL_SEAT_CAPABILITY_TOUCH ) != !!m_pTouch )
|
||||
+ {
|
||||
+ if ( m_pTouch )
|
||||
+ {
|
||||
+ wl_touch_release( m_pTouch );
|
||||
+ m_pTouch = nullptr;
|
||||
+ m_TouchSurfaces.clear();
|
||||
+ }
|
||||
+ else
|
||||
+ {
|
||||
+ m_pTouch = wl_seat_get_touch( m_pSeat );
|
||||
+ wl_touch_add_listener( m_pTouch, &s_TouchListener, this );
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ // Touch
|
||||
+
|
||||
+ bool CWaylandInputThread::TouchToOutput( wl_surface *pSurface, wl_fixed_t fX, wl_fixed_t fY, double *pflX, double *pflY )
|
||||
+ {
|
||||
+ if ( !pSurface || !IsGamescopeToplevel( pSurface ) )
|
||||
+ return false;
|
||||
+ CWaylandPlane *pPlane = (CWaylandPlane *)wl_surface_get_user_data( pSurface );
|
||||
+ if ( !pPlane )
|
||||
+ return false;
|
||||
+ auto oState = pPlane->GetCurrentState();
|
||||
+ if ( !oState || !g_nOutputWidth || !g_nOutputHeight )
|
||||
+ return false;
|
||||
+ uint32_t uScale = oState->uFractionalScale;
|
||||
+ *pflX = ( wl_fixed_to_double( fX ) * uScale / 120.0 + oState->nDestX ) / g_nOutputWidth;
|
||||
+ *pflY = ( wl_fixed_to_double( fY ) * uScale / 120.0 + oState->nDestY ) / g_nOutputHeight;
|
||||
+ return true;
|
||||
+ }
|
||||
+ // Touch ids are offset by one: the nested pointer already moves wlserver's touch 0.
|
||||
+ void CWaylandInputThread::Wayland_Touch_Down( wl_touch *pTouch, uint32_t uSerial, uint32_t uTime, wl_surface *pSurface, int32_t nId, wl_fixed_t fX, wl_fixed_t fY )
|
||||
+ {
|
||||
+ double flX, flY;
|
||||
+ if ( !TouchToOutput( pSurface, fX, fY, &flX, &flY ) )
|
||||
+ return;
|
||||
+ m_TouchSurfaces[ nId ] = pSurface;
|
||||
+ wlserver_lock();
|
||||
+ wlserver_touchdown( flX, flY, nId + 1, ++m_uFakeTimestamp );
|
||||
+ wlserver_unlock();
|
||||
+ }
|
||||
+ void CWaylandInputThread::Wayland_Touch_Up( wl_touch *pTouch, uint32_t uSerial, uint32_t uTime, int32_t nId )
|
||||
+ {
|
||||
+ if ( m_TouchSurfaces.erase( nId ) == 0 )
|
||||
+ return;
|
||||
+ wlserver_lock();
|
||||
+ wlserver_touchup( nId + 1, ++m_uFakeTimestamp );
|
||||
+ wlserver_unlock();
|
||||
+ }
|
||||
+ void CWaylandInputThread::Wayland_Touch_Motion( wl_touch *pTouch, uint32_t uTime, int32_t nId, wl_fixed_t fX, wl_fixed_t fY )
|
||||
+ {
|
||||
+ auto it = m_TouchSurfaces.find( nId );
|
||||
+ if ( it == m_TouchSurfaces.end() )
|
||||
+ return;
|
||||
+ double flX, flY;
|
||||
+ if ( !TouchToOutput( it->second, fX, fY, &flX, &flY ) )
|
||||
+ return;
|
||||
+ wlserver_lock();
|
||||
+ wlserver_touchmotion( flX, flY, nId + 1, ++m_uFakeTimestamp );
|
||||
+ wlserver_unlock();
|
||||
+ }
|
||||
+ void CWaylandInputThread::Wayland_Touch_Frame( wl_touch *pTouch )
|
||||
+ {
|
||||
+ }
|
||||
+ void CWaylandInputThread::Wayland_Touch_Cancel( wl_touch *pTouch )
|
||||
+ {
|
||||
+ wlserver_lock();
|
||||
+ for ( auto &[ nId, pSurface ] : m_TouchSurfaces )
|
||||
+ wlserver_touchup( nId + 1, ++m_uFakeTimestamp );
|
||||
+ wlserver_unlock();
|
||||
+ m_TouchSurfaces.clear();
|
||||
}
|
||||
|
||||
void CWaylandInputThread::Wayland_Seat_Name( wl_seat *pSeat, const char *pName )
|
||||
@@ -0,0 +1,16 @@
|
||||
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
|
||||
index bf72267..c400978 100644
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -3223,7 +3223,10 @@ namespace gamescope
|
||||
double flY = ( wl_fixed_to_double( fSurfaceY ) * uScale / 120.0 + oState->nDestY ) / g_nOutputHeight;
|
||||
|
||||
wlserver_lock();
|
||||
- wlserver_touchmotion( flX, flY, 0, ++m_uFakeTimestamp );
|
||||
+ // Always move the real pointer too: in Passthrough (what Steam's Big Picture asks for) a
|
||||
+ // touch motion for an id that is not down moves nothing, so hover never reached the
|
||||
+ // client and a click landed wherever the pointer had last been.
|
||||
+ wlserver_touchmotion( flX, flY, 0, ++m_uFakeTimestamp, true );
|
||||
wlserver_unlock();
|
||||
}
|
||||
void CWaylandInputThread::Wayland_Pointer_Button( wl_pointer *pPointer, uint32_t uSerial, uint32_t uTime, uint32_t uButton, uint32_t uState )
|
||||
@@ -1,2 +1,2 @@
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p1
|
||||
GAMESCOPE_SHA256=522d1835d84e4a64a843e095bbe341f68b10f8467f38c0e72ae4ef20b675b873
|
||||
GAMESCOPE_TAG=gamescope-3.16.29-p3
|
||||
GAMESCOPE_SHA256=566e3b93931f37c30375d440d15ee76452892b842d2dc854cd3c06b926c8451b
|
||||
@@ -36,6 +36,10 @@ swaybg -m fill -i /usr/share/backgrounds/steamdeck.png &
|
||||
run pcmanfm-qt pcmanfm-qt --desktop --profile lxqt
|
||||
run lxqt-panel lxqt-panel
|
||||
/usr/lib/xdg-desktop-portal-wlr >/dev/null 2>&1 &
|
||||
# The desktop was asked for with Steam in it (the front end's "Steam Desktop UI", Big Picture's
|
||||
# "Switch to Desktop"): the client's desktop UI, as the menu's Steam entry opens it. A running
|
||||
# client just gets the request; on a software desktop it goes back to the app as a Steam session.
|
||||
[ "${BL_DESKTOP_STEAM:-0}" = 1 ] && run steam /usr/local/bin/bannerlator-steam-launch desktop
|
||||
# Remote runs, for driving the desktop from a debugger: with ~/.droiddeck-remote-run present (only
|
||||
# the app or root can create it), each script dropped into ~/.cache/droiddeck/run/ is run once,
|
||||
# inside the session with its environment, its output tagged into the desktop log.
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
# installed desktop without re-downloading the package.
|
||||
set -u
|
||||
export XDG_SESSION_TYPE=wayland XDG_CURRENT_DESKTOP=LXQt XDG_SESSION_DESKTOP=lxqt
|
||||
export QT_QPA_PLATFORM=wayland GDK_BACKEND=wayland,x11 SDL_VIDEODRIVER=wayland,x11
|
||||
# Qt tries Wayland and falls back to X11 (Xwayland): an AppImage that bundles only Qt's xcb
|
||||
# plugin - melonDS - exits at once on a plain "wayland" ("Could not find the Qt platform plugin").
|
||||
export QT_QPA_PLATFORM="wayland;xcb" GDK_BACKEND=wayland,x11 SDL_VIDEODRIVER=wayland,x11
|
||||
export QT_QPA_PLATFORMTHEME=lxqt
|
||||
# Firefox's child processes sandbox themselves with seccomp and namespaces, neither of which
|
||||
# behaves under proot: the content process ends up unable to read the font files its parent can,
|
||||
|
||||
@@ -19,4 +19,13 @@
|
||||
<keybind key="W-d"><action name="ToggleMaximize"/></keybind>
|
||||
</keyboard>
|
||||
<mouse><doubleClickTime>500</doubleClickTime></mouse>
|
||||
<!-- Programs opened on the desktop at a size that suits it. melonDS remembers a 1x window for the
|
||||
front end's full-screen toggle (bannerlator-pad-defaults), too small for a desktop: here it
|
||||
opens at 800x600, centred (AutoPlace alone kept the top-left corner). Only the desktop reads this file, so the front end is unaffected. -->
|
||||
<windowRules>
|
||||
<windowRule title="melonDS*">
|
||||
<action name="ResizeTo" width="800" height="600"/>
|
||||
<action name="AutoPlace" policy="center"/>
|
||||
</windowRule>
|
||||
</windowRules>
|
||||
</labwc_config>
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
# The SteamOS session switch. Big Picture's power menu runs it for "Switch to Desktop" (a Plasma
|
||||
# session: "plasma", "plasma-wayland-persistent", ...) and waits for Game Mode to end; with nothing
|
||||
# here it sat on "Switching to Desktop..." for ever. Here the desktop is DroidDeck's own: the app is
|
||||
# asked for a desktop session with Steam's desktop client open in it (the request file
|
||||
# bannerlator-steam-launch uses; the app ends this session and starts that one). Anything else -
|
||||
# "gamescope", the session Game Mode already is - has nothing to do.
|
||||
echo "steamos-session-select: $*" >&2
|
||||
case "${1:-}" in
|
||||
""|gamescope) exit 0 ;;
|
||||
esac
|
||||
dir=${BL_LAUNCH_DIR:-}
|
||||
if [ -z "$dir" ] || [ ! -d "$dir" ]; then
|
||||
echo "steamos-session-select: not inside a DroidDeck session (BL_LAUNCH_DIR unset)" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf 'session=desktop\nui=desktop\nurl=\n' > "$dir/steam-launch.tmp" && mv -f "$dir/steam-launch.tmp" "$dir/steam-launch"
|
||||
exit 0
|
||||
@@ -723,8 +723,11 @@ def cemu():
|
||||
|
||||
# melonDS 1.x: raw SDL joystick indices. The session's pad has the kernel's Xbox 360 layout
|
||||
# (buttons A B X Y LB RB Back Start Guide LS RS = 0..10, hat 0 for the d-pad); the d-pad values
|
||||
# also take the left stick (EmuInstanceInput.cpp; encoding InputConfig/MapButton.h).
|
||||
MELONDS_JOY = """[Instance0.Joystick]
|
||||
# also take the left stick (EmuInstanceInput.cpp; encoding InputConfig/MapButton.h). The guide
|
||||
# button toggles full screen (HK_FullscreenToggle), as it does in Dolphin: the front end starts
|
||||
# melonDS full screen (-f), and leaving it shows the window's menus for settings.
|
||||
MELONDS_GUIDE = 8
|
||||
MELONDS_JOY = f"""[Instance0.Joystick]
|
||||
A = 1
|
||||
B = 0
|
||||
X = 3
|
||||
@@ -737,14 +740,152 @@ Up = 17891585
|
||||
Down = 16843012
|
||||
Left = 1114376
|
||||
Right = 65794
|
||||
HK_FullscreenToggle = {MELONDS_GUIDE}
|
||||
"""
|
||||
|
||||
# The screen a handheld's wide panel suits best: the top screen as big as the panel's height allows
|
||||
# with the bottom screen alone beside it, centred (ScreenLayout.h: Horizontal = 2, EmphTop = 1;
|
||||
# melonDS's Hybrid shows the big screen a second time, small, above the bottom one; nobody needs
|
||||
# it twice). Sharp pixels: no filtering, and no integer steps that leave the panel half used. Keys as
|
||||
# melonDS writes them (Window.cpp windowCfg).
|
||||
MELONDS_WINDOW = """[Instance0.Window0]
|
||||
ScreenLayout = 2
|
||||
ScreenSizing = 1
|
||||
IntegerScaling = false
|
||||
ScreenFilter = false
|
||||
"""
|
||||
# melonDS's own defaults for those, which an existing install is moved off once. Hybrid (3) was
|
||||
# this preset's first layout, and moves on too.
|
||||
MELONDS_WINDOW_DEFAULTS = {"ScreenLayout": ("0", "3"), "ScreenSizing": ("0",), "ScreenFilter": ("true",)}
|
||||
|
||||
|
||||
# The window melonDS returns to when the guide button leaves full screen: 1x wide (the width of
|
||||
# two DS screens side by side, Screen.cpp screenGetMinSize) and 16:9, so gamescope stretches it to
|
||||
# fill the panel and the menu bar and cursor come out large enough to use. A bigger window keeps
|
||||
# its menus at their real size, tiny on a handheld. Qt's saveGeometry() v3 blob: magic, version,
|
||||
# frame and normal rects (x, y, right, bottom), screen, maximized, full screen, screen width, and
|
||||
# the normal rect again (QWidget::restoreGeometry).
|
||||
def melonds_geometry():
|
||||
import base64, struct
|
||||
w, h = 512, 288
|
||||
try:
|
||||
screen_w = int(os.environ.get("BL_WIDTH", "1920"))
|
||||
except ValueError:
|
||||
screen_w = 1920
|
||||
rect = (0, 0, w - 1, h - 1)
|
||||
blob = struct.pack(">IHH4i4iiBBi4i", 0x1D9D0CB, 3, 0, *rect, *rect, 0, 0, 0, screen_w, *rect)
|
||||
return base64.b64encode(blob).decode()
|
||||
|
||||
|
||||
def toml_get(lines, table, key):
|
||||
"""The raw value of key in [table], or None."""
|
||||
inside = False
|
||||
for l in lines:
|
||||
t = l.strip()
|
||||
if t.startswith("["):
|
||||
inside = t == f"[{table}]"
|
||||
elif inside and "=" in t and t.split("=", 1)[0].strip() == key:
|
||||
return t.split("=", 1)[1].strip()
|
||||
return None
|
||||
|
||||
|
||||
def toml_set(lines, table, key, value):
|
||||
"""key = value in [table]; the table is added at the end when missing."""
|
||||
start = None
|
||||
for i, l in enumerate(lines):
|
||||
t = l.strip()
|
||||
if t.startswith("["):
|
||||
if start is not None:
|
||||
break
|
||||
if t == f"[{table}]":
|
||||
start = i
|
||||
elif start is not None and "=" in t and t.split("=", 1)[0].strip() == key:
|
||||
lines[i] = f"{key} = {value}"
|
||||
return
|
||||
if start is None:
|
||||
lines += ["", f"[{table}]", f"{key} = {value}"]
|
||||
return
|
||||
end = start + 1
|
||||
while end < len(lines) and not lines[end].strip().startswith("["):
|
||||
end += 1
|
||||
while end > start + 1 and not lines[end - 1].strip():
|
||||
end -= 1
|
||||
lines.insert(end, f"{key} = {value}")
|
||||
|
||||
|
||||
def toml_str(path):
|
||||
return '"' + path.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
||||
|
||||
|
||||
# The user's own BIOS, firmware and DSi NAND, found in the ROMs folder's nds/bios (or firmware)
|
||||
# folder by what each file is: the DS BIOSes by size and checksum (the GBA BIOS is also 16 KB),
|
||||
# firmware and NAND by size, the DSi boot ROMs (both 64 KB) by the 7 or 9 in their names. A path
|
||||
# is only filled where melonDS has none, and external files are only switched on when a whole set
|
||||
# was found - without them melonDS runs DS games on its built-in free BIOS.
|
||||
DS_BIOS7_MD5 = "df692a80a5b1bc90728bc3dfc76cd948"
|
||||
DS_BIOS9_MD5 = "a392174eb3e572fed6447e956bde4b25"
|
||||
|
||||
|
||||
def nds_firmware_files():
|
||||
import hashlib
|
||||
base = system_folder(("nds", "ds"), "nds")
|
||||
roots = [os.path.join(base, n) for n in ("bios", "BIOS", "firmware") if os.path.isdir(os.path.join(base, n))]
|
||||
found = {}
|
||||
for root in roots:
|
||||
for d, _, files in os.walk(root):
|
||||
if d[len(root):].count(os.sep) > 2:
|
||||
continue
|
||||
for name in sorted(files):
|
||||
f = os.path.join(d, name)
|
||||
try:
|
||||
size = os.path.getsize(f)
|
||||
except OSError:
|
||||
continue
|
||||
low = name.lower()
|
||||
if size == 16384 or size == 4096:
|
||||
with open(f, "rb") as h:
|
||||
md5 = hashlib.md5(h.read()).hexdigest()
|
||||
if md5 == DS_BIOS7_MD5:
|
||||
found.setdefault("DS.BIOS7Path", f)
|
||||
elif md5 == DS_BIOS9_MD5:
|
||||
found.setdefault("DS.BIOS9Path", f)
|
||||
elif size in (262144, 524288) and "dsi" not in low:
|
||||
found.setdefault("DS.FirmwarePath", f)
|
||||
elif size == 65536:
|
||||
if "arm7" in low or "bios7" in low:
|
||||
found.setdefault("DSi.BIOS7Path", f)
|
||||
elif "arm9" in low or "bios9" in low:
|
||||
found.setdefault("DSi.BIOS9Path", f)
|
||||
elif size == 131072:
|
||||
found.setdefault("DSi.FirmwarePath", f)
|
||||
elif size >= 200 * 1024 * 1024 and "nand" in low:
|
||||
found.setdefault("DSi.NANDPath", f)
|
||||
return found
|
||||
|
||||
|
||||
def melonds_bios(lines):
|
||||
found = nds_firmware_files()
|
||||
changed = []
|
||||
for key, f in found.items():
|
||||
table, k = key.split(".", 1)
|
||||
if (toml_get(lines, table, k) or '""') == '""':
|
||||
toml_set(lines, table, k, toml_str(f))
|
||||
changed.append(key)
|
||||
for table, flag, keys in (("Emu", "ExternalBIOSEnable", ("DS.BIOS7Path", "DS.BIOS9Path", "DS.FirmwarePath")),
|
||||
("DSi", "ExternalBIOSEnable", ("DSi.BIOS7Path", "DSi.BIOS9Path", "DSi.FirmwarePath", "DSi.NANDPath"))):
|
||||
if all(k in found for k in keys) and any(k in changed for k in keys):
|
||||
toml_set(lines, table, flag, "true")
|
||||
return changed
|
||||
|
||||
|
||||
def melonds():
|
||||
path = os.path.join(CONFIG, "melonDS/melonDS.toml")
|
||||
marker = os.path.join(os.path.dirname(path), ".droiddeck-display-2")
|
||||
if not os.path.isfile(path):
|
||||
seed(path, "[Instance0]\nJoystickID = 0\n\n" + MELONDS_JOY, "melonDS")
|
||||
return
|
||||
seed(path, "[Instance0]\nJoystickID = 0\n\n" + MELONDS_JOY + "\n" + MELONDS_WINDOW +
|
||||
f'Geometry = "{melonds_geometry()}"\n', "melonDS",
|
||||
"Player 1 on the controller, big top screen")
|
||||
open(marker, "w").close()
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
text = f.read()
|
||||
try:
|
||||
@@ -752,20 +893,40 @@ def melonds():
|
||||
joy = tomllib.loads(text).get("Instance0", {}).get("Joystick", {})
|
||||
except Exception:
|
||||
return
|
||||
if any(isinstance(v, int) and v != -1 for v in joy.values()):
|
||||
return # something is bound already
|
||||
# Replace melonDS's own all-unbound table with ours (a TOML table can be defined only once).
|
||||
out, skipping = [], False
|
||||
for line in text.splitlines():
|
||||
t = line.strip()
|
||||
if t.startswith("["):
|
||||
skipping = t == "[Instance0.Joystick]"
|
||||
if not skipping:
|
||||
out.append(line)
|
||||
with open(path + ".tmp", "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(out).rstrip("\n") + "\n\n" + MELONDS_JOY)
|
||||
os.replace(path + ".tmp", path)
|
||||
print(f"bannerlator-pad-defaults: melonDS: Player 1 on the controller ({path})")
|
||||
lines = text.splitlines()
|
||||
done = []
|
||||
if not any(isinstance(v, int) and v != -1 and k != "HK_FullscreenToggle" for k, v in joy.items()):
|
||||
# Replace melonDS's own all-unbound table with ours (a TOML table can be defined only once).
|
||||
out, skipping = [], False
|
||||
for line in lines:
|
||||
t = line.strip()
|
||||
if t.startswith("["):
|
||||
skipping = t == "[Instance0.Joystick]"
|
||||
if not skipping:
|
||||
out.append(line)
|
||||
lines = "\n".join(out).rstrip("\n").splitlines() + [""] + MELONDS_JOY.rstrip("\n").splitlines()
|
||||
done.append("Player 1 on the controller")
|
||||
elif joy.get("HK_FullscreenToggle", -1) == -1 and MELONDS_GUIDE not in joy.values():
|
||||
toml_set(lines, "Instance0.Joystick", "HK_FullscreenToggle", str(MELONDS_GUIDE))
|
||||
done.append("guide button toggles full screen")
|
||||
# Once, for a melonDS set up before this: the big top screen, where it is still on its own
|
||||
# defaults. The marker keeps whatever the user picks in melonDS's View menu afterwards.
|
||||
if not os.path.exists(marker):
|
||||
for l in MELONDS_WINDOW.splitlines()[1:]:
|
||||
k, v = (x.strip() for x in l.split("=", 1))
|
||||
if toml_get(lines, "Instance0.Window0", k) in (None,) + MELONDS_WINDOW_DEFAULTS.get(k, ()):
|
||||
toml_set(lines, "Instance0.Window0", k, v)
|
||||
toml_set(lines, "Instance0.Window0", "Geometry", f'"{melonds_geometry()}"')
|
||||
done.append("big top screen, 1x window")
|
||||
open(marker, "w").close()
|
||||
bios = melonds_bios(lines)
|
||||
if bios:
|
||||
done.append("BIOS " + ", ".join(bios))
|
||||
if done:
|
||||
with open(path + ".tmp", "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines).rstrip("\n") + "\n")
|
||||
os.replace(path + ".tmp", path)
|
||||
print(f"bannerlator-pad-defaults: melonDS: {'; '.join(done)} ({path})")
|
||||
|
||||
|
||||
# PPSSPP (SDL): its pad defaults leave the shoulders, the right stick and the triggers unbound on
|
||||
|
||||
@@ -440,6 +440,42 @@ BUSCONF
|
||||
# falls through to the host, and the guest shell dies on libreadline before the game is reached.
|
||||
# FEX_ROOTFS names it outright and is read whatever the config situation.
|
||||
[ -d /usr/share/guestos/fex-mesa ] && export FEX_ROOTFS=/usr/share/guestos/fex-mesa
|
||||
# Decky is optional and session scoped: the app's marker opts in, and this supervisor is
|
||||
# reaped with the client session. Native ARM64 runs directly. A legacy x86_64 asset is used
|
||||
# only when its recorded architecture and this guest's existing FEX installation agree.
|
||||
decky_loader=$HOME/homebrew/services/PluginLoader
|
||||
if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then
|
||||
decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown)
|
||||
if [ "$decky_arch" = arm64 ] || { [ "$decky_arch" = x86_64 ] && [ -x /usr/bin/FEX ] && [ -n "${FEX_ROOTFS:-}" ]; }; then
|
||||
(
|
||||
decky_child=
|
||||
decky_stop() { [ -z "$decky_child" ] || kill "$decky_child" 2>/dev/null; [ -z "$decky_child" ] || wait "$decky_child" 2>/dev/null; exit 0; }
|
||||
trap decky_stop TERM INT HUP
|
||||
decky_exits=0
|
||||
while :; do
|
||||
if [ "$decky_arch" = x86_64 ]; then /usr/bin/FEX "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 &
|
||||
else "$decky_loader" >>"$HOME/homebrew/services/PluginLoader.log" 2>&1 &
|
||||
fi
|
||||
decky_child=$!
|
||||
decky_status=0
|
||||
wait "$decky_child" || decky_status=$?
|
||||
decky_child=
|
||||
decky_exits=$((decky_exits + 1))
|
||||
if [ "$decky_exits" -ge 5 ]; then
|
||||
echo "== Decky: stopped after $decky_exits loader exits (last status $decky_status)"
|
||||
break
|
||||
fi
|
||||
decky_delay=$((decky_exits * 3))
|
||||
echo "== Decky: loader exited with status $decky_status; restart $((decky_exits + 1))/5 in ${decky_delay}s"
|
||||
sleep "$decky_delay"
|
||||
done
|
||||
) &
|
||||
decky_supervisor=$!
|
||||
echo "== Decky: session supervisor started ($decky_arch)"
|
||||
else
|
||||
echo "== Decky: installed loader architecture is unsupported by this guest; not starting"
|
||||
fi
|
||||
fi
|
||||
# The client exits 42 when it has updated itself and wants a fresh start (steam.sh does this).
|
||||
# BL_STEAM_UI=desktop = the client's desktop UI (a window, the library as a list), which the
|
||||
# desktop's launchers ask for; gamescope shows one window at a time and the game takes over.
|
||||
@@ -521,10 +557,20 @@ BUSCONF
|
||||
# script's parent, so reap_orphans - right under gamescope, where everything is the client's -
|
||||
# is not for here. The helpers this run started (the cores and redistributables beats, the
|
||||
# system bus and the NetworkManager stand-in) go with the client instead.
|
||||
if [ -n "${decky_supervisor:-}" ]; then
|
||||
kill "$decky_supervisor" 2>/dev/null || true
|
||||
wait "$decky_supervisor" 2>/dev/null || true
|
||||
echo "== Decky: session supervisor stopped"
|
||||
fi
|
||||
_bl_jobs=$(jobs -p)
|
||||
[ -n "$_bl_jobs" ] && kill $_bl_jobs 2>/dev/null
|
||||
echo "== steam: the client on the desktop has exited"
|
||||
else
|
||||
if [ -n "${decky_supervisor:-}" ]; then
|
||||
kill "$decky_supervisor" 2>/dev/null || true
|
||||
wait "$decky_supervisor" 2>/dev/null || true
|
||||
echo "== Decky: session supervisor stopped"
|
||||
fi
|
||||
reap_orphans
|
||||
fi
|
||||
exit "$rc"
|
||||
|
||||
Reference in new issue
Block a user