+#include "wayland-server.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct wl_client;
+struct wl_resource;
+
+/**
+ * @page page_single_pixel_buffer_v1 The single_pixel_buffer_v1 protocol
+ * single pixel buffer factory
+ *
+ * @section page_desc_single_pixel_buffer_v1 Description
+ *
+ * This protocol extension allows clients to create single-pixel buffers.
+ *
+ * Compositors supporting this protocol extension should also support the
+ * viewporter protocol extension. Clients may use viewporter to scale a
+ * single-pixel buffer to a desired size.
+ *
+ * Warning! The protocol described in this file is currently in the testing
+ * phase. Backward compatible changes may be added together with the
+ * corresponding interface version bump. Backward incompatible changes can
+ * only be done by creating a new major version of the extension.
+ *
+ * @section page_ifaces_single_pixel_buffer_v1 Interfaces
+ * - @subpage page_iface_wp_single_pixel_buffer_manager_v1 - global factory for single-pixel buffers
+ * @section page_copyright_single_pixel_buffer_v1 Copyright
+ *
+ *
+ * Copyright © 2022 Simon Ser
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ */
+struct wl_buffer;
+struct wp_single_pixel_buffer_manager_v1;
+
+#ifndef WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_INTERFACE
+#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_INTERFACE
+/**
+ * @page page_iface_wp_single_pixel_buffer_manager_v1 wp_single_pixel_buffer_manager_v1
+ * @section page_iface_wp_single_pixel_buffer_manager_v1_desc Description
+ *
+ * The wp_single_pixel_buffer_manager_v1 interface is a factory for
+ * single-pixel buffers.
+ * @section page_iface_wp_single_pixel_buffer_manager_v1_api API
+ * See @ref iface_wp_single_pixel_buffer_manager_v1.
+ */
+/**
+ * @defgroup iface_wp_single_pixel_buffer_manager_v1 The wp_single_pixel_buffer_manager_v1 interface
+ *
+ * The wp_single_pixel_buffer_manager_v1 interface is a factory for
+ * single-pixel buffers.
+ */
+extern const struct wl_interface wp_single_pixel_buffer_manager_v1_interface;
+#endif
+
+/**
+ * @ingroup iface_wp_single_pixel_buffer_manager_v1
+ * @struct wp_single_pixel_buffer_manager_v1_interface
+ */
+struct wp_single_pixel_buffer_manager_v1_interface {
+ /**
+ * destroy the manager
+ *
+ * Destroy the wp_single_pixel_buffer_manager_v1 object.
+ *
+ * The child objects created via this interface are unaffected.
+ */
+ void (*destroy)(struct wl_client *client,
+ struct wl_resource *resource);
+ /**
+ * create a 1×1 buffer from 32-bit RGBA values
+ *
+ * Create a single-pixel buffer from four 32-bit RGBA values.
+ *
+ * Unless specified in another protocol extension, the RGBA values
+ * use pre-multiplied alpha.
+ *
+ * The width and height of the buffer are 1.
+ *
+ * The r, g, b and a arguments valid range is from UINT32_MIN (0)
+ * to UINT32_MAX (0xffffffff).
+ *
+ * These arguments should be interpreted as a percentage, i.e. -
+ * UINT32_MIN = 0% of the given color component - UINT32_MAX = 100%
+ * of the given color component
+ * @param r value of the buffer's red channel
+ * @param g value of the buffer's green channel
+ * @param b value of the buffer's blue channel
+ * @param a value of the buffer's alpha channel
+ */
+ void (*create_u32_rgba_buffer)(struct wl_client *client,
+ struct wl_resource *resource,
+ uint32_t id,
+ uint32_t r,
+ uint32_t g,
+ uint32_t b,
+ uint32_t a);
+};
+
+
+/**
+ * @ingroup iface_wp_single_pixel_buffer_manager_v1
+ */
+#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_DESTROY_SINCE_VERSION 1
+/**
+ * @ingroup iface_wp_single_pixel_buffer_manager_v1
+ */
+#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_CREATE_U32_RGBA_BUFFER_SINCE_VERSION 1
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/app/src/main/cpp/waylandcomp/protocols/single-pixel-buffer-v1.xml b/app/src/main/cpp/waylandcomp/protocols/single-pixel-buffer-v1.xml
new file mode 100644
index 0000000000..bcbd0382eb
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/protocols/single-pixel-buffer-v1.xml
@@ -0,0 +1,76 @@
+
+
+
+ Copyright © 2022 Simon Ser
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of this software and associated documentation files (the "Software"),
+ to deal in the Software without restriction, including without limitation
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ and/or sell copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice (including the next
+ paragraph) shall be included in all copies or substantial portions of the
+ Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ DEALINGS IN THE SOFTWARE.
+
+
+
+ This protocol extension allows clients to create single-pixel buffers.
+
+ Compositors supporting this protocol extension should also support the
+ viewporter protocol extension. Clients may use viewporter to scale a
+ single-pixel buffer to a desired size.
+
+ Warning! The protocol described in this file is currently in the testing
+ phase. Backward compatible changes may be added together with the
+ corresponding interface version bump. Backward incompatible changes can
+ only be done by creating a new major version of the extension.
+
+
+
+
+ The wp_single_pixel_buffer_manager_v1 interface is a factory for
+ single-pixel buffers.
+
+
+
+
+ Destroy the wp_single_pixel_buffer_manager_v1 object.
+
+ The child objects created via this interface are unaffected.
+
+
+
+
+
+ Create a single-pixel buffer from four 32-bit RGBA values.
+
+ Unless specified in another protocol extension, the RGBA values use
+ pre-multiplied alpha.
+
+ The width and height of the buffer are 1.
+
+ The r, g, b and a arguments valid range is from UINT32_MIN (0)
+ to UINT32_MAX (0xffffffff).
+
+ These arguments should be interpreted as a percentage, i.e.
+ - UINT32_MIN = 0% of the given color component
+ - UINT32_MAX = 100% of the given color component
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c
index fbbd09886e..805eff9fa1 100644
--- a/app/src/main/cpp/waylandcomp/src/compositor.c
+++ b/app/src/main/cpp/waylandcomp/src/compositor.c
@@ -745,6 +745,21 @@ 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 */
}
+/* A single-pixel buffer (wl_single_pixel.c) as a 1x1 image, which the surface's viewport stretches. */
+static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
+ if (s->shm_img && (vkp_image_width(s->shm_img) != 1 || vkp_image_height(s->shm_img) != 1)) {
+ vkp_image_destroy(s->shm_img);
+ s->shm_img = NULL;
+ }
+ if (!s->shm_img) s->shm_img = vkp_image_create_shm(1, 1);
+ if (s->shm_img) vkp_image_upload_shm(s->shm_img, bgra, 4);
+ wl_buffer_send_release(buffer);
+ s->buf_w = 1;
+ s->buf_h = 1;
+ s->buf_alpha = bgra[3] != 0xff;
+ s->has_content = s->shm_img != NULL;
+}
+
/* 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;
@@ -1084,6 +1099,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
struct wl_resource *buffer = s->pending_buffer;
struct dmabuf_buffer *db = get_dmabuf(buffer);
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
+ uint8_t pixel[4];
/* The previous content is replaced before reaching the screen. */
feedback_discard_all(&s->feedback);
@@ -1113,6 +1129,9 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
} else if (shm) {
drop_dmabuf(s, 1);
take_shm(s, shm, buffer);
+ } else if (single_pixel_buffer_get(buffer, pixel)) {
+ drop_dmabuf(s, 1);
+ take_pixel(s, pixel, buffer);
} else {
drop_dmabuf(s, 1);
s->has_content = 0;
@@ -1661,15 +1680,24 @@ static void bind_desktop(struct wl_client *c, void *data, uint32_t ver, uint32_t
static void output_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static const struct wl_output_interface output_impl = { .release = output_release };
-static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
- struct wl_resource *r = wl_resource_create(c, &wl_output_interface, ver, id);
- if (!r) { wl_client_post_no_memory(c); return; }
- wl_resource_set_implementation(r, &output_impl, NULL, NULL);
- wl_output_send_geometry(r, 0, 0, 340, 190, WL_OUTPUT_SUBPIXEL_UNKNOWN,
- "DroidDeck", "Wayland", WL_OUTPUT_TRANSFORM_NORMAL);
+/* Every bound wl_output, so a resized output (a foldable opening) can send its new mode. */
+static struct wl_list g_outputs;
+static void output_resource_destroy(struct wl_resource *r) { wl_list_remove(wl_resource_get_link(r)); }
+
+static void output_send_mode(struct wl_resource *r) {
wl_output_send_mode(r, WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED,
g_output_w > 0 ? g_output_w : 1920, g_output_h > 0 ? g_output_h : 1080,
g_output_refresh_mhz > 0 ? g_output_refresh_mhz : 60000);
+}
+
+static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
+ struct wl_resource *r = wl_resource_create(c, &wl_output_interface, ver, id);
+ if (!r) { wl_client_post_no_memory(c); return; }
+ wl_resource_set_implementation(r, &output_impl, NULL, output_resource_destroy);
+ wl_list_insert(&g_outputs, wl_resource_get_link(r));
+ wl_output_send_geometry(r, 0, 0, 340, 190, WL_OUTPUT_SUBPIXEL_UNKNOWN,
+ "DroidDeck", "Wayland", WL_OUTPUT_TRANSFORM_NORMAL);
+ output_send_mode(r);
if (ver >= WL_OUTPUT_NAME_SINCE_VERSION) {
wl_output_send_name(r, "DroidDeck-1");
wl_output_send_description(r, "DroidDeck display");
@@ -3200,6 +3228,23 @@ static void key_event(uint32_t evdev, int pressed) {
wl_display_flush_clients(g_display);
}
+/* The output changed size under a running session (a foldable opened or closed, with the
+ * session following the screen). Every client that has had its first configure is told the new
+ * size: gamescope's Wayland backend and the desktop's KWin both resize their output to it, and
+ * the next buffers they commit fill the new panel instead of being letterboxed onto it. */
+static void output_resized(void) {
+ struct surface *s;
+ struct wl_resource *r;
+ wl_resource_for_each(r, &g_outputs) {
+ output_send_mode(r);
+ if (wl_resource_get_version(r) >= 2) wl_output_send_done(r);
+ }
+ wl_list_for_each(s, &g_surfaces, link)
+ if (s->xdg_toplevel && s->toplevel_committed) send_toplevel_configure(s);
+ droiddeck_log("display", "output resized to %dx%d", g_output_w, g_output_h);
+ wl_display_flush_clients(g_display);
+}
+
/* wl event-loop callback: drain queued input events written by the Android UI thread. */
static int on_input_readable(int fd, uint32_t mask, void *data) {
struct input_msg m;
@@ -3212,6 +3257,7 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
case 5: on_vsync(((int64_t)m.p1 << 32) | (uint32_t)m.p2); break;
case 6: pointer_delta(m.p1 / 256.0, m.p2 / 256.0); break; /* relative motion, 1/256 px */
case 7: deliver_touch(&m); break;
+ case 8: output_resized(); break;
default: deliver_pointer(&m); break;
}
}
@@ -3242,6 +3288,14 @@ void droiddeck_wayland_send_key(int evdev, int state) {
(void)n;
}
+/* Called from JNI after g_output_w/h changed: the compositor thread re-sends the size. */
+void droiddeck_wayland_output_resized(void) {
+ if (g_input_pipe[1] < 0) return;
+ struct input_msg m = { 8, 0, 0, 0, 0 };
+ ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
+ (void)n;
+}
+
/* Called from JNI on every screen refresh (Choreographer). */
void droiddeck_wayland_vsync(int64_t frame_time_ns) {
if (g_input_pipe[1] < 0) return;
@@ -3439,6 +3493,7 @@ static struct wl_listener g_client_created = { .notify = on_client_created };
int droiddeck_wayland_run(void) {
wl_list_init(&g_surfaces);
wl_list_init(&g_toplevels);
+ wl_list_init(&g_outputs);
wl_list_init(&g_constraints);
wl_list_init(&g_relative_pointers);
open_session_log();
diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c
index 74ddc6adaf..913f713d38 100644
--- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c
+++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c
@@ -122,4 +122,5 @@ void droiddeck_ext_init(struct wl_display *display) {
clipboard_init(display);
text_input_init(display);
toplevel_icon_init(display);
+ single_pixel_init(display);
}
diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h
index e21014fbf5..0dc8ae41aa 100644
--- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h
+++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h
@@ -48,3 +48,6 @@ void text_input_host_commit(const char *utf8, size_t len);
void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end);
void text_input_host_delete(int before, int after);
void toplevel_icon_init(struct wl_display *display);
+void single_pixel_init(struct wl_display *display);
+/* A wp_single_pixel_buffer_manager_v1 buffer: 1 and its pixel (B, G, R, A, premultiplied), else 0. */
+int single_pixel_buffer_get(struct wl_resource *buffer, uint8_t bgra[4]);
diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c
index 3af9a8c254..4551c4806f 100644
--- a/app/src/main/cpp/waylandcomp/src/vk_present.c
+++ b/app/src/main/cpp/waylandcomp/src/vk_present.c
@@ -160,6 +160,11 @@ static const char *vk_result_name(VkResult r);
static pthread_mutex_t g_req_lock = PTHREAD_MUTEX_INITIALIZER;
static ANativeWindow *g_req_window;
static int g_req_pending;
+/* A detach was asked for since the compositor thread last looked. A rebind (null, then the same
+ * window) to rebuild the swapchain at a new size can land in full before the thread gets to it,
+ * and would otherwise read as the same window handed over again - nothing rebuilt, and the old
+ * size's buffers scaled onto the rotated or refolded panel. */
+static int g_req_detached;
/* Scale mode + alignment (app values, see vk_present.h); written from any thread, read per frame. */
static volatile int g_mode = VKP_MODE_STRETCH, g_align = VKP_ALIGN_CENTER;
@@ -252,6 +257,7 @@ void vk_present_set_window(ANativeWindow *window) {
if (g_req_pending && g_req_window && g_req_window != window) superseded = g_req_window;
g_req_window = window;
g_req_pending = 1;
+ if (!window) g_req_detached = 1;
pthread_mutex_unlock(&g_req_lock);
if (superseded) ANativeWindow_release(superseded);
}
@@ -261,13 +267,20 @@ int vkp_apply_window_request(void) {
pthread_mutex_lock(&g_req_lock);
if (!g_req_pending) { pthread_mutex_unlock(&g_req_lock); return 0; }
w = g_req_window;
+ const int detached = g_req_detached;
g_req_window = NULL;
g_req_pending = 0;
+ g_req_detached = 0;
pthread_mutex_unlock(&g_req_lock);
if (w == g_window) {
/* The same window handed over again (ANativeWindow_fromSurface adds a reference each time). */
if (w) ANativeWindow_release(w);
- return 0;
+ if (!w || !detached) return 0;
+ /* ... after a detach: a rebind for a resized surface. Rebuilt at its size on the next frame. */
+ sc_layer_window_gone();
+ destroy_swapchain();
+ droiddeck_log("gpu", "screen surface rebound: rebuilding the swapchain at its new size");
+ return 1;
}
sc_layer_window_gone(); /* the layer (if any) belongs to the old window */
destroy_swapchain(); /* recreated against the new window on the next frame */
@@ -1516,6 +1529,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
const struct vkp_hdr_frame *hf, int *how) {
if (how) *how = 0;
vkp_apply_window_request();
+ check_surface_changed(); /* a rotation or a fold the rebind did not cover: rebuild at the new size */
if (g_dev_state == -2) return -1;
if (dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
@@ -2099,6 +2113,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
const struct vkp_hdr_frame *hf, int *rw, int *rh) {
if (g_pass.active) vkp_pass_abort();
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
+ check_surface_changed(); /* as in render_impl: the effects pass maps onto the output's size */
if (!g_swapchain && swap_init() != 0) return -1; /* the mapping is in output pixels */
update_map(scene_w, scene_h);
if (!g_map.valid) return -1;
diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
index 4d11a54192..8ec4b96b64 100644
--- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
+++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c
@@ -30,6 +30,7 @@ extern int droiddeck_cursor_serial(void);
extern void droiddeck_wayland_send_key(int evdev, int state);
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
+extern void droiddeck_wayland_output_resized(void);
extern volatile int g_fps_limit;
extern volatile int g_hide_shell;
extern volatile int g_zero_copy;
@@ -401,6 +402,17 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetOutputSize(JNIEnv
g_output_h = h > 0 ? h : 0;
}
+/* The output's size changed while the compositor runs (a foldable opening or closing with the
+ * session following the screen): store it and have the compositor thread tell the clients. */
+JNIEXPORT void JNICALL
+Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeResizeOutput(JNIEnv *env, jclass clazz, jint w, jint h) {
+ (void)env; (void)clazz;
+ if (w <= 0 || h <= 0) return;
+ g_output_w = w;
+ g_output_h = h;
+ droiddeck_wayland_output_resized();
+}
+
/* Fullscreen mode + screen alignment (Container.FULLSCREEN_* / ALIGN_* values): how the scene is
* fitted onto the output. Any thread, any time; the next frame uses it. */
JNIEXPORT void JNICALL
diff --git a/app/src/main/cpp/waylandcomp/src/wl_single_pixel.c b/app/src/main/cpp/waylandcomp/src/wl_single_pixel.c
new file mode 100644
index 0000000000..9dfe78233c
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/wl_single_pixel.c
@@ -0,0 +1,51 @@
+/*
+ * wp_single_pixel_buffer_manager_v1 (version 1): a wl_buffer of one pixel of one colour, which a
+ * client stretches over a surface with wp_viewporter. KWin's Wayland backend - the desktop's KWin
+ * nested in this compositor - refuses to start without it. The surface takes the pixel as a 1x1
+ * image, the way it takes a wl_shm buffer (compositor.c, take_pixel).
+ */
+#include
+#include "droiddeck_ext.h"
+#include "single-pixel-buffer-v1-server-protocol.h"
+
+struct single_pixel {
+ uint8_t bgra[4]; /* premultiplied, as wl_shm's ARGB8888 lies in memory */
+};
+
+static void buffer_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
+static const struct wl_buffer_interface buffer_impl = { .destroy = buffer_destroy };
+
+static void buffer_free(struct wl_resource *r) { free(wl_resource_get_user_data(r)); }
+
+int single_pixel_buffer_get(struct wl_resource *buffer, uint8_t bgra[4]) {
+ if (!buffer || !wl_resource_instance_of(buffer, &wl_buffer_interface, &buffer_impl)) return 0;
+ struct single_pixel *p = wl_resource_get_user_data(buffer);
+ for (int i = 0; i < 4; i++) bgra[i] = p->bgra[i];
+ return 1;
+}
+
+static void mgr_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
+static void mgr_create_buffer(struct wl_client *c, struct wl_resource *r, uint32_t id,
+ uint32_t red, uint32_t green, uint32_t blue, uint32_t alpha) {
+ struct single_pixel *p = calloc(1, sizeof(*p));
+ struct wl_resource *buffer = p ? wl_resource_create(c, &wl_buffer_interface, 1, id) : NULL;
+ if (!buffer) { free(p); wl_client_post_no_memory(c); return; }
+ /* The protocol's values span the whole u32 range; the top byte is the 8-bit channel. */
+ p->bgra[0] = blue >> 24;
+ p->bgra[1] = green >> 24;
+ p->bgra[2] = red >> 24;
+ p->bgra[3] = alpha >> 24;
+ wl_resource_set_implementation(buffer, &buffer_impl, p, buffer_free);
+}
+static const struct wp_single_pixel_buffer_manager_v1_interface mgr_impl = {
+ .destroy = mgr_destroy, .create_u32_rgba_buffer = mgr_create_buffer,
+};
+static void bind_manager(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
+ struct wl_resource *r = wl_resource_create(c, &wp_single_pixel_buffer_manager_v1_interface, ver, id);
+ if (!r) { wl_client_post_no_memory(c); return; }
+ wl_resource_set_implementation(r, &mgr_impl, NULL, NULL);
+}
+
+void single_pixel_init(struct wl_display *display) {
+ wl_global_create(display, &wp_single_pixel_buffer_manager_v1_interface, 1, NULL, bind_manager);
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt
index 4271956465..e12aefb38d 100644
--- a/app/src/main/java/com/droiddeck/launcher/App.kt
+++ b/app/src/main/java/com/droiddeck/launcher/App.kt
@@ -22,12 +22,15 @@ class App : Application() {
override fun onCreate() {
super.onCreate()
CrashHandler.install(this)
- // Before anything else touches the session prefs, so the first session already runs in Deck mode.
- com.droiddeck.launcher.session.SessionPrefs.settleDeckModeDefault(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.update.AppUpdates.init(this)
GpuClockPin.clearLeftover(this)
BwrapSpawner.start(this)
com.droiddeck.launcher.frontend.GameFileSync.start(this)
+ // The game stores the Stores section can talk to; the native engine loads only when one needs it.
+ com.droiddeck.launcher.stores.StoresState.init(this)
+ com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend)
+ com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend)
+ com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt
index 74c14f964a..7a6c60cbf5 100644
--- a/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/HomeActivity.kt
@@ -14,6 +14,7 @@ class HomeActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
routeHome()
}
diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt
index 0c101a51a5..1db0681286 100644
--- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt
@@ -10,6 +10,7 @@ import java.io.File
import android.content.pm.PackageManager
import android.hardware.display.DisplayManager
import android.net.Uri
+import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
@@ -17,6 +18,7 @@ import android.util.Log
import android.view.Display
import android.view.KeyEvent
import android.view.View
+import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
@@ -119,7 +121,6 @@ class MainActivity : ComponentActivity() {
private var showNonAdreno by mutableStateOf(null)
private var glThread by mutableStateOf(true)
private var noGlError by mutableStateOf(true)
- private var steamDeckMode by mutableStateOf(false)
private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true)
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
@@ -139,6 +140,7 @@ class MainActivity : ComponentActivity() {
private var pkgStage by mutableStateOf(null)
private var pkgPercent by mutableIntStateOf(-1)
private var desktopInstalled by mutableStateOf(false)
+ private var desktopPresent by mutableStateOf(false)
private var offlineAccount by mutableStateOf(null)
private var offline by mutableStateOf(false)
private var showPerformance by mutableStateOf(false)
@@ -161,9 +163,16 @@ class MainActivity : ComponentActivity() {
private var showPhantomGate by mutableStateOf(false)
private var directAudio by mutableStateOf(false)
private var stretch16x9 by mutableStateOf(false)
+ private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var launcherFullscreen by mutableStateOf(true)
private var animationsEnabled by mutableStateOf(true)
private var storeEnabled by mutableStateOf(false)
+ private var gameStoresEnabled by mutableStateOf(false)
+ private var gameStoresSpeedTier by mutableStateOf("fast")
+ private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
+ /** A page a notification asked for ("stores:downloads", "app:"), until the front end has gone there. */
+ private var navRequest by mutableStateOf(null)
+ private var storesShowMature by mutableStateOf(false)
private var mic by mutableStateOf(false)
private var wifiDiscovery by mutableStateOf(false)
private var wifiDiscoveryPermission by mutableStateOf(false)
@@ -295,29 +304,34 @@ class MainActivity : ComponentActivity() {
GameSaves.savesDir().mkdirs()
pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_saves_pick_folder, name, layout.label(this)), GameSaves.savesDir().path))
}
- private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
- if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
- SessionPrefs.setAddedGamesDirs(this, addedGamesDirs + path)
- addedGamesDirs = SessionPrefs.addedGamesDirs(this)
- addedGamesArt = SessionPrefs.addedGamesArt(this)
- refreshAddedGames()
- refresh()
- }
+ /** The Games tab's +: the picked .exe becomes a game (or selects / switches the one it belongs to). */
+ private fun addGameExe(path: String) {
+ val exe = java.io.File(path)
+ Thread({
+ val result = try { com.droiddeck.launcher.frontend.AddedGames.addExe(this, exe) } catch (e: Exception) {
+ Log.w(TAG, "add game: ${e.message}"); com.droiddeck.launcher.frontend.AddedGames.AddResult.NotFound
+ }
+ val game = when (result) {
+ is com.droiddeck.launcher.frontend.AddedGames.AddResult.Added -> result.game
+ is com.droiddeck.launcher.frontend.AddedGames.AddResult.Existing -> result.game
+ is com.droiddeck.launcher.frontend.AddedGames.AddResult.Switched -> result.game
+ else -> null
+ }
+ ui.post {
+ if (game == null) {
+ if (result is com.droiddeck.launcher.frontend.AddedGames.AddResult.Unreachable)
+ android.widget.Toast.makeText(this, R.string.games_add_unreachable, android.widget.Toast.LENGTH_LONG).show()
+ return@post
+ }
+ updateAddedGames(listOf(game.folder.path), then = { fetchAddedGameArt() })
+ navRequest = "app:${game.steamAppId ?: game.appId.toInt()}"
+ }
+ }, "add-game-exe").start()
}
- private var pendingAddedGame: String? = null
- private val pickAddedGameExe = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
- val folder = pendingAddedGame ?: return@registerForActivityResult
- pendingAddedGame = null
- if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
- SessionPrefs.setAddedGameExe(this, folder, path)
- refreshAddedGames()
- refresh()
- }
- }
- private var addedGamesDirs by mutableStateOf>(emptyList())
private var addedGamesArt by mutableStateOf(true)
@Volatile private var artFetchRunning = false
- private var addedGames by mutableStateOf>(emptyList())
+ /** The user entered a SteamGridDB API key of their own. */
+ private var sgdbUserKey by mutableStateOf(false)
private val pickRomsDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
SessionPrefs.setRomsDir(this, path)
@@ -329,7 +343,6 @@ class MainActivity : ComponentActivity() {
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
private var fexPreset by mutableStateOf("")
private var forceSsbs by mutableStateOf(false)
- private var steamChannel by mutableStateOf("steamdeck_publicbeta")
private var runSteamAtStartup by mutableStateOf(false)
private var theme by mutableStateOf("graphite")
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
@@ -343,7 +356,6 @@ class MainActivity : ComponentActivity() {
private var steamDownloadsInBackground by mutableStateOf(false)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var backActionsInverted by mutableStateOf(false)
- private var renderer by mutableStateOf("vulkan")
private var gameStorage by mutableStateOf("")
private var storageDiagnostics by mutableStateOf(false)
private var storageOptions by mutableStateOf>(emptyList())
@@ -352,6 +364,8 @@ class MainActivity : ComponentActivity() {
}
private var romsDir by mutableStateOf(null)
private var steamGames by mutableStateOf>(emptyList())
+ @Volatile private var componentSweepDone = false
+ @Volatile private var componentSweepSession: String? = null
private var emulatorList by mutableStateOf>(emptyList())
private var runningLabel by mutableStateOf(null)
private var logsEnabled by mutableStateOf(true)
@@ -437,6 +451,7 @@ class MainActivity : ComponentActivity() {
}
private fun readGameIntent(request: Intent) {
+ request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT
if (shortcutPicker) {
// The shortcut picker must only offer games from the scan started for this request.
@@ -520,9 +535,15 @@ class MainActivity : ComponentActivity() {
// Last start's game list, so the Steam wall is up on the first frame; refresh() replaces it.
steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
+ orientation = SessionPrefs.orientation(this)
+ requestedOrientation = orientation
launcherFullscreen = SessionPrefs.launcherFullscreen(this)
animationsEnabled = SessionPrefs.animationsEnabled(this)
storeEnabled = SessionPrefs.storeEnabled(this)
+ gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
+ gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
+ storesOpenTab = SessionPrefs.storesOpenTab(this)
+ storesShowMature = SessionPrefs.storesShowMature(this)
applyLauncherFullscreen()
updates.start()
setContent {
@@ -545,7 +566,7 @@ class MainActivity : ComponentActivity() {
shortcutLibraryScanning = shortcutLibraryScanning,
gameSyncFolder = gameSyncFolder,
busy = busy, stage = stage, percent = percent,
- desktopInstalled = desktopInstalled,
+ desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, agentCommands = agentCommands,
steamGames = steamGames, emulators = emulatorList, running = runningLabel,
@@ -573,23 +594,54 @@ class MainActivity : ComponentActivity() {
updates = updates.state(),
phantomProcessStatus = phantomProcessStatus,
showPhantomGate = showPhantomGate,
+ orientation = orientation,
launcherFullscreen = launcherFullscreen,
animationsEnabled = animationsEnabled,
storeEnabled = storeEnabled,
+ gameStoresEnabled = gameStoresEnabled,
+ gameStoresSpeedTier = gameStoresSpeedTier,
+ storesOpenTab = storesOpenTab,
+ navigate = navRequest,
+ addedGamesArt = addedGamesArt,
+ sgdbUserKey = sgdbUserKey,
+ storesShowMature = storesShowMature,
+ storeDownloadsActive = com.droiddeck.launcher.stores.StoresState.activeDownloads,
),
FrontEndActions(
onPlay = { startSteamSession() },
- // Steam's desktop client as a window on the desktop: under gamescope the
- // client puts itself into Big Picture whatever it is started with.
+ // The client's desktop UI, with gamescope's Deck integration disabled.
onPlayDesktopUi = {
startSession(Intent(this, SessionActivity::class.java)
- .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
+ .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_STEAM)
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true)
},
- onSteamGame = { g -> if (shortcutPicker) chooseGameShortcut(g) else launchGame(g) },
+ // A store game may need something done first (an Epic game its sign-in code).
+ onSteamGame = { g ->
+ if (shortcutPicker) chooseGameShortcut(g)
+ else {
+ // The launch takes the Windows components already on; the game's list is
+ // looked at again in the background once the session is over.
+ com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g)
+ com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
+ }
+ },
onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) },
onExportGameFile = { g -> pickGameExport(g) },
onSyncGameFiles = { pickGameExport(null) },
+ onAddGameExe = { path -> addGameExe(path) },
+ onAddedGamesChanged = { folders ->
+ // New games want art; an edit does not.
+ val known = steamGames.mapNotNull { it.gameFiles?.path }.toSet()
+ updateAddedGames(folders, then = { if (folders.any { it !in known }) fetchAddedGameArt() })
+ },
+ onAddedGameRemoved = { folder, appId, name -> removeAddedGame(folder, appId, name) },
+ onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() },
+ onSgdbKey = { key ->
+ Thread({
+ com.droiddeck.launcher.frontend.SteamGridDb.setUserKey(this, key)
+ ui.post { sgdbUserKey = key.isNotBlank(); refreshAddedGames() }
+ }, "sgdb-key").start()
+ },
onStopGameFileSync = {
Thread({
GameFileSync.disable(this)
@@ -632,6 +684,7 @@ class MainActivity : ComponentActivity() {
// The activity re-attaches to the session that is running; nothing restarts.
onResume = { startActivity(Intent(this, SessionActivity::class.java)) },
onSteamSettings = { openModeSettings(SessionService.MODE_STEAM) },
+ onRemoveDesktop = { removeDesktop() },
onDesktopSettings = { openModeSettings(SessionService.MODE_DESKTOP) },
onInstallPackage = { id -> installPackage(id) },
onRemovePackage = { id -> removePackage(id) },
@@ -696,12 +749,23 @@ class MainActivity : ComponentActivity() {
com.droiddeck.launcher.core.AppUiPrefs.setScale(this, percent)
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
},
+ onOrientation = { value ->
+ SessionPrefs.setOrientation(this, value)
+ orientation = value
+ requestedOrientation = value
+ },
onLauncherFullscreen = { on ->
SessionPrefs.setLauncherFullscreen(this, on)
launcherFullscreen = on
applyLauncherFullscreen()
},
onStoreEnabled = { on -> SessionPrefs.setStoreEnabled(this, on); storeEnabled = on },
+ onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on; if (on) com.droiddeck.launcher.stores.StoresState.refresh(this) },
+ onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier },
+ onStoresOpenTab = { tab -> SessionPrefs.setStoresOpenTab(this, tab); storesOpenTab = tab },
+ onNavigated = { navRequest = null },
+ onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show },
+ onLibraryChanged = { refreshAddedGames(); refresh() },
onAnimationsEnabled = { on ->
SessionPrefs.setAnimationsEnabled(this, on)
animationsEnabled = on
@@ -779,6 +843,7 @@ class MainActivity : ComponentActivity() {
onSteamButton = { on -> ControllerPrefs.setSteamButton(this, on); refreshController() },
onQamButton = { on -> ControllerPrefs.setQamButton(this, on); refreshController() },
onKeyboardButton = { on -> ControllerPrefs.setKeyboardButton(this, on); refreshController() },
+ onSelectSteam = { on -> ControllerPrefs.setSelectSteam(this, on); refreshController() },
onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) },
onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() },
onMapping = { settingsMode = null; showPerformance = false; showProtons = false; showComponents = false; showMapping = true },
@@ -843,8 +908,13 @@ class MainActivity : ComponentActivity() {
SessionPrefs.setMicAsked(this)
}
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
+ // A store sign-in an earlier build left in plain text is sealed with the Keystore key.
+ Thread({ com.droiddeck.launcher.stores.StoreAccounts.encryptAll(this) }, "store-credentials").start()
// A session folder left without its ending - the process was killed - gets it now.
if (!SessionState.running) Thread({
+ com.droiddeck.launcher.session.LogMigration.run(this)
+ com.droiddeck.launcher.frontend.GamesFolderMigration.run(this)
+ SessionLogShare.clear(this)
SessionArtifacts.finishAbandoned(this)
SessionArtifacts.scrubOlder(this)
SessionArtifacts.prune(this)
@@ -885,10 +955,20 @@ class MainActivity : ComponentActivity() {
} else {
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
}
+ if (Build.VERSION.SDK_INT >= 28) {
+ window.attributes = window.attributes.apply {
+ layoutInDisplayCutoutMode = if (launcherFullscreen) {
+ WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ } else {
+ WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
+ }
+ }
+ }
}
/** On the Components page the pad's LB / RB step through GPU drivers, FEX, DXVK and VKD3D-Proton, wrapping around. */
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
+ if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
val all = listOf(com.droiddeck.launcher.ui.GPU_TAB) + ComponentsManager.COMPONENTS
@@ -897,12 +977,26 @@ class MainActivity : ComponentActivity() {
}
return true
}
- return super.dispatchKeyEvent(event)
+ // Compose throws when its focus tree has lost the focused node; one key is dropped
+ // instead of the app.
+ return try {
+ super.dispatchKeyEvent(event)
+ } catch (e: IllegalStateException) {
+ if (e.message?.contains("active focus target") != true) throw e
+ android.util.Log.w("MainActivity", "key ${event.keyCode} dropped: ${e.message}")
+ true
+ }
}
override fun onResume() {
super.onResume()
+ orientation = SessionPrefs.orientation(this)
+ requestedOrientation = orientation
refreshWifiDiscovery()
+ // Back from a store's sign-in page: the Stores chips show the account at once. A store
+ // install finishing while this screen is up rebuilds the Games list through the listener.
+ if (gameStoresEnabled) com.droiddeck.launcher.stores.StoresState.refresh(this)
+ com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
com.droiddeck.launcher.ui.Motion.refresh(this)
// Back from a session stopped behind a flood: open on its blue, before the first frame.
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
@@ -960,6 +1054,8 @@ class MainActivity : ComponentActivity() {
unregisterReceiver(wifiLocationReceiver)
unregisterReceiver(mediaReceiver)
ui.removeCallbacks(mediaRefresh)
+ // An install finishing while this screen is away is picked up by onResume's refresh.
+ com.droiddeck.launcher.stores.StoresState.libraryListener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
// The session covers the page by now; coming back finds it as it was.
flood = null
@@ -1136,6 +1232,7 @@ class MainActivity : ComponentActivity() {
private fun refreshPackages() {
packageRows = catalog?.map { PackageRow(it.id, it.kind, it.notes) }
desktopInstalled = DesktopCatalog.desktopInstalled(this)
+ desktopPresent = DesktopCatalog.desktopPresent(this)
}
private fun launchProgram(path: String) {
@@ -1189,20 +1286,19 @@ class MainActivity : ComponentActivity() {
steamDownloadsInBackground = steamDownloadsInBackground,
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
pipAutoEnter = pipAutoEnter,
+ unfoldedControls = if (mode == SessionService.MODE_STEAM &&
+ com.droiddeck.launcher.session.SessionDisplay.foldable(this)) unfoldedControls else null,
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
backActionsInverted = backActionsInverted,
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
mic = if (mode == SessionService.MODE_STEAM) mic else null,
- renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null,
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
storageOptions = storageOptions,
storageDiagnostics = mode == SessionService.MODE_STEAM && storageDiagnostics,
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
forceSsbs = forceSsbs,
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
- steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
- steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
steamRepairQueued = steamRepairQueued,
mangoapp = mangoapp,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
@@ -1212,9 +1308,6 @@ class MainActivity : ComponentActivity() {
wifiDiscoveryLocation = wifiDiscoveryLocation,
wifiDiscoveryAsked = wifiDiscoveryAsked,
wifiDiscoveryBlocked = wifiDiscoveryBlocked,
- addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
- addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
- addedGamesArt = addedGamesArt,
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null,
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
@@ -1250,6 +1343,7 @@ class MainActivity : ComponentActivity() {
steamDownloadsInBackground = enabled
},
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
+ onUnfoldedControls = { on -> SessionPrefs.setUnfoldedControls(this, on); unfoldedControls = on },
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this, inverted)
@@ -1266,7 +1360,6 @@ class MainActivity : ComponentActivity() {
requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 2)
}
},
- onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r },
onGameStorage = { path, label -> setGameStorage(path, label) },
onPickGameStorageFolder = {
pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_game_storage), gameStorage.ifEmpty { null }))
@@ -1283,27 +1376,13 @@ class MainActivity : ComponentActivity() {
fsyncFirst = SessionPrefs.fsyncFirst(this)
syncFallback = SessionPrefs.syncFallback(this)
},
- onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id },
onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) },
- onSteamDeckMode = { on ->
- SessionPrefs.setSteamDeckMode(this, on)
- steamDeckMode = on
- steamChannel = SessionPrefs.steamChannel(this)
- },
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
onRunSteamAtStartup = { on ->
SessionPrefs.setRunSteamAtStartup(this, on)
runSteamAtStartup = on
},
- onPickAddedGamesDir = { pickAddedGamesDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_added_games), addedGamesDirs.lastOrNull())) },
- onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() },
- onForgetAddedGamesDir = { dir -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs - dir); addedGamesDirs = SessionPrefs.addedGamesDirs(this); refreshAddedGames(); refresh() },
- onAddedGameExe = { folder, path -> SessionPrefs.setAddedGameExe(this, folder, path); refreshAddedGames(); refresh() },
- onPickAddedGameExe = { folder ->
- pendingAddedGame = folder
- pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), getString(R.string.main_pick_game_exe), folder))
- },
onDeckyInstall = { release -> decky.installDecky(release) },
onDeckyCheck = { decky.refreshDecky() },
onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); decky.deckySupervisor = enabled },
@@ -1358,18 +1437,44 @@ class MainActivity : ComponentActivity() {
)
}
- /** The added games as the settings page lists them; a scan of the folder, on this thread (one level, small). */
- /** The added games for the session settings: a folder walk, so off the main thread. */
- private fun refreshAddedGames() {
+ /**
+ * The Games tab after these added games were added or edited: each read alone and put in
+ * place of its old entry (or added), no library-wide scan. [then] runs after, on the main thread.
+ */
+ private fun updateAddedGames(folders: List, then: () -> Unit = {}) {
+ if (folders.isEmpty()) return
Thread({
- val games = scanAddedGames()
- ui.post { addedGames = games; fetchAddedGameArt() }
- }, "added-games").start()
+ val fresh = folders.mapNotNull { f ->
+ com.droiddeck.launcher.frontend.AddedGames.single(this, f)?.let { com.droiddeck.launcher.frontend.Library.addedGame(this, it) }
+ }
+ // An added or edited game's Windows components, from its source's list.
+ fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.refreshLater(this, it) }
+ ui.post {
+ val paths = folders.toSet()
+ steamGames = (steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path in paths } + fresh).distinctBy { it.gameId }
+ then()
+ }
+ }, "added-games-update").start()
}
- /** Walks the added-games folders, which can sit on slow shared storage or an SD card. */
- private fun scanAddedGames() = com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
- com.droiddeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, (g.candidates + g.exe).map { c -> c.path to c.name }.distinctBy { it.first })
+ /** An added game removed: off the Games tab now; the rest (cache, Steam, listing) off the main thread. */
+ private fun removeAddedGame(folder: String, appId: Long?, name: String) {
+ steamGames = steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path == folder }
+ Thread({ com.droiddeck.launcher.frontend.AddedGames.remove(this, java.io.File(folder), appId, name) }, "added-game-remove").start()
+ }
+
+ /** After the added games changed: art that is missing is fetched (off the main thread). */
+ private fun refreshAddedGames() {
+ sgdbKeyKnown()
+ fetchAddedGameArt()
+ }
+
+ /** Whether the user has a SteamGridDB key of their own, for Setup; read off the main thread. */
+ private fun sgdbKeyKnown() {
+ Thread({
+ val set = com.droiddeck.launcher.frontend.SteamGridDb.userKey(this).isNotEmpty()
+ ui.post { sgdbUserKey = set }
+ }, "sgdb-key-state").start()
}
private fun fetchAddedGameArt() {
@@ -1389,9 +1494,11 @@ class MainActivity : ComponentActivity() {
}
private var pipAutoEnter by mutableStateOf(false)
+ private var unfoldedControls by mutableStateOf(false)
private fun openModeSettings(mode: String) {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
+ unfoldedControls = SessionPrefs.unfoldedControls(this)
showPerformance = false
showProtons = false
showComponents = false
@@ -1402,13 +1509,10 @@ class MainActivity : ComponentActivity() {
fastSync = SessionPrefs.fastSync(this)
fsyncFirst = SessionPrefs.fsyncFirst(this)
syncFallback = SessionPrefs.syncFallback(this)
- steamChannel = SessionPrefs.steamChannel(this)
- steamDeckMode = SessionPrefs.steamDeckMode(this)
steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this)
steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
- addedGamesDirs = SessionPrefs.addedGamesDirs(this)
hdrOn = SessionPrefs.hdr(this, mode)
fpsLimit = SessionPrefs.fpsLimit(this, mode)
upscaler = SessionPrefs.upscaler(this)
@@ -1423,7 +1527,6 @@ class MainActivity : ComponentActivity() {
stretch16x9 = SessionPrefs.stretch16x9(this)
mic = SessionPrefs.micEnabled(this)
refreshWifiDiscovery()
- renderer = SessionPrefs.desktopRenderer(this)
gameStorage = SessionPrefs.gameStorage(this)
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
settingsMode = mode
@@ -1431,12 +1534,10 @@ class MainActivity : ComponentActivity() {
// added-games folders, the storage volumes) lands while it animates in.
Thread({
drivers.refreshDrivers()
- val games = scanAddedGames()
val storage = GameStorage.options(this)
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this)
ui.post {
- addedGames = games
storageOptions = storage
if (mode == SessionService.MODE_STEAM) {
decky.deckyInstalled = deckyInstalled
@@ -1466,7 +1567,6 @@ class MainActivity : ComponentActivity() {
clientOverride = SessionPrefs.clientCpusOverride(this)
glThread = SessionPrefs.glThread(this)
noGlError = SessionPrefs.noGlError(this)
- steamDeckMode = SessionPrefs.steamDeckMode(this)
clientCores = CpuCores.parse(SessionPrefs.clientCpus(this)).ifEmpty { CpuCores.all.toSet() }
gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() }
tuSysmem = SessionPrefs.tuSysmem(this)
@@ -1485,7 +1585,9 @@ class MainActivity : ComponentActivity() {
private fun refresh() {
if (!busy && LinuxRuntimeInstaller.isBusy()) followRuntimeOperation { LinuxRuntimeInstaller.attach(it) }
+ addedGamesArt = SessionPrefs.addedGamesArt(this)
desktopInstalled = DesktopCatalog.desktopInstalled(this)
+ desktopPresent = DesktopCatalog.desktopPresent(this)
offlineAccount = OfflineMode.account(this)
offline = OfflineMode.enabled(this)
installed = LinuxRuntimeInstaller.installedVersion(this)
@@ -1505,13 +1607,39 @@ class MainActivity : ComponentActivity() {
val scanGeneration = ++libraryScanGeneration
if (shortcutPicker) shortcutLibraryScanning = true
Thread({
- // One update with the whole list: the wall places games by their position in it, so a
- // partial list first would shuffle every capsule when the rest arrived. LibraryCache
- // covers the wait.
+ // Steam's own games first, from their manifests alone (quick), beside the added games
+ // already listed: a game Steam installed during the session shows as the session ends,
+ // without waiting for the added games' walk below. Its Windows components' list is
+ // queued then too, on the low-priority worker, so its page is usually ready.
+ if (ready) {
+ val quick = runCatching { Library.steamGames(this) }.getOrNull()
+ if (quick != null) ui.post {
+ if (scanGeneration == libraryScanGeneration && steamGames.isNotEmpty()) {
+ val before = steamGames.map { it.gameId }.toSet()
+ val fresh = quick.filter { it.gameId !in before }
+ if (fresh.isNotEmpty()) {
+ steamGames = (quick + steamGames.filter { it.library == Library.ADDED }).distinctBy { it.gameId }
+ fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.queueGame(this, it, asked = false) }
+ }
+ }
+ }
+ }
+ // Then one update with the whole list: the wall places games by their position in it,
+ // so a partial list first would shuffle every capsule when the rest arrived.
+ // LibraryCache covers the wait.
val games = if (ready) Library.launchableGames(this) else emptyList()
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
val all = games.distinctBy { it.gameId }
if (ready) com.droiddeck.launcher.frontend.LibraryCache.save(this, all)
+ // Once per app start: the Steam games' Windows components from Steam's lists.
+ // Queued only, after the launcher has been up a little; the worker takes them one at a time.
+ // And again after each session (a game installed in it, files changed).
+ val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession }
+ if (ready && (!componentSweepDone || endedSession != null)) {
+ componentSweepDone = true
+ endedSession?.let { componentSweepSession = it }
+ ui.postDelayed({ Thread({ com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all) }, "components-sweep").start() }, 10_000)
+ }
ui.post {
if (scanGeneration == libraryScanGeneration) {
steamGames = all
@@ -1598,6 +1726,15 @@ class MainActivity : ComponentActivity() {
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null ||
components.compBusy != null || saveBusy != null || com.droiddeck.launcher.store.UserAppsState.working != null
+ private fun removeDesktop() {
+ if (runtimeChangesBlocked()) return
+ val operation = LinuxRuntimeInstaller.beginMaintenance(this, getString(R.string.desktop_removing)) ?: return
+ com.droiddeck.launcher.runtime.RuntimeInstallService.keepRemovalAlive(this)
+ followRuntimeOperation { listener ->
+ operation.run(listener) { progress -> DesktopCatalog.removeDesktop(this, progress) }
+ }
+ }
+
private fun removeRuntime() {
if (runtimeChangesBlocked()) return
val removal = LinuxRuntimeInstaller.beginUninstall(this) ?: return
@@ -1620,7 +1757,7 @@ class MainActivity : ComponentActivity() {
private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
busy = true
failed = false
- stage = getString(if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting)
+ stage = getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting)
percent = -1
Thread({
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index 2e9be51934..97c408b8c4 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -19,6 +19,7 @@ import android.view.MotionEvent
import android.view.ViewConfiguration
import android.view.Display
import android.view.SurfaceHolder
+import android.view.Gravity
import android.view.SurfaceView
import android.view.View
import android.view.WindowManager
@@ -51,6 +52,7 @@ import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.SessionClipboard
import com.droiddeck.launcher.input.OnScreenControls
import com.droiddeck.launcher.input.PadBridge
+import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.PointerGestures
import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays
@@ -109,6 +111,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var pip: com.droiddeck.launcher.session.SessionPipController
private var pipUi by mutableStateOf(false)
private var pipAutoEnter by mutableStateOf(false)
+ /** Unfolded controls: the setting, and the Deck controls under the game while they show. */
+ private var unfoldedControls by mutableStateOf(false)
+ private var unfoldedPanel: com.droiddeck.launcher.ui.DeckControlsPanel? = null
+ private lateinit var sessionRoot: FrameLayout
private val guestKeysDown = mutableSetOf()
private lateinit var surfaceView: SurfaceView
private lateinit var sessionOverlay: ComposeView
@@ -119,7 +125,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var padMotion: com.droiddeck.launcher.input.PadMotion? = null
/** Between onResume and onPause. */
private var resumed = false
- private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion(); openDeckRing("deck pad changed") } }
+ private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion(); openDeckRing("deck pad changed"); applyUnfoldedControls() } }
/**
* A Deck's controller is there from the moment it boots, and the client looks for it once, as
@@ -142,9 +148,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
/** Motion is read while the session shows and only if the pad is a Deck controller - which
* the service can decide after this activity has resumed (SessionState.deckPadListener). */
private fun updatePadMotion() {
- if (resumed && !pipUi && SessionState.deckPad) padMotion?.start() else padMotion?.stop()
+ // A Steam Controller brings its own gyro (SteamControllerBle); the phone's would fight it.
+ if (resumed && !pipUi && SessionState.deckPad && !SteamControllerBle.connected) padMotion?.start()
+ else padMotion?.stop()
}
+ private var steamController: SteamControllerBle? = null
private var onScreenControls: OnScreenControls? = null
+ /** Steam's touch controls (SteamTouchControls), made once the session offers the device. */
+ private var steamTouchControls: com.droiddeck.launcher.input.SteamTouchControls? = null
+ private var steamTouchAvailable by mutableStateOf(false)
+ private val steamTouchRetry = Runnable { updateOnScreenControls() }
+ /** While Steam's touch controls are up: how the game's touch config says touches outside them
+ * act (Steam Link's input and mouse modes), in place of the drawer's touch mode. */
+ private var steamTouchOptions: com.droiddeck.launcher.input.SteamTouchConfig.Options? = null
+ /** The touch mode touches are routed by: the drawer's, or the game's while Steam's controls are up. */
+ private var routedTouchMode = SessionPrefs.TOUCH_AUTO
private var keyboard: KeyboardHost? = null
private var controllerSettings by mutableStateOf(null)
private val sessionClipboard by lazy {
@@ -232,6 +250,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
private var drawerControllerActive by mutableStateOf(false)
private var backActionsInverted by mutableStateOf(false)
+ /** What the pad is to the Steam client (SessionPrefs.CONTROLLER_*), switched from the drawer. */
+ private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
/** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */
private var pcKeyboardOpen by mutableStateOf(false)
private var hudOn by mutableStateOf(true)
@@ -295,6 +315,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onInputDeviceRemoved(deviceId: Int) {
Log.i(TAG, "input device $deviceId disconnected")
+ padBridge?.onDeviceRemoved(deviceId)
updateOnScreenControls()
updatePointerCapture()
}
@@ -305,7 +326,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving()) {
+ requestedOrientation = SessionPrefs.orientation(this)
+ if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() ||
+ com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isMaintaining()) {
runtimeRemovalBlocked = true
android.widget.Toast.makeText(this, R.string.session_wait_removal, android.widget.Toast.LENGTH_SHORT).show()
finish()
@@ -336,6 +359,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
)
}
Log.i(TAG, "perf: " + PerfMode.apply(this, SessionState.fpsLimit))
+ if (!SessionState.running) SessionState.followScreen = followChoice()
+ applyFollowOrientation(resources.configuration)
goFullscreen()
// The device's volume keys change the stream the session plays on (the relay and
// PulseAudio are media playback); they are never forwarded to the guest.
@@ -357,13 +382,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "pointer capture " + if (hasCapture) "on" else "off")
}
}
+ sessionRoot = root
surfaceView = SurfaceView(this)
surfaceView.holder.addCallback(this)
root.addView(surfaceView)
+ // The window's size is only known once laid out, and changes as the phone folds or turns.
+ root.addOnLayoutChangeListener { _, l, t, r, b, ol, ot, or, ob ->
+ if (r - l != or - ol || b - t != ob - ot) uiHandler.post { applyUnfoldedControls() }
+ }
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
+ bridge.setSelectSteam(ControllerPrefs.read(this).selectSteam)
padBridge = bridge
SessionState.padBridge = bridge
+ // A paired Steam Controller is read over Bluetooth LE, out of lizard mode, as Steam Link reads it.
+ SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); updateOnScreenControls() } }
+ steamController = SteamControllerBle(this).also { it.start() }
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
@Suppress("DEPRECATION")
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
@@ -555,12 +589,30 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onKeyboardButton = { on -> updateControllerPrefs { ControllerPrefs.setKeyboardButton(this@SessionActivity, on) } },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
+ // Only where the session set the pad up to be switched (SessionService: deckPad).
+ padType = if (SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad) padType else null,
+ onPadType = { id ->
+ SessionPrefs.setSteamController(this@SessionActivity, id)
+ com.droiddeck.launcher.session.SteamDeckPad.showPad(SessionPrefs.padType(id))
+ com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(id))
+ padType = id
+ },
backActionsInverted = backActionsInverted,
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
backActionsInverted = inverted
},
- onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() },
+ onOsc = { v ->
+ SessionPrefs.setOscMode(this@SessionActivity, v)
+ readPrefs()
+ updateOnScreenControls()
+ if (v == SessionPrefs.OSC_STEAM_TOUCH && com.droiddeck.launcher.input.SteamTouchDevice.current == null)
+ Toast.makeText(this@SessionActivity, R.string.osc_style_next_session, Toast.LENGTH_LONG).show()
+ },
+ onEditSteamTouch = if (steamTouchAvailable && oscMode == SessionPrefs.OSC_STEAM_TOUCH && onScreenButtonsVisible) ({
+ drawerOpen = false
+ steamTouchControls?.startEditing()
+ }) else null,
onSuspendPolicy = { policy ->
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
suspendPolicy = policy
@@ -597,6 +649,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
pipAutoEnter = on
pip.refresh(true)
},
+ unfoldedControls = if (com.droiddeck.launcher.session.SessionDisplay.foldable(this@SessionActivity)) unfoldedControls else null,
+ onUnfoldedControls = ::chooseUnfoldedControls,
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
@@ -743,9 +797,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun loadingTitle(): String = when (loadingMode()) {
- SessionService.MODE_DESKTOP ->
- if (!SessionState.running && intent.getStringExtra(SessionService.EXTRA_STEAM_UI) != null) getString(R.string.session_starting_steam_desktop)
- else getString(R.string.session_starting_desktop)
+ // Also when the desktop was asked for with Steam (Big Picture's Switch to Desktop): the client
+ // does not open on it.
+ SessionService.MODE_DESKTOP -> getString(R.string.session_starting_desktop)
SessionService.MODE_RUN -> {
val program = if (SessionState.running) SessionState.program else intent.getStringExtra(SessionService.EXTRA_PROGRAM)
com.droiddeck.launcher.frontend.Library.nameForProgram(program)?.let { getString(R.string.session_starting_named, it) }
@@ -777,6 +831,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun readPrefs() {
pipAutoEnter = SessionPrefs.pipAutoEnter(this)
+ unfoldedControls = SessionPrefs.unfoldedControls(this)
hudOn = SessionPrefs.hudEnabled(this)
upscaler = SessionPrefs.upscaler(this)
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
@@ -792,15 +847,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
WaylandCompositor.nativeSendSceneInput(3, it, 0)
}
}
- if (nextTouchMode == SessionPrefs.TOUCH_OFF) cursorVisible = false
+ if (nextTouchMode == SessionPrefs.TOUCH_OFF || !usingTouchpad()) cursorVisible = false
}
touchMode = nextTouchMode
+ routedTouchMode = effectiveTouchMode()
frameGen = FrameGen.mode(this)
fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
oscMode = SessionPrefs.oscMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
+ padType = SessionPrefs.steamController(this)
}
// ── Compositor ──────────────────────────────────────────────────────────────────────────
@@ -927,8 +984,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
/** Null when the desktop package is in, else the loading screen's closing line. */
private fun installDesktop(): String? {
uiHandler.post { loading.percent = -1; loading.say(getString(DESKTOP_LINES.downloading), DESKTOP_LINES.topic, readable = true) }
- val entry = com.droiddeck.launcher.runtime.DesktopCatalog.fetch()?.firstOrNull { it.id == "desktop" }
- ?: return getString(R.string.session_desktop_catalog_unreachable)
+ val entry = com.droiddeck.launcher.runtime.DesktopCatalog.desktopEntry(this)
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry,
progressFor(DESKTOP_LINES, entry.size / 1_000_000))
return problem?.let { getString(R.string.session_desktop_install_failed, it) }
@@ -962,7 +1018,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// sized once when the session starts and cannot change. A foldable recreates the Surface
// on the other panel, and recomputing the size there told the compositor a 21:9 buffer
// 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()
+ // Follow screen is the exception: there the compositor tells gamescope the new size, so the
+ // session takes the shape of the Surface it now has.
+ val previous = SessionState.outputSize
+ val live = if (SessionState.followScreen && !isInPictureInPictureMode)
+ com.droiddeck.launcher.session.SessionDisplay.followSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
+ else null
+ val size = live ?: if (SessionState.running) previous else outputSize()
SessionState.outputSize = size
if (!SessionState.running) SessionState.refreshHz = refreshHz()
// How far the panel enlarges the session, for texture sharpness "Auto" (TextureFiltering):
@@ -1021,6 +1083,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), SessionState.fpsLimit,
)
+ if (SessionState.running && size != previous) {
+ Log.i(TAG, "follow screen: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
+ WaylandCompositor.nativeResizeOutput(size.first, size.second)
+ }
if (!SessionState.running) SessionEvents.record("compositor.started")
// The service owns everything below the compositor. It is started whenever no session is
// running - NOT only when the compositor was just started: the compositor lives for the
@@ -1049,9 +1115,52 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (resized) {
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
CompositorHost.resize(holder.surface) { applyFrameGen() }
+ followWindow(width, height)
}
}
+ /**
+ * Follow screen: the session's display takes the window's new size (a Fold opening onto its
+ * inner panel, or closing onto the cover), so the picture fills the panel instead of being
+ * letterboxed onto it. Not in picture-in-picture: that window is a preview of the session,
+ * and resizing the guest to it would leave Steam laid out for a thumbnail.
+ */
+ private fun followWindow(width: Int, height: Int) {
+ if (!SessionState.followScreen || isInPictureInPictureMode || !CompositorHost.isStarted) return
+ val size = com.droiddeck.launcher.session.SessionDisplay.followSize(width, height) ?: return
+ if (size == SessionState.outputSize) return
+ Log.i(TAG, "follow screen: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
+ SessionState.outputSize = size
+ val panel = panelBounds()
+ SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1)
+ WaylandCompositor.nativeResizeOutput(size.first, size.second)
+ }
+
+ /** Whether this session's resolution is Follow screen; decided once, when it starts. */
+ private fun followChoice(): Boolean {
+ val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
+ return SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) ==
+ com.droiddeck.launcher.session.SessionDisplay.FOLLOW_SCREEN
+ }
+
+ /**
+ * Follow screen on a large panel (a Fold's inner screen) may turn with the device: a window
+ * locked to landscape on a squarer panel is letterboxed by the system itself, which no output
+ * size can undo. A phone-sized panel (the cover screen) stays landscape as before.
+ */
+ private fun applyFollowOrientation(config: android.content.res.Configuration) {
+ if (!SessionState.followScreen) return
+ val wanted = if (config.smallestScreenWidthDp >= 600) android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER
+ else android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
+ if (requestedOrientation != wanted) requestedOrientation = wanted
+ }
+
+ override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
+ super.onConfigurationChanged(newConfig)
+ applyFollowOrientation(newConfig)
+ applyUnfoldedControls()
+ }
+
override fun surfaceDestroyed(holder: SurfaceHolder) {
surfaceW = 0
surfaceH = 0
@@ -1277,7 +1386,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return super.dispatchKeyEvent(event)
}
if (pipUi) return true
- val fromController = event.device != null && PadBridge.isFromController(event.device)
+ val fromController = PadBridge.isControllerKeyEvent(event)
if (fromController && event.action == KeyEvent.ACTION_DOWN) {
if (drawerOpen && !drawerControllerActive) sessionOverlay.requestFocus()
drawerControllerActive = true
@@ -1329,12 +1438,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
return true
}
- if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchKeyEvent(event)
+ if (pcKeyboardOpen && fromController) return super.dispatchKeyEvent(event)
if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true
// A hardware keyboard, forwarded to the compositor's wl_keyboard. Back is left to the
// activity, which opens the drawer.
- val fromPad = event.device != null && PadBridge.isFromController(event.device)
- if (CompositorHost.isStarted && event.keyCode != KeyEvent.KEYCODE_BACK && !fromPad) {
+ if (CompositorHost.isStarted && event.keyCode != KeyEvent.KEYCODE_BACK && !fromController) {
val down = event.action == KeyEvent.ACTION_DOWN
if (down || event.action == KeyEvent.ACTION_UP) {
var evdev = EvdevKeys.fromKeyCode(event.keyCode)
@@ -1372,7 +1480,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (pipUi) return true
- if (drawerOpen && event.device != null && PadBridge.isFromController(event.device)) {
+ if (drawerOpen && PadBridge.isControllerMotionEvent(event)) {
if (!drawerControllerActive) sessionOverlay.requestFocus()
drawerControllerActive = true
if (event.actionMasked == MotionEvent.ACTION_MOVE &&
@@ -1383,7 +1491,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return true
}
if (drawerDirectionKey != KeyEvent.KEYCODE_UNKNOWN) releaseDrawerDirection()
- if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event)
+ if (pcKeyboardOpen && PadBridge.isControllerMotionEvent(event)) return super.dispatchGenericMotionEvent(event)
if (padBridge?.onMotionEvent(event) == true) return true
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true
return super.dispatchGenericMotionEvent(event)
@@ -1607,17 +1715,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
WaylandCompositor.nativeSendSceneInput(3, button, if (pressed) 1 else 0)
},
sendWheel = { steps -> WaylandCompositor.nativeSendSceneInput(4, steps, 0) },
- onSteamMenu = {
- if (SessionState.mode == SessionService.MODE_STEAM) {
- padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
- Handler(Looper.getMainLooper()).postDelayed({
- padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, false) }
- }, 90)
- }
- },
- onQam = {
- if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam()
- },
+ onSteamMenu = ::tapSteamButton,
+ onQam = ::tapQam,
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
)
secondScreenPresentation = presentation
@@ -1634,6 +1733,64 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
+ private fun tapSteamButton() {
+ if (SessionState.mode == SessionService.MODE_STEAM) {
+ padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
+ Handler(Looper.getMainLooper()).postDelayed({
+ padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, false) }
+ }, 90)
+ }
+ }
+
+ private fun tapQam() {
+ if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam()
+ }
+
+ private fun chooseUnfoldedControls(on: Boolean) {
+ SessionPrefs.setUnfoldedControls(this, on)
+ unfoldedControls = on
+ applyUnfoldedControls()
+ }
+
+ /**
+ * Unfolded controls: on a foldable's inner screen, the game above and the Steam Deck controller's
+ * trackpads and back grips below ([com.droiddeck.launcher.ui.DeckControlsPanel], as a second
+ * screen shows them, plus a whole gamepad). The on-screen pad is hidden meanwhile. The surface shrinks to the top part, so a Follow screen session resizes
+ * to it and any other is fitted into it. Folded onto the cover screen - a phone-sized panel -
+ * or in picture-in-picture, the game is full screen again.
+ */
+ private fun applyUnfoldedControls() {
+ if (!::sessionRoot.isInitialized) return
+ val width = sessionRoot.width
+ val height = sessionRoot.height
+ val wanted = unfoldedControls && com.droiddeck.launcher.session.SessionDisplay.foldable(this) &&
+ SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad &&
+ !pipUi && !isInPictureInPictureMode && width > 0 && height > 0 &&
+ resources.configuration.smallestScreenWidthDp >= com.droiddeck.launcher.session.SessionDisplay.UNFOLDED_MIN_DP
+ val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height)
+ else FrameLayout.LayoutParams.MATCH_PARENT
+ val params = surfaceView.layoutParams as FrameLayout.LayoutParams
+ if (params.height != gameHeight) {
+ surfaceView.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, gameHeight, Gravity.TOP)
+ Log.i(TAG, if (wanted) "unfolded controls: game ${width}x$gameHeight, controls ${width}x${height - gameHeight}"
+ else "unfolded controls: game full screen")
+ }
+ var panel = unfoldedPanel
+ if (!wanted) {
+ if (panel != null) { sessionRoot.removeView(panel); unfoldedPanel = null; updateOnScreenControls() }
+ return
+ }
+ if (panel == null) {
+ panel = com.droiddeck.launcher.ui.DeckControlsPanel(this, onClose = { chooseUnfoldedControls(false) },
+ onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge)
+ // Just above the surface: the on-screen pad, keyboard and drawer still draw over it.
+ sessionRoot.addView(panel, sessionRoot.indexOfChild(surfaceView) + 1)
+ unfoldedPanel = panel
+ updateOnScreenControls()
+ }
+ panel.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM)
+ }
+
private fun moveSecondScreenPointer(x: Float, y: Float, width: Float, height: Float) {
if (width <= 0f || height <= 0f) return
val nx = (x / width).coerceIn(0f, 1f)
@@ -1654,8 +1811,32 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
+ /** The touch mode in force: the game's own while Steam's touch controls are shown. */
+ private fun effectiveTouchMode(): String {
+ val options = steamTouchOptions
+ if (options == null || steamTouchControls?.visibility != View.VISIBLE) return SessionPrefs.touchMode(this)
+ return when {
+ options.inputMode == com.droiddeck.launcher.input.SteamTouchConfig.INPUT_CONTROLLER -> SessionPrefs.TOUCH_OFF
+ options.mouseMode == com.droiddeck.launcher.input.SteamTouchConfig.MOUSE_RELATIVE -> SessionPrefs.TOUCH_PAD
+ else -> SessionPrefs.TOUCH_DIRECT
+ }
+ }
+
+ private fun applyTouchRouting() {
+ val next = effectiveTouchMode()
+ if (::touchpad.isInitialized) {
+ val speed = steamTouchOptions?.trackpadSensitivity?.takeIf { steamTouchControls?.visibility == View.VISIBLE } ?: 1f
+ touchpad.sensitivity = 1.15f * speed
+ }
+ if (next == routedTouchMode) return
+ if (::touchpad.isInitialized) touchpad.cancel()
+ if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
+ if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false
+ routedTouchMode = next
+ }
+
/** Touchpad on the desktop, direct in Steam, unless the drawer says otherwise. */
- private fun usingTouchpad(): Boolean = when (SessionPrefs.touchMode(this)) {
+ private fun usingTouchpad(): Boolean = when (routedTouchMode) {
SessionPrefs.TOUCH_PAD -> true
SessionPrefs.TOUCH_DIRECT -> false
else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop"
@@ -1677,7 +1858,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event)
// Child views get the event first, so menus, keyboards and the on-screen pad still work.
- if (touchMode == SessionPrefs.TOUCH_OFF) return true
+ if (routedTouchMode == SessionPrefs.TOUCH_OFF) return true
if (usingTouchpad()) {
val rect = drawnRect() ?: return false
if (touchpad.bounds != rect) {
@@ -1796,30 +1977,97 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
what, d.name, d.vendorId, d.productId, d.id, d.sources))
}
+ /** Steam's touch controls, once the session has made the device (SessionService). */
+ private fun steamTouch(): com.droiddeck.launcher.input.SteamTouchControls? {
+ val device = com.droiddeck.launcher.input.SteamTouchDevice.current ?: return null
+ steamTouchControls?.let { view ->
+ if (view.device === device) return view
+ // A new session made a new device: the view of the old one goes.
+ view.releaseAll()
+ (view.parent as? android.view.ViewGroup)?.removeView(view)
+ steamTouchControls = null
+ }
+ val root = onScreenControls?.parent as? android.view.ViewGroup ?: return null
+ val view = com.droiddeck.launcher.input.SteamTouchControls(this, device,
+ onMenu = { drawerOpen = true }, onKeyboard = ::togglePcKeyboard)
+ view.visibility = View.GONE
+ view.onOptions = { options ->
+ steamTouchOptions = options
+ applyTouchRouting()
+ }
+ // Paste: the clipboard is shared with the session's X servers; Ctrl+V types it.
+ view.onPaste = {
+ sendGuestKey(29, true); sendGuestKey(47, true) // KEY_LEFTCTRL, KEY_V
+ sendGuestKey(47, false); sendGuestKey(29, false)
+ }
+ // The client reads a controller's config when it connects: after a save, plug the device
+ // out and back in so it takes the new one.
+ view.onSaved = {
+ device.plugged = false
+ uiHandler.postDelayed({ updateOnScreenControls() }, 700)
+ }
+ root.addView(view, root.indexOfChild(onScreenControls) + 1)
+ steamTouchControls = view
+ steamTouchAvailable = true
+ return view
+ }
+
private fun updateOnScreenControls() {
val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc")
.takeIf { it.isFile }
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
?: SessionPrefs.oscMode(this)
val controls = onScreenControls ?: return
- if (pipUi) {
+ // In picture-in-picture, or with the unfolded screen's gamepad below the game, the on-screen
+ // pad would only cover the picture or that panel.
+ if (pipUi || unfoldedPanel != null) {
onScreenButtonsVisible = false
controls.releaseAll()
controls.visibility = View.GONE
+ steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE }
+ com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
return
}
val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM
+ // Steam's touch controller stands in for the app's pad, and is plugged into the client only
+ // while it is shown - as Steam Link withdraws its controls when a physical pad is in use.
+ val wantsSteam = forced == SessionPrefs.OSC_STEAM_TOUCH && SessionState.mode == SessionService.MODE_STEAM
+ val steam = if (wantsSteam) steamTouch() else null
+ // The service makes the device while the session starts, after this activity: the app's
+ // own pad until then, and another look in a moment.
+ if (wantsSteam && steam == null && !isFinishing && !isDestroyed) {
+ uiHandler.removeCallbacks(steamTouchRetry)
+ uiHandler.postDelayed(steamTouchRetry, 1000)
+ }
+ if (steam == null) {
+ steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE }
+ com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
+ }
controls.setButtonsOnly(buttonsOnly)
val show = when (forced) {
SessionPrefs.OSC_ALWAYS -> true
SessionPrefs.OSC_STEAM_QAM -> true
SessionPrefs.OSC_NEVER -> false
+ // Shown throughout a Steam session: a handheld's built-in pad would keep Auto off for good.
+ // Outside Steam it is Auto.
+ SessionPrefs.OSC_STEAM_TOUCH -> SessionState.mode == SessionService.MODE_STEAM ||
+ (!PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP)
// Auto: the touch pad when there is no controller - except on the desktop, where the
// screen is a touchpad for the pointer and a pad over it would be in the way. A game
// started from the rail, or Steam, gets it; the drawer turns it on anywhere.
- else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
+ else -> !PadBridge.anyControllerConnected() && !SteamControllerBle.connected &&
+ SessionState.mode != SessionService.MODE_DESKTOP
}
onScreenButtonsVisible = show
+ if (steam != null) {
+ if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE }
+ if (!show) steam.releaseAll()
+ steam.visibility = if (show) View.VISIBLE else View.GONE
+ com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = show
+ applyTouchRouting()
+ Log.i(TAG, "on-screen controls: Steam's touch controller " + if (show) "shown" else "hidden")
+ return
+ }
if (show == (controls.visibility == View.VISIBLE)) return
if (!show) controls.releaseAll()
controls.visibility = if (show) View.VISIBLE else View.GONE
@@ -1891,6 +2139,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
super.onPictureInPictureModeChanged(inPip, newConfig)
if (::pip.isInitialized) pip.changed(inPip)
+ // The panel may have changed while the session was a thumbnail (folded or unfolded in PiP).
+ if (!inPip && surfaceW > 0) followWindow(surfaceW, surfaceH)
+ applyUnfoldedControls()
}
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
@@ -1947,6 +2198,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onResume() {
super.onResume()
+ requestedOrientation = SessionPrefs.orientation(this)
if (runtimeRemovalBlocked) return
com.droiddeck.launcher.ui.Motion.refresh(this)
refreshHomeApp()
@@ -2018,10 +2270,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
+ // ALWAYS from Android 11: SHORT_EDGES left a black strip along a camera on the long edge,
+ // which is where a Fold's inner-screen camera sits with the device held in landscape.
if (Build.VERSION.SDK_INT >= 28) {
window.attributes = window.attributes.apply {
- layoutInDisplayCutoutMode =
- WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+ layoutInDisplayCutoutMode = if (Build.VERSION.SDK_INT >= 30)
+ WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
+ else WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
}
}
@@ -2038,6 +2293,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onDestroy() {
+ uiHandler.removeCallbacks(steamTouchRetry)
if (runtimeRemovalBlocked) { super.onDestroy(); return }
// Deliberately does NOT end the session: this activity can be destroyed while the user is
// in another app, and the whole point of the service is that Steam survives that.
@@ -2049,6 +2305,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
closeSecondScreen(reset = false)
if (::hud.isInitialized) hud.stop()
padBridge?.stop()
+ steamController?.stop()
if (SessionState.padBridge === padBridge) SessionState.padBridge = null
padMotion?.stop()
if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt
index 80648e8875..2b8ba775b0 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.agent
+import com.droiddeck.launcher.session.SessionPaths
import android.Manifest
import android.content.ContentProvider
import android.content.ContentValues
@@ -107,7 +108,7 @@ class AgentBridgeProvider : ContentProvider() {
private fun state(context: Context): JSONObject {
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
- val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: latestSessionDirectory()
+ val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
val session = JSONObject()
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
.put("phase", SessionState.phase.name)
@@ -163,12 +164,6 @@ class AgentBridgeProvider : ContentProvider() {
.put("session", session)
}
- private fun latestSessionDirectory(): File? {
- val parent = LinuxRuntime.debugLogDir()
- return parent.listFiles { file -> file.isDirectory && file.name.startsWith("session-") }
- ?.maxWithOrNull(compareBy { it.lastModified() }.thenBy { it.name })
- }
-
private fun stop(context: Context): JSONObject {
if (SessionState.running) {
SessionService.stop(context)
diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentStartActivity.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentStartActivity.kt
index 99a6f784c6..edf38dde68 100644
--- a/app/src/main/java/com/droiddeck/launcher/agent/AgentStartActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentStartActivity.kt
@@ -14,6 +14,7 @@ import org.json.JSONObject
class AgentStartActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
val request = decodeRequest(intent.getStringExtra(EXTRA_REQUEST))
if (request == null) {
finish()
diff --git a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java
index 9af7ab959f..c4e1db8c7d 100644
--- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java
+++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java
@@ -182,26 +182,30 @@ public class PulseAudioComponent extends SessionPart {
* client is never left without an output. Says so in the audio log either way.
*/
private void ensureClientSink(java.io.PrintWriter out) {
- long deadline = System.currentTimeMillis() + 15000L;
- String sinks = null;
- while (System.currentTimeMillis() < deadline && pid > 1) {
- if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break;
- try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
+ try {
+ long deadline = System.currentTimeMillis() + 15000L;
+ String sinks = null;
+ while (System.currentTimeMillis() < deadline && pid > 1) {
+ if (socket().exists() && (sinks = pactl("list", "short", "sinks")) != null) break;
+ try { Thread.sleep(250L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
+ }
+ String line;
+ if (sinks == null) {
+ line = "== client sink: the daemon did not answer in 15 s; no fallback attempted";
+ } else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
+ line = "== client sink: DirectAudio (module-directaudio-native-sink)";
+ } else {
+ boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
+ && pactl("set-default-sink", "AAudioSink") != null;
+ line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
+ : "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
+ Log.w(TAG, line);
+ }
+ Log.i(TAG, line);
+ if (out != null) synchronized (out) { out.println(line); out.flush(); }
+ } catch (Throwable t) {
+ Log.w(TAG, "ensureClientSink failed", t);
}
- String line;
- if (sinks == null) {
- line = "== client sink: the daemon did not answer in 15 s; no fallback attempted";
- } else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) {
- line = "== client sink: DirectAudio (module-directaudio-native-sink)";
- } else {
- boolean loaded = pactl("load-module", "module-aaudio-sink", "sink_name=AAudioSink", "performance_mode=1", "adaptive=1", "volume=1.0") != null
- && pactl("set-default-sink", "AAudioSink") != null;
- line = loaded ? "== client sink: DirectAudio did not come up; FALLBACK to the plain AAudio sink (AAudioSink)"
- : "== client sink: DirectAudio did not come up and the AAudio fallback failed too - no client sound";
- Log.w(TAG, line);
- }
- Log.i(TAG, line);
- if (out != null) synchronized (out) { out.println(line); out.flush(); }
}
/** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */
@@ -223,8 +227,14 @@ public class PulseAudioComponent extends SessionPart {
builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath());
process = builder.start();
String output;
- try (InputStream in = process.getInputStream()) {
- output = new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
+ try (InputStream in = process.getInputStream();
+ java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream()) {
+ byte[] buf = new byte[4096];
+ int n;
+ while ((n = in.read(buf)) != -1) {
+ outStream.write(buf, 0, n);
+ }
+ output = outStream.toString(java.nio.charset.StandardCharsets.UTF_8.name());
}
if (!process.waitFor(5, TimeUnit.SECONDS)) {
process.destroyForcibly();
@@ -234,7 +244,7 @@ public class PulseAudioComponent extends SessionPart {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
- } catch (Exception e) {
+ } catch (Throwable t) {
return null;
} finally {
if (process != null && process.isAlive()) process.destroyForcibly();
diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
index c16ad51f85..5fa562da95 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
@@ -53,7 +53,7 @@ object DeviceReport {
b.append("DroidDeck session report\n")
b.append("========================\n")
k("Written", SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz", Locale.US).format(Date()))
- k("Session mode", when (mode) { SessionService.MODE_DESKTOP -> "desktop (labwc/LXQt)"; SessionService.MODE_RUN -> "a program under gamescope"; else -> "Steam client (gamescope)" })
+ k("Session mode", when (mode) { SessionService.MODE_DESKTOP -> "desktop (KDE Plasma)"; SessionService.MODE_RUN -> "a program under gamescope"; else -> "Steam client (gamescope)" })
h("App")
runCatching {
@@ -152,7 +152,6 @@ object DeviceReport {
k("Zink lazy descriptors", SessionPrefs.zinkLazy(context))
k("Threaded GL (glthread)", SessionPrefs.glThread(context))
k("No GL error checks", SessionPrefs.noGlError(context))
- k("Steam Deck mode", SessionPrefs.steamDeckMode(context))
k("Steam controller", SessionPrefs.steamController(context))
k("Upscaler", (SessionPrefs.upscalerChoices.firstOrNull { it.first == SessionPrefs.upscaler(context) }?.second ?: "Off") +
" (sharpness ${SessionPrefs.upscaleSharpness(context)}%)")
@@ -189,7 +188,7 @@ object DeviceReport {
}
for (name in listOf("droiddeck-tu-debug", "droiddeck-driver",
"droiddeck-osc", "droiddeck-no-pad",
- "droiddeck-no-hud", "droiddeck-wlr-renderer")) {
+ "droiddeck-no-hud")) {
val f = File(Environment.getExternalStorageDirectory(), "Download/$name")
if (f.isFile) k(name, FileUtils.readString(f)?.trim()?.replace('\n', ' ')?.ifEmpty { "(present, empty)" } ?: "(present)")
}
diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt
index e621372380..daa7e5d9d3 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt
@@ -26,4 +26,8 @@ object DeviceSupport {
val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null
return soc?.let { "$it (${Build.HARDWARE})" } ?: Build.HARDWARE.ifBlank { context.getString(R.string.gpu_this_gpu) }
}
+
+ /** False on the Odin 3 (CQ8725S): a low-latency Wi-Fi lock makes its WLAN firmware hang, and
+ * that firmware reboots the whole device instead of restarting Wi-Fi. */
+ fun lowLatencyWifiSafe(): Boolean = Build.VERSION.SDK_INT < 31 || Build.SOC_MODEL != "CQ8725S"
}
diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt
index b2a8611f4e..6e6369228e 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt
@@ -33,7 +33,8 @@ object GameEnvironment {
"VKD3D_SHADER_MODEL" to "6_9",
// .NET 7 and later reserve 256 GB of address space for the GC heap at startup, more than an
// Android process has free, and the runtime fails to start. 32 GB is plenty for a game.
- "DOTNET_GCRegionRange" to "0x800000000",
+ // Older NativeAOT runtimes require bare hex digits. CoreCLR accepts this form too.
+ "DOTNET_GCRegionRange" to "800000000",
// .NET's W^X writes JIT code through a second mapping that FEX does not watch, so FEX keeps
// running the stale translation and the game hangs at startup.
"DOTNET_EnableWriteXorExecute" to "0",
diff --git a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt
index bac157b82e..4406a7028b 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt
@@ -75,12 +75,30 @@ object LogRedactor {
* 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_STATE = Regex("(?i)(OnLoginStateChange:? )([^\\s<]\\S*)")
private val LOGIN_USERS = Regex("(OnLoginUsersChanged )(\\S.*)$")
+ /**
+ * An account name as a field: `AccountName`, `account_name`, `username` (`"AccountName"
+ * "someone"` in a VDF, `account_name=...`, `"username": "..."`) and `login` - the last only
+ * as `login=`, a quoted key or a VDF pair, so "Login: OnLoginStateChange ..." keeps its label.
+ * A quoted value is blanked whole; one already blanked is left as it is.
+ */
+ private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)"
+ private val ACCOUNT_KV = Regex(
+ "(?i)(? = emptyList()
+ private var accounts: List = emptyList()
/**
* Learns every Steam account on the device from the client's loginusers.vdf - its AccountName
@@ -88,12 +106,13 @@ object LogRedactor {
* Names under three characters are skipped: blanking every "a" would ruin a log.
*/
fun learnAccounts(loginUsers: java.io.File) {
- val found = ArrayList()
+ val found = ArrayList()
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)(? = emptyList()
+ private var own: List = emptyList()
/**
* Learns the device's addresses from the link file the app writes for the session
@@ -118,7 +137,7 @@ object LogRedactor {
* private, link-local and loopback addresses identify nobody and are left out.
*/
fun learnOwnAddresses(linkFile: java.io.File) {
- val found = ArrayList()
+ val found = ArrayList()
try {
if (linkFile.isFile) linkFile.forEachLine { line ->
val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine
@@ -127,9 +146,12 @@ object LogRedactor {
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)(? found += Regex("(? found += Learned(Regex("(? out.write(redact(line)); out.write("\n") }
}
+ /**
+ * The last pass for a file going into a shared zip: [redact], then the rules the stores' log
+ * uses too ([SecretScrub]) - URLs without query, fragment and user:password and with any
+ * token-bearing path segment blanked, token values and Authorization / Cookie headers blanked
+ * - and private IPv4 addresses as ``. A line already clean comes out unchanged.
+ */
+ fun redactForShare(line: String): String {
+ if (line.isEmpty()) return line
+ return try {
+ val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "")
+ LAN_IPV4.replace(out, "")
+ } catch (t: Throwable) {
+ ""
+ }
+ }
+
+ /** [src]'s lines through [redactForShare], to [out]: the pass every text file in a shared zip gets. */
+ fun scrubForShare(src: java.io.File, out: java.io.Writer) {
+ src.forEachLine { line -> out.write(redactForShare(line)); out.write("\n") }
+ }
+
+ /** ``, inside [value]'s quotes when it had them. */
+ private fun quoted(value: String): String {
+ val q = value.first().takeIf { it == '"' || it == '\'' }?.toString().orEmpty()
+ return "$q$q"
+ }
+
+ /**
+ * A line on its way through [redact]. Each rule runs only on a line holding what it cannot match
+ * without - a word, enough separators, a long enough run: most of a Steam log is lines no rule
+ * touches, and a session's logs went through every rule at about a megabyte a second. A line with anything but ASCII in it goes through
+ * every case-insensitive rule, since Android's regex folds case more widely than lowercase().
+ */
+ private class Line(var text: String) {
+ private val unfolded = text.any { it.code >= 0x80 }
+ private var lower: String? = null
+
+ fun has(vararg words: String): Boolean {
+ if (unfolded) return true
+ val folded = lower ?: text.lowercase().also { lower = it }
+ return words.any { folded.contains(it) }
+ }
+
+ fun set(next: String) {
+ if (next != text) {
+ text = next
+ lower = null
+ }
+ }
+
+ fun holds(c: Char, times: Int): Boolean {
+ var n = 0
+ for (ch in text) if (ch == c && ++n >= times) return true
+ return false
+ }
+
+ inline fun hasRun(length: Int, inRun: (Char) -> Boolean): Boolean {
+ var n = 0
+ for (ch in text) if (!inRun(ch)) n = 0 else if (++n >= length) return true
+ return false
+ }
+ }
+
+ private fun isHex(c: Char) = c in '0'..'9' || c in 'a'..'f' || c in 'A'..'F'
+
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
fun redact(line: String): String {
if (line.isEmpty()) return line
return try {
- var out = line
- out = MAC_FIELD.replace(out) { "${it.groupValues[1]}" }
- out = MAC.replace(out, "")
- out = DEVICE_IDENTIFIER.replace(out) {
+ val out = Line(line)
+ if (out.has("mac")) out.set(MAC_FIELD.replace(out.text) { "${it.groupValues[1]}" })
+ if (out.holds(':', 5) || out.holds('-', 5)) out.set(MAC.replace(out.text, ""))
+ if (out.has("serial", "android")) out.set(DEVICE_IDENTIFIER.replace(out.text) {
val value = it.groupValues[2]
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
"${it.groupValues[1]}${quote}${quote}"
+ })
+ if (out.holds('-', 4)) out.set(GUID.replace(out.text, ""))
+ if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}" })
+ if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, ""))
+ if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) {
+ out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}" })
}
- out = GUID.replace(out, "")
- out = JWT_LABELLED.replace(out) { "${it.groupValues[1]}" }
- out = JWT_BASE64.replace(out, "")
- out = SECRET_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}" }
- out = GUARD_CODE.replace(out) { "${it.groupValues[1]}" }
- out = WEBAPI_KEY.replace(out, "")
+ if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}" })
+ if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, ""))
// Mask, not delete: the last four digits let a reader correlate lines to one account.
- out = STEAMID64.replace(out) { "${it.groupValues[1]}********${it.groupValues[3]}" }
- out = STEAMID3.replace(out) { m ->
+ if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" })
+ if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m ->
val id = m.groupValues[1]
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
+ })
+ if (out.has("external")) out.set(EXTERNAL_ADDR.replace(out.text) { "${it.groupValues[1]}" })
+ for (r in own) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, ""))
+ if (out.has("onloginstatechange")) out.set(LOGIN_STATE.replace(out.text) { "${it.groupValues[1]}" })
+ if ("OnLoginUsersChanged " in out.text) out.set(LOGIN_USERS.replace(out.text) { "${it.groupValues[1]}" })
+ if (out.has("account", "user")) {
+ out.set(ACCOUNT_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
}
- out = EXTERNAL_ADDR.replace(out) { "${it.groupValues[1]}" }
- for (r in own) out = r.replace(out, "")
- out = LOGIN_STATE.replace(out) { "${it.groupValues[1]}" }
- out = LOGIN_USERS.replace(out) { "${it.groupValues[1]}" }
- for (r in accounts) out = r.replace(out, "")
- out = EMAIL.replace(out, "")
- out = RESIDUAL.replace(out) { "${it.groupValues[1]}=" }
- out = LONG_TOKEN.replace(out, "")
- out
+ if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
+ for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, ""))
+ if ('@' in out.text) out.set(EMAIL.replace(out.text, ""))
+ if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) {
+ out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=" })
+ }
+ if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) {
+ out.set(LONG_TOKEN.replace(out.text, ""))
+ }
+ out.text
} catch (t: Throwable) {
// A log line is never worth crashing a session over, but an unscrubbed one must not
// reach the file either.
diff --git a/app/src/main/java/com/droiddeck/launcher/core/SecretScrub.kt b/app/src/main/java/com/droiddeck/launcher/core/SecretScrub.kt
new file mode 100644
index 0000000000..c91ca60ef9
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/core/SecretScrub.kt
@@ -0,0 +1,72 @@
+package com.droiddeck.launcher.core
+
+/**
+ * The one set of rules that keeps URLs and tokens out of anything the app writes or shares: the
+ * stores' log ([com.droiddeck.launcher.stores.StoreLog.redactLine]) and the last pass over every
+ * text file in a shared log zip ([LogRedactor.redactForShare]).
+ *
+ * - Every URL loses its query, fragment and `user:password@`. [Urls.SHORT] then keeps only the host
+ * and a plain first path segment (the stores' lines, where a GOG secure link carries its token in
+ * the path); [Urls.KEEP_PATH] keeps the path but blanks any segment that carries a token.
+ * - Outside URLs, the values of token-like keys (`token`, `__token__`, `f_token`, `hdnts`, access /
+ * refresh / id tokens; exchange and authorization codes of four characters or more, and a bare
+ * `code=` where it is one: in a query string or on a line with OAuth keys such as `client_id`,
+ * `redirect_uri` or `state`, never an 8-hex exception code like Proton's `code=c0000005`) and of
+ * Authorization / Cookie headers are blanked with [mark].
+ *
+ * A line already scrubbed comes out unchanged.
+ */
+object SecretScrub {
+ enum class Urls { SHORT, KEEP_PATH }
+
+ private val URL = Regex("""[A-Za-z][A-Za-z0-9+.\-]*://[^\s"'<>]+""")
+ private val SAFE_SEGMENT = Regex("""[A-Za-z0-9._\-]{1,40}""")
+ private val TOKEN_SEGMENT = Regex("""(?i)(token|hdnts|hmac|signature|sig|exp)=""")
+ private val TOKEN = Regex("""(?i)(?}]+""")
+ /** Codes that are only ever OAuth grants. */
+ private val GRANT_CODE = Regex("""(?i)(?}]{4,}""")
+ /** A bare `code=`: a grant only right after `?` / `&` (a query string) or beside OAuth keys ([OAUTH_CONTEXT]). */
+ private val CODE = Regex("""(?i)(?}]{4,})""")
+ private val OAUTH_CONTEXT = Regex("""(?i)(? if (urls == Urls.SHORT) short(m.value) else keepPath(m.value, mark) }
+ out = TOKEN.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark }
+ out = GRANT_CODE.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark }
+ val oauth = OAUTH_CONTEXT.containsMatchIn(text)
+ val src = out
+ out = CODE.replace(src) { m ->
+ val inQuery = m.range.first > 0 && src[m.range.first - 1] in "?&"
+ val grant = !STATUS_CODE.matches(m.groupValues[3]) && (oauth || inQuery)
+ if (grant) m.groupValues[1] + m.groupValues[2] + mark else m.value
+ }
+ out = HEADER.replace(out) { m -> m.groupValues[1] + m.groupValues[2] + mark }
+ return out
+ }
+
+ private fun split(url: String): Triple