Compare commits

..
97 changed files with 808 additions and 2525 deletions

No files matched your search

@@ -205,19 +205,15 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
acquire = exp.fd;
} else {
} else if (dmabuf_fd >= 0) {
if (!g_export_failed_logged) {
g_export_failed_logged = 1;
droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s",
dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd",
draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU");
droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_EXPORT_SYNC_FILE failed (%s): waiting for each frame on the CPU instead",
strerror(errno));
}
if (dmabuf_fd >= 0) {
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
if (draw) return -1;
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
}
int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw,
s ? droiddeck_surface_color(s) : NULL, ab->format);
+16 -223
View File
@@ -2272,69 +2272,6 @@ static void bind_output(struct wl_client *c, void *data, uint32_t ver, uint32_t
struct draw_list { struct vkp_draw *d; int n, cap; };
#define ZERO_COPY_FALLBACK_SIGNATURES 32u
enum zero_copy_fallback_reason {
ZERO_COPY_NO_SURFACE_BUFFER = 1,
ZERO_COPY_NO_GRALLOC_AHB = 2,
ZERO_COPY_AHB_PRESENT_FAILED = 3
};
struct zero_copy_fallback_signature {
uint32_t reason, format, stride, offset;
int width, height;
uint64_t modifier;
};
static struct zero_copy_fallback_signature g_zero_copy_fallbacks[ZERO_COPY_FALLBACK_SIGNATURES];
static uint32_t g_zero_copy_fallback_count;
static int g_zero_copy_fallback_limit_logged;
static int zero_copy_fallback_should_log(const struct dmabuf_buffer *b, uint32_t reason) {
const struct zero_copy_fallback_signature key = {
.reason = reason, .format = b ? b->format : 0,
.stride = b && b->n_planes ? b->stride[0] : 0,
.offset = b && b->n_planes ? b->offset[0] : 0,
.width = b ? b->width : 0, .height = b ? b->height : 0,
.modifier = b ? b->modifier : 0};
for (uint32_t i = 0; i < g_zero_copy_fallback_count; i++) {
const struct zero_copy_fallback_signature *seen = &g_zero_copy_fallbacks[i];
if (seen->reason == key.reason && seen->format == key.format && seen->stride == key.stride &&
seen->offset == key.offset && seen->width == key.width && seen->height == key.height &&
seen->modifier == key.modifier)
return 0;
}
if (g_zero_copy_fallback_count >= ZERO_COPY_FALLBACK_SIGNATURES) {
if (!g_zero_copy_fallback_limit_logged) {
g_zero_copy_fallback_limit_logged = 1;
droiddeck_log("layer", "zero-copy: further fallback diagnostics suppressed after %u distinct buffer signatures",
ZERO_COPY_FALLBACK_SIGNATURES);
}
return 0;
}
g_zero_copy_fallbacks[g_zero_copy_fallback_count++] = key;
return 1;
}
static void note_zero_copy_fallback(struct surface *s, const struct dmabuf_buffer *b, uint32_t reason,
int scene_w, int scene_h, int present_result) {
if (!zero_copy_fallback_should_log(b, reason)) return;
char name[160] = "unknown surface";
if (s) describe(s, name, sizeof(name));
if (reason == ZERO_COPY_NO_SURFACE_BUFFER) {
droiddeck_log("layer", "zero-copy: layer candidate %s has no associated Wayland surface buffer; using the layer-copy path",
name);
} else {
droiddeck_log("layer", "zero-copy: %s buffer %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx %s; "
"scene %dx%d will use the layer-copy path (direct-present result %d)",
name, b->format & 0xff, (b->format >> 8) & 0xff, (b->format >> 16) & 0xff,
(b->format >> 24) & 0xff, b->width, b->height,
b->n_planes ? b->stride[0] : 0, b->n_planes ? b->offset[0] : 0,
(unsigned long long)b->modifier,
reason == ZERO_COPY_NO_GRALLOC_AHB
? "has no registered gralloc AHardwareBuffer"
: "has a registered gralloc AHardwareBuffer but direct presentation failed",
scene_w, scene_h, present_result);
}
}
static int add_cursor(struct draw_list *dl, int scene_w);
static struct vkp_image *surface_image(struct surface *s) {
@@ -2454,53 +2391,17 @@ static int black_fill_below(const struct draw_list *dl, int n) {
return 1;
}
#define LAYER_CANDIDATE_DIAGNOSTICS 32u
static unsigned g_layer_candidate_diag_count;
static int g_layer_candidate_diag_limit;
static void note_layer_candidate_skip(const struct vkp_draw *d, int index, int reason,
int scene_w, int scene_h) {
static int seen[LAYER_CANDIDATE_DIAGNOSTICS][8];
const int key[8] = {index, reason, scene_w, scene_h, d->dx, d->dy, d->dw, d->dh};
for (unsigned i = 0; i < g_layer_candidate_diag_count; i++)
if (!memcmp(seen[i], key, sizeof(key))) return;
if (g_layer_candidate_diag_count >= LAYER_CANDIDATE_DIAGNOSTICS) {
if (!g_layer_candidate_diag_limit++) droiddeck_log("layer", "zero-copy: further candidate-rejection details suppressed after %u signatures",
LAYER_CANDIDATE_DIAGNOSTICS);
return;
}
memcpy(seen[g_layer_candidate_diag_count++], key, sizeof(key));
const char *why = reason == 1 ? "translucent draw" :
reason == 2 ? "image is not DMA-BUF" :
reason == 3 ? "source rectangle is outside/invalid" :
reason == 4 ? "draw rectangle is outside scene or invalid" :
"not fullscreen and no black backing below";
droiddeck_log("layer", "zero-copy: candidate draw %d rejected: %s; scene %dx%d, dst %dx%d at %d,%d, src %.2f,%.2f %.2fx%.2f, image %dx%d",
index, why, scene_w, scene_h, d->dw, d->dh, d->dx, d->dy,
d->sx, d->sy, d->sw, d->sh, vkp_image_width(d->img), vkp_image_height(d->img));
}
static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) {
for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) {
const struct vkp_draw *d = &dl->d[i];
if (d->blend) { note_layer_candidate_skip(d, i, 1, scene_w, scene_h); continue; }
if (!vkp_image_is_dmabuf(d->img)) { note_layer_candidate_skip(d, i, 2, scene_w, scene_h); continue; }
if (d->blend) continue;
if (!vkp_image_is_dmabuf(d->img)) continue;
if (d->sx < 0 || d->sy < 0 || d->sw < 1.0f || d->sh < 1.0f ||
d->sx + d->sw >= vkp_image_width(d->img) + 1.0f ||
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) {
note_layer_candidate_skip(d, i, 3, scene_w, scene_h);
continue;
}
d->sy + d->sh >= vkp_image_height(d->img) + 1.0f) continue;
if (d->dx == 0 && d->dy == 0 && d->dw == scene_w && d->dh == scene_h) return i;
if (d->dx < 0 || d->dy < 0 || d->dw <= 0 || d->dh <= 0 || d->dx + d->dw > scene_w ||
d->dy + d->dh > scene_h) {
note_layer_candidate_skip(d, i, 4, scene_w, scene_h);
continue;
}
if (!black_fill_below(dl, i)) {
note_layer_candidate_skip(d, i, 5, scene_w, scene_h);
continue;
}
d->dy + d->dh > scene_h || !black_fill_below(dl, i)) continue;
return i;
}
return -1;
@@ -2521,56 +2422,6 @@ static void note_copy_scene(const struct draw_list *dl, int scene_w, int scene_h
vkp_image_is_dmabuf(t->img) ? "GPU" : "memory", t->blend ? ", translucent" : "");
}
static struct surface *surface_for_image(const struct vkp_image *img);
static void note_layer_candidate_rejected(const struct draw_list *dl, int scene_w, int scene_h) {
static int seen[32][14];
static unsigned seen_count;
static int limit_logged;
static time_t window_start;
struct timespec now_ts;
const struct vkp_draw *a = dl->n > 0 ? &dl->d[dl->n - 1] : NULL;
const struct vkp_draw *b = dl->n > 1 ? &dl->d[dl->n - 2] : NULL;
struct surface *sa = a ? surface_for_image(a->img) : NULL;
struct surface *sb = b ? surface_for_image(b->img) : NULL;
const int signature[14] = {
dl->n, scene_w, scene_h,
a ? a->dw : 0, a ? a->dh : 0,
a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0,
a ? vkp_image_is_dmabuf(a->img) : 0, a ? a->blend : 0, sa && sa->dmabuf_buf ? 1 : 0,
b ? b->dw : 0, b ? b->dh : 0, b ? vkp_image_is_dmabuf(b->img) : 0, sb && sb->dmabuf_buf ? 1 : 0
};
clock_gettime(CLOCK_MONOTONIC, &now_ts);
if (!window_start || now_ts.tv_sec - window_start >= 30) {
seen_count = 0;
limit_logged = 0;
window_start = now_ts.tv_sec;
}
for (unsigned i = 0; i < seen_count; i++)
if (!memcmp(signature, seen[i], sizeof(signature))) return;
if (seen_count >= 32) {
if (!limit_logged++) droiddeck_log("layer", "zero-copy: further fullscreen-candidate rejection details suppressed after 32 signatures in 30 seconds");
return;
}
memcpy(seen[seen_count++], signature, sizeof(signature));
char below[48];
if (b)
snprintf(below, sizeof(below), "%s %dx%d",
vkp_image_is_dmabuf(b->img) ? "DMA-BUF" : "non-DMA-BUF", b->dw, b->dh);
else
snprintf(below, sizeof(below), "none");
droiddeck_log("layer", "zero-copy: no eligible fullscreen DMA-BUF layer candidate: scene %dx%d, %d draws; "
"top draw %dx%d at %d,%d image %dx%d %s%s surface=%s dmabuf=%s; "
"draw below %s",
scene_w, scene_h, dl->n, a ? a->dw : 0, a ? a->dh : 0, a ? a->dx : 0, a ? a->dy : 0,
a ? vkp_image_width(a->img) : 0, a ? vkp_image_height(a->img) : 0,
a && vkp_image_is_dmabuf(a->img) ? "DMA-BUF" : "non-DMA-BUF",
a && a->blend ? " blended" : "",
sa ? "associated" : "unassociated",
sa && sa->dmabuf_buf ? "yes" : "no",
below);
}
static struct surface *surface_for_image(const struct vkp_image *img) {
struct surface *s;
wl_list_for_each(s, &g_surfaces, link)
@@ -2579,56 +2430,16 @@ static struct surface *surface_for_image(const struct vkp_image *img) {
}
static struct surface *ahb_layer_only_candidate(int scene_w, int scene_h) {
static struct {
const struct surface *surface;
int reason, scene_w, scene_h, w, h, buf_w, buf_h, x, y, src_set, dst_set, children;
} seen[32];
static unsigned seen_count;
static int limit_logged;
struct surface *s;
int w = 0, h = 0, reason = 0;
int w, h;
if (wl_list_empty(&g_toplevels)) return NULL;
s = wl_container_of(g_toplevels.prev, s, toplevel_link);
if (!s->dmabuf_buf) reason = 1;
else if (s->dmabuf_buf->img) reason = 2;
else if (!ahb_swapchain_has_ahb(s->dmabuf_buf)) reason = 3;
else if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) reason = 4;
else if (!wl_list_empty(&s->children)) reason = 5;
else if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) reason = 6;
if (!s->dmabuf_buf || s->dmabuf_buf->img || !ahb_swapchain_has_ahb(s->dmabuf_buf)) return NULL;
if ((g_desktop && !s->placed) || s->x != 0 || s->y != 0 || s->src_set || s->dst_set) return NULL;
if (!wl_list_empty(&s->children)) return NULL;
if (g_hide_shell && !strcmp(client_name(wl_resource_get_client(s->resource)), "explorer.exe")) return NULL;
surface_size(s, &w, &h);
if (!reason && (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h)) reason = 7;
if (reason) {
int found = 0;
for (unsigned i = 0; i < seen_count; i++) {
if (seen[i].surface == s && seen[i].reason == reason && seen[i].scene_w == scene_w &&
seen[i].scene_h == scene_h && seen[i].w == w && seen[i].h == h &&
seen[i].buf_w == s->buf_w && seen[i].buf_h == s->buf_h && seen[i].x == s->x &&
seen[i].y == s->y && seen[i].src_set == s->src_set && seen[i].dst_set == s->dst_set &&
seen[i].children == !wl_list_empty(&s->children)) { found = 1; break; }
}
if (!found && seen_count < 32) {
seen[seen_count].surface = s; seen[seen_count].reason = reason;
seen[seen_count].scene_w = scene_w; seen[seen_count].scene_h = scene_h;
seen[seen_count].w = w; seen[seen_count].h = h; seen[seen_count].buf_w = s->buf_w; seen[seen_count].buf_h = s->buf_h;
seen[seen_count].x = s->x; seen[seen_count].y = s->y; seen[seen_count].src_set = s->src_set;
seen[seen_count].dst_set = s->dst_set; seen[seen_count].children = !wl_list_empty(&s->children);
seen_count++;
const char *why = reason == 1 ? "no DMA-BUF buffer" :
reason == 2 ? "buffer is already importable by Vulkan" :
reason == 3 ? "no registered gralloc AHardwareBuffer" :
reason == 4 ? "surface is positioned/cropped/scaled" :
reason == 5 ? "surface has child surfaces" :
reason == 6 ? "hidden shell surface" : "surface or buffer dimensions differ from scene";
char name[160]; describe(s, name, sizeof(name));
droiddeck_log("layer", "zero-copy: AHardwareBuffer-only candidate rejected: %s; %s, scene %dx%d, surface %dx%d at %d,%d, buffer %dx%d, crop=%d destination=%d children=%d",
why, name, scene_w, scene_h, w, h, s->x, s->y, s->buf_w, s->buf_h,
s->src_set, s->dst_set, !wl_list_empty(&s->children));
} else if (!found && !limit_logged) {
limit_logged = 1;
droiddeck_log("layer", "zero-copy: further AHardwareBuffer-only candidate diagnostics suppressed after 32 signatures");
}
return NULL;
}
if (w != scene_w || h != scene_h || s->buf_w != scene_w || s->buf_h != scene_h) return NULL;
return s;
}
@@ -3071,10 +2882,7 @@ static void render_scene(void) {
struct surface *ls = li >= 0 ? surface_for_image(dl.d[li].img) : NULL;
const struct vkp_draw *ld = li >= 0 ? &dl.d[li] : NULL;
if (li < 0) ls = layer_only;
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) {
if (!cursor_on && !bfi) note_layer_candidate_rejected(&dl, w, h);
note_copy_scene(&dl, w, h, cursor_on);
}
if (g_zero_copy && li < 0 && !ls && !blocked && !cardboard) note_copy_scene(&dl, w, h, cursor_on);
if (cardboard) ls = NULL;
if (cursor_on) ls = NULL;
if (bfi) ls = NULL;
@@ -3102,30 +2910,15 @@ static void render_scene(void) {
r = generated >= 0 ? 0 : -1;
else if (generated >= 0 && !(fx_on && li >= 0) && ls && ls->dmabuf_buf && ahb_swapchain_has_ahb(ls->dmabuf_buf))
r = ahb_swapchain_present(ls->dmabuf_buf, ls, w, h, ld);
if (!fg_pass && generated >= 0 && !fx_on && !framegen && r != 0) {
if (!ls || !ls->dmabuf_buf)
note_zero_copy_fallback(ls, NULL, ZERO_COPY_NO_SURFACE_BUFFER, w, h, r);
else if (!ahb_swapchain_has_ahb(ls->dmabuf_buf))
note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_NO_GRALLOC_AHB, w, h, r);
else
note_zero_copy_fallback(ls, ls->dmabuf_buf, ZERO_COPY_AHB_PRESENT_FAILED, w, h, r);
}
if (r == 0 && !fg_pass) g_zero_copy_shown = ls;
else settle_unwaited();
int ov = 0, ov_done = 0;
if (!fg_pass && generated >= 0 && r != 0 && li >= 0) {
if (fx_on) {
r = sc_layer_present_pass(&dl.d[li], 1, w, h);
} else {
r = sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL,
over == 1 ? &dl.d[li + 1] : NULL, &ov);
ov_done = 1;
}
}
if (!fg_pass && generated >= 0 && r != 0 && li >= 0)
r = fx_on ? sc_layer_present_pass(&dl.d[li], 1, w, h)
: sc_layer_present(dl.d[li].img, w, h, ld, ls ? droiddeck_surface_color(ls) : NULL);
if (r == 0) {
if (ls) ls->drawn = 1;
int go[8];
if (!ov_done && over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
int go[8], ov = 0;
if (over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
ov = sc_layer_present_overlay(dl.d[li + 1].img, go, dl.d[li + 1].blend) == 0 ? 1 : -1;
if (ov <= 0) sc_layer_hide_overlay();
if (ov < 0) {
@@ -62,40 +62,8 @@ struct entry {
static struct wl_list g_entries;
static struct wl_event_loop *g_loop;
static uint64_t g_next_id = 1;
static int g_refused_logged;
static int g_ubwc_promised;
#define DISPLAY_BUFFER_MISMATCH_SIGNATURES 64u
struct display_buffer_mismatch_signature {
uint32_t kind, format, stride, offset;
int width, height;
uint64_t modifier;
};
static struct display_buffer_mismatch_signature g_mismatch_signatures[DISPLAY_BUFFER_MISMATCH_SIGNATURES];
static uint32_t g_mismatch_signature_count;
static int g_mismatch_limit_logged;
static int mismatch_should_log(const struct dmabuf_buffer *b, uint32_t kind) {
const struct display_buffer_mismatch_signature key = {
.kind = kind, .format = b->format, .stride = b->stride[0], .offset = b->offset[0],
.width = b->width, .height = b->height, .modifier = b->modifier};
for (uint32_t i = 0; i < g_mismatch_signature_count; i++) {
const struct display_buffer_mismatch_signature *seen = &g_mismatch_signatures[i];
if (seen->kind == key.kind && seen->format == key.format && seen->stride == key.stride &&
seen->offset == key.offset && seen->width == key.width && seen->height == key.height &&
seen->modifier == key.modifier)
return 0;
}
if (g_mismatch_signature_count >= DISPLAY_BUFFER_MISMATCH_SIGNATURES) {
if (!g_mismatch_limit_logged) {
g_mismatch_limit_logged = 1;
droiddeck_log("layer", "display buffers: further mismatch diagnostics suppressed after %u distinct buffer signatures",
DISPLAY_BUFFER_MISMATCH_SIGNATURES);
}
return 0;
}
g_mismatch_signatures[g_mismatch_signature_count++] = key;
return 1;
}
static int g_ubwc_probed[2];
static uint32_t ahb_format_of(uint32_t drm, uint64_t modifier) {
@@ -270,51 +238,16 @@ static void handle_alloc(struct peer *p, const struct display_buffers_request *q
} else {
if (ahb) AHardwareBuffer_release(ahb);
fd = -1;
static struct {
pid_t pid;
uint32_t width, height, format, stride, offset, reason;
uint64_t size, modifier;
} refused[32];
static unsigned refused_count;
static int refused_limit_logged;
uint32_t reason = !sized ? 1u : !sane ? 2u : !wanted ? 3u :
!ahb_swapchain_advertised() ? 4u :
p->count >= DISPLAY_BUFFERS_MAX_PER_CLIENT ? 5u : 6u;
int seen = 0;
for (unsigned i = 0; i < refused_count; i++) {
if (refused[i].pid == p->pid && refused[i].width == q->width && refused[i].height == q->height &&
refused[i].format == q->format && refused[i].stride == q->stride && refused[i].offset == q->offset &&
refused[i].size == q->size && refused[i].modifier == q->modifier && refused[i].reason == reason) {
seen = 1;
break;
}
}
if (!seen && refused_count < 32) {
refused[refused_count].pid = p->pid;
refused[refused_count].width = q->width;
refused[refused_count].height = q->height;
refused[refused_count].format = q->format;
refused[refused_count].stride = q->stride;
refused[refused_count].offset = q->offset;
refused[refused_count].size = q->size;
refused[refused_count].modifier = q->modifier;
refused[refused_count].reason = reason;
refused_count++;
const char *why = reason == 1 ? "invalid dimensions, format, or stride" :
reason == 2 ? "size/offset/layout sanity check failed" :
reason == 3 ? "zero-copy or UBWC offering is disabled" :
reason == 4 ? "AHardwareBuffer swapchain is not advertised" :
reason == 5 ? "per-client allocation limit reached" :
"gralloc allocation/fd/size validation failed";
droiddeck_log(compressed ? "error" : "layer",
"display buffers: allocation refused for pid %d: %s; request %ux%u %c%c%c%c %s stride=%u offset=%u size=%llu modifier=0x%llx (client has %d allocations)",
(int)p->pid, why, q->width, q->height,
q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff,
compressed ? "UBWC" : "linear", q->stride, q->offset,
(unsigned long long)q->size, (unsigned long long)q->modifier, p->count);
} else if (!seen && !refused_limit_logged) {
refused_limit_logged = 1;
droiddeck_log("layer", "display buffers: further allocation-refusal diagnostics suppressed after 32 signatures");
if (sized && wanted && (compressed || !g_refused_logged)) {
g_refused_logged = 1;
droiddeck_log(compressed ? "error" : "layer", "display buffers: no gralloc buffer matches pid %d's %ux%u "
"%c%c%c%c %s layout (stride %u bytes, pixels at %u, %llu bytes; gralloc's layout has pixels at "
"%llu, %llu bytes): %s", (int)p->pid, q->width, q->height,
q->format & 0xff, (q->format >> 8) & 0xff, (q->format >> 16) & 0xff, (q->format >> 24) & 0xff,
compressed ? "UBWC" : "linear", q->stride, q->offset, (unsigned long long)q->size,
(unsigned long long)(compressed ? ubwc_meta_size(q->width, q->height) : 0),
(unsigned long long)(compressed ? ubwc_size(q->width, q->height, q->stride) : q->size),
compressed ? "its compressed frames cannot be shown" : "its frames keep the copy path");
}
}
if (reply(p, &r, fd) != 0 && e) entry_free(e);
@@ -366,18 +299,9 @@ static int on_listen(int fd, uint32_t mask, void *data) {
}
void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, struct dmabuf_buffer *b) {
static int invalid_logged;
struct stat st;
struct entry *e;
if (!g_loop || wl_list_empty(&g_entries)) return;
if (b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) {
if (!invalid_logged) {
invalid_logged = 1;
droiddeck_log("layer", "display buffers: cannot associate %s's DMA-BUF with gralloc (plane count %u; expected one plane at offset 0, or fstat failed)",
droiddeck_client_name(c), b->n_planes);
}
return;
}
if (!g_loop || wl_list_empty(&g_entries) || b->n_planes != 1 || b->offset[0] != 0 || fstat(b->fd[0], &st) != 0) return;
wl_list_for_each(e, &g_entries, link) {
if (e->dev != st.st_dev || e->ino != st.st_ino) continue;
AHardwareBuffer_Desc d;
@@ -387,27 +311,11 @@ void display_buffers_match(struct wl_client *c, struct wl_resource *buffer, stru
(uint32_t)b->height == e->height
: (b->modifier == MOD_LINEAR || b->modifier == MOD_INVALID) &&
e->stride == b->stride[0];
const uint32_t expected_format = ahb_format_of(b->format, e->modifier);
const int dimensions = b->width > 0 && b->height > 0 &&
(uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height;
if (laid_out && e->format == expected_format && dimensions) {
if (laid_out && e->format == ahb_format_of(b->format, e->modifier) && b->width > 0 && b->height > 0 &&
(uint32_t)b->width <= d.width && (uint32_t)b->height <= d.height)
ahb_swapchain_adopt(c, buffer, b, e->ahb, e->modifier);
} else if (mismatch_should_log(b, 2)) {
droiddeck_log("layer", "display buffers: gralloc DMA-BUF identity matched but layout was rejected for %s: %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx; gralloc %ux%u stride %u format 0x%x, expected format 0x%x (layout %s, dimensions %s)",
droiddeck_client_name(c), b->format & 0xff, (b->format >> 8) & 0xff,
(b->format >> 16) & 0xff, (b->format >> 24) & 0xff, b->width, b->height,
b->stride[0], b->offset[0], (unsigned long long)b->modifier,
e->width, e->height, e->stride, e->format, expected_format,
laid_out ? "ok" : "mismatch", dimensions ? "ok" : "mismatch");
}
return;
}
if (mismatch_should_log(b, 1)) {
droiddeck_log("layer", "display buffers: no registered gralloc allocation matches %s's DMA-BUF identity: %c%c%c%c %dx%d stride %u offset %u modifier 0x%llx; imported normally, copy path only",
droiddeck_client_name(c), b->format & 0xff, (b->format >> 8) & 0xff,
(b->format >> 16) & 0xff, (b->format >> 24) & 0xff, b->width, b->height,
b->stride[0], b->offset[0], (unsigned long long)b->modifier);
}
}
void display_buffers_init(struct wl_display *display) {
+14 -58
View File
@@ -187,8 +187,6 @@ struct layer {
static struct layer g_layers[SC_LAYER_COUNT];
static void apply_frame_rate(ASurfaceTransaction *tx, struct layer *l);
static void coverage_text(const struct layer *l, char *out, size_t n);
static int overlay_slot(struct layer *l, struct vkp_image *src, int *idx, int *wait_fd);
static int overlay_shown(struct layer *l, int idx, const int geo[8], int translucent);
static int g_layers_ready;
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static int g_pending_cb;
@@ -723,15 +721,9 @@ static int layer_geometry(int w, int h, int scene_w, int scene_h, const struct v
static ARect g_game_src, g_game_dst;
static int g_game_geo_known;
static void note_game_geometry(const int r[8]) {
g_game_src = (ARect){r[0], r[1], r[2], r[3]};
g_game_dst = (ARect){r[4], r[5], r[6], r[7]};
g_game_geo_known = 1;
}
static void apply_geometry(ASurfaceTransaction *tx, struct layer *l, const int r[8]) {
ARect srcR = {r[0], r[1], r[2], r[3]}, dstR = {r[4], r[5], r[6], r[7]};
if (l == &g_layers[SC_LAYER_GAME]) note_game_geometry(r);
if (l == &g_layers[SC_LAYER_GAME]) { g_game_src = srcR; g_game_dst = dstR; g_game_geo_known = 1; }
if (!l->geo_valid || memcmp(&srcR, &l->geo_src, sizeof(srcR)) || memcmp(&dstR, &l->geo_dst, sizeof(dstR))) {
api.setGeometry(tx, l->sc, &srcR, &dstR, 0 );
l->geo_src = srcR; l->geo_dst = dstR; l->geo_valid = 1;
@@ -1006,40 +998,19 @@ unavailable:
}
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw,
const struct droiddeck_color *color, const struct vkp_draw *over, int *over_shown) {
const struct droiddeck_color *color) {
struct layer *l = layer_of(SC_LAYER_GAME);
*over_shown = 0;
if (!src || ensure_sc(l) != 0) return -1;
int sw = vkp_image_width(src), sh = vkp_image_height(src);
int r[8];
int g = layer_geometry(sw, sh, scene_w, scene_h, draw, r);
if (g < 0) return -1;
int og[8];
if (over && !vkp_map_draw(over, og)) over = NULL;
if (g == 0) {
sc_layer_hide();
if (over) *over_shown = sc_layer_present_overlay(over->img, og, over->blend) == 0 ? 1 : -1;
return 0;
}
if (g == 0) { sc_layer_hide(); return 0; }
struct vkp_blit blits[2] = {{.src = src, .wait_fd = -1}, {.src = over ? over->img : NULL, .wait_fd = -1}};
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &blits[0].wait_fd);
if (idx < 0) {
log_drop(l);
if (g_alloc_failed) return -1;
if (over) *over_shown = sc_layer_present_overlay(over->img, og, over->blend) == 0 ? 1 : -1;
return 0;
}
blits[0].dst = l->slots[idx].img;
struct layer *ol = layer_of(SC_LAYER_OVERLAY);
int over_idx = -1;
if (over) {
note_game_geometry(r);
const int taken = overlay_slot(ol, over->img, &over_idx, &blits[1].wait_fd);
*over_shown = taken < 0 ? -1 : 1;
if (taken > 0) blits[1].dst = ol->slots[over_idx].img;
}
if (vkp_blit_images(blits, over_idx >= 0 ? 2 : 1) != 0) return -1;
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
if (present_slot(l, idx, r, color, 0) != 0) return -1;
if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8);
if (!l->first_logged) {
@@ -1049,7 +1020,6 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
pool_kind(l->pool_modifier), l->pool_n);
}
vkp_signal_first_frame();
if (over_idx >= 0 && overlay_shown(ol, over_idx, og, over->blend) != 0) *over_shown = -1;
return 0;
}
@@ -1239,19 +1209,17 @@ int sc_layer_overlay_affordable(void) {
return ok;
}
static int overlay_slot(struct layer *l, struct vkp_image *src, int *idx, int *wait_fd) {
*wait_fd = -1;
if (!src) return -1;
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) {
struct layer *l = layer_of(SC_LAYER_OVERLAY);
if (!src || !geo) return -1;
if (!sc_layer_overlay_affordable()) return -1;
if (ensure_sc(l) != 0) return -1;
int sw = vkp_image_width(src), sh = vkp_image_height(src);
if (sw <= 0 || sh <= 0) return -1;
*idx = take_free_slot(l, sw, sh, AHB_RGBA8, wait_fd);
if (*idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
return 1;
}
static int overlay_shown(struct layer *l, int idx, const int geo[8], int translucent) {
int wait_fd;
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return g_alloc_failed ? -1 : 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
if (!l->first_logged) {
l->first_logged = 1;
@@ -1260,18 +1228,6 @@ static int overlay_shown(struct layer *l, int idx, const int geo[8], int translu
return 0;
}
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) {
struct layer *l = layer_of(SC_LAYER_OVERLAY);
if (!geo) return -1;
int idx;
struct vkp_blit blit = {.src = src, .wait_fd = -1};
const int taken = overlay_slot(l, src, &idx, &blit.wait_fd);
if (taken <= 0) return taken;
blit.dst = l->slots[idx].img;
if (vkp_blit_images(&blit, 1) != 0) return -1;
return overlay_shown(l, idx, geo, translucent);
}
static int hide_layer(struct layer *l) {
if (!l->sc || !l->shown || api.state != 1) return 0;
ASurfaceTransaction *tx = api.txCreate();
+1 -1
View File
@@ -22,7 +22,7 @@ void sc_layer_hdr_symbols(char *out, size_t size);
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct vkp_draw *draw,
const struct droiddeck_color *color, const struct vkp_draw *over, int *over_shown);
const struct droiddeck_color *color);
int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int scene_h);
int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const struct vkp_hdr_frame *hf,
+27 -62
View File
@@ -20,8 +20,6 @@
#include <unistd.h>
#include <errno.h>
#include <poll.h>
#include <linux/sync_file.h>
#include <sys/ioctl.h>
#include <time.h>
#include <pthread.h>
#include <stdarg.h>
@@ -3164,38 +3162,8 @@ static void blit_to_layer(VkCommandBuffer cmd, VkImage src, VkImageLayout src_la
0, 0, NULL, 0, NULL, 1, &release);
}
static int merge_wait_fds(int a, int b) {
if (a < 0) return b;
if (b < 0) return a;
struct sync_merge_data m = {.name = "droiddeck-layer-copy", .fd2 = b};
if (ioctl(a, SYNC_IOC_MERGE, &m) == 0) {
close(a);
close(b);
return m.fence;
}
struct pollfd p = {.fd = b, .events = POLLIN};
int r;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
close(b);
if (r != 0) return a;
p.fd = a;
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
close(a);
return -2;
}
int vkp_blit_images(const struct vkp_blit *blits, int n) {
int wait_fd = -1;
for (int i = 0; i < n; i++) {
if (wait_fd == -2) { if (blits[i].wait_fd >= 0) close(blits[i].wait_fd); continue; }
wait_fd = merge_wait_fds(wait_fd, blits[i].wait_fd);
}
int valid = n > 0 && wait_fd != -2;
for (int i = 0; valid && i < n; i++) {
const struct vkp_image *src = blits[i].src, *dst = blits[i].dst;
if (!src || src->blit_dst || !dst || !dst->blit_dst) valid = 0;
}
if (!valid || dev_init() != 0) {
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd);
return -1;
}
@@ -3208,35 +3176,32 @@ int vkp_blit_images(const struct vkp_blit *blits, int n) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(g_cmd, &bi);
for (int i = 0; i < n; i++) {
struct vkp_image *src = blits[i].src, *dst = blits[i].dst;
stage_linear_dmabuf(g_cmd, src);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
src->in_general = 1;
}
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
stage_linear_dmabuf(g_cmd, src);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, foreign_image(src), src->blit_dst, &src_pair);
VkImageMemoryBarrier acq = src_external ? src_pair.acquire : (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
if (!src_external) {
acq.oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq.newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
src->in_general = 1;
}
g_vk.CmdPipelineBarrier(g_cmd, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &acq);
int bw = src->w < dst->w ? src->w : dst->w, bh = src->h < dst->h ? src->h : dst->h;
VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.srcOffsets = {{0, 0, 0}, {bw, bh, 1}},
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
blit_to_layer(g_cmd, src->image, src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
g_vk.EndCommandBuffer(g_cmd);
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
@@ -105,11 +105,7 @@ int vkp_render_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n
int vkp_pass_begin_hdr(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
const struct vkp_hdr_frame *hf, int *rw, int *rh);
struct vkp_blit {
struct vkp_image *src, *dst;
int wait_fd;
};
int vkp_blit_images(const struct vkp_blit *blits, int n);
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd);
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px);
int vkp_update_map(int scene_w, int scene_h);
int vkp_map_draw(const struct vkp_draw *d, int out[8]);
@@ -192,7 +192,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(true)
private var desktopAsUser by mutableStateOf(false)
private var cursorComposite by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
@@ -3050,7 +3049,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
@@ -3067,7 +3066,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
onClientCore = { core, on ->
@@ -3386,7 +3384,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
nativeUserland = SessionPrefs.nativeUserland(this)
desktopAsUser = SessionPrefs.desktopAsUser(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
refreshPhantomStatus()
@@ -807,7 +807,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private var isHomeApp by mutableStateOf(false)
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
private var padConnected by mutableStateOf(false)
private val deviceListener = object : InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) {
@@ -1265,7 +1264,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
) { headTracker?.recenter() }
if (!phonePanel && glasses.present && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot,
controllerSettings?.tint ?: android.graphics.Color.rgb(90, 160, 255), controllerSettings?.opacity ?: 100) {
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.VR
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.GLASSES
drawerOpen = true
}
if (!drawerOpen && !pcKeyboardOpen && !loading.visible) {
@@ -1452,10 +1451,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
LaunchedEffect(drawerOpen, achievementsOpen, AgentGuest.focusRevision, StoreAchievements.revision) {
if (!drawerOpen && !achievementsOpen) {
achievementsInFront = null
return@LaunchedEffect
}
if (!drawerOpen && !achievementsOpen) return@LaunchedEffect
val found = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { resolveAchievementsInFront() }
.onFailure { Log.w(TAG, "achievements in front: ${it.javaClass.simpleName}") }.getOrNull()
@@ -1791,7 +1787,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onBlackFrameInsertion = { on ->
SessionPrefs.setBlackFrameInsertion(this@SessionActivity, on)
blackFrameInsertion = on
CompositorHost.setBlackFrameInsertion(on, refreshHz(), compositorFpsLimit())
CompositorHost.setBlackFrameInsertion(on, refreshHz(), outputFpsLimit())
},
hdr = hdrWanted,
hdrAvailable = hdrAvailable,
@@ -1828,9 +1824,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onRumble = { on -> updateControllerPrefs { ControllerPrefs.setRumble(this@SessionActivity, on) } },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
controllerConnected = padConnected,
achievementsGame = achievementsInFront?.game,
achievementsTitle = achievementsInFront?.title,
onAchievements = achievementsInFront?.let { { drawerOpen = false; achievementsOpen = true } },
achievementsProgress = achievementsInFront?.progress,
padType = if (SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad) padType else null,
onPadType = { id ->
@@ -1951,13 +1945,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onResume = { SessionService.resume(this@SessionActivity) },
orientation = sessionOrientation,
onOrientation = { value ->
when (SessionState.mode) {
SessionService.MODE_STEAM, SessionService.MODE_RUN ->
SessionPrefs.setOrientation(this@SessionActivity, "steam", value)
SessionService.MODE_DESKTOP ->
SessionPrefs.setOrientation(this@SessionActivity, "desktop", value)
else -> SessionPrefs.setOrientation(this@SessionActivity, value)
}
SessionPrefs.setOrientation(this@SessionActivity, value)
sessionOrientation = value
applyFollowOrientation(resources.configuration)
},
@@ -2736,7 +2724,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
oscTrackpads = SessionPrefs.oscTrackpads(this)
backHold = SessionPrefs.backHold(this)
dockedMenuController = SessionPrefs.dockedMenuController(this)
sessionOrientation = SessionPrefs.orientation(this, SessionState.mode)
sessionOrientation = SessionPrefs.orientation(this)
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
@@ -3002,7 +2990,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
CompositorHost.startOrAttach(
this, holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), compositorFpsLimit(),
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(),
)
onOutputAttached(holder)
if (SessionState.running && size != previous) {
@@ -3068,7 +3056,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
WaylandCompositor.nativeResizeOutput(size.first, size.second)
}
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this, SessionState.mode)
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
private fun applyFollowChoice() {
val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first }
@@ -3077,7 +3065,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun applyFollowOrientation(config: android.content.res.Configuration) {
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp, SessionState.mode)
val wanted = SessionPrefs.windowOrientation(this, SessionState.followScreen, config.smallestScreenWidthDp)
if (requestedOrientation != wanted) requestedOrientation = wanted
}
@@ -3140,13 +3128,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun displayMode(): String = SessionPrefs.displayMode(this,
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this, SessionState.mode) && !controlsBelowWanted()
private fun portraitOutput(): Boolean = SessionPrefs.portrait(this) && !controlsBelowWanted()
private fun outputSize(): Pair<Int, Int> =
com.droiddeck.launcher.session.SessionDisplay.resolveChoice(com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
resolutionChoice(), portraitOutput())
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this, SessionState.mode)): String {
private fun resolutionChoice(portrait: Boolean = SessionPrefs.portrait(this)): String {
val mode = displayMode()
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
return if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
@@ -3193,18 +3181,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun outputFpsLimit(): Int = outputFpsLimit(pipUi)
// Android holds the window to the Game Mode override while the panel runs faster; the guest paces to the panel,
// so without this cap every frame past the override is drawn and dropped.
private fun hostFrameCap(): Int {
if (glassesScreen != null || bottomOutputActive) return 0
val display = (if (Build.VERSION.SDK_INT >= 30) display else @Suppress("DEPRECATION") windowManager.defaultDisplay) ?: return 0
return SessionPrefs.hostFrameCap(display.refreshRate, display.mode.refreshRate)
}
private fun compositorFpsLimit(): Int = SessionPrefs.compositorFpsLimit(
mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pipUi, hostFrameCap(),
)
private fun outputFpsLimit(pip: Boolean): Int =
SessionPrefs.compositorFpsLimit(mirrorRefreshLimit(), if (noSteamSession()) SessionState.fpsLimit else 0, pip)
@@ -3242,7 +3218,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
)
val hz = refreshHz()
val changed = kotlin.math.abs(SessionState.refreshHz - hz) > 0.1f
CompositorHost.updatePacing(hz, compositorFpsLimit())
CompositorHost.updatePacing(hz, outputFpsLimit())
pushCardboard(activeCardboard)
if (changed && ::surfaceView.isInitialized) applyFrameGen()
}
@@ -3813,7 +3789,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab.
val pages = sessionDrawerPages(achievementsInFront != null)
val pages = sessionDrawerPages(glasses.present)
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
releaseDrawerDirection()
}
@@ -4969,7 +4945,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun refreshControls() {
padConnected = controllerConnected()
applyUnfoldedControls()
updateOnScreenControls()
}
@@ -6410,7 +6385,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
(getSystemService(INPUT_SERVICE) as? InputManager)
?.registerInputDeviceListener(deviceListener, Handler(Looper.getMainLooper()))
padConnected = controllerConnected()
padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this))
refreshSecondScreenDisplays()
if (SessionState.guestPid > 1) padBridge?.syncConnectedControllers()
@@ -38,11 +38,6 @@ object ElfSeccompPatch {
val end = minOf(data.size, buffer.getLong(at + 8).toInt() + buffer.getLong(at + 32).toInt()) and 3.inv()
var pos = start
while (pos + 4 <= end) {
if (patchTermiosRequest(buffer, pos, end)) {
patched++
pos += 4
continue
}
val replacement = when (buffer.getInt(pos)) {
MOV_X8_SET_ROBUST_LIST -> NOP
MOV_X8_CLONE3, MOV_X8_RSEQ -> MOV_X0_ENOSYS
@@ -70,40 +65,6 @@ object ElfSeccompPatch {
return patched
}
/**
* glibc 2.42 and later read and set a terminal with TCGETS2 and TCSETS2/W2/F2, which Android's
* SELinux policy refuses on an app's pseudo-terminal slaves (EACCES): isatty() was false in every
* Konsole, ssh and tmux session, so bash had no prompt or job control and stdout was not line
* buffered. TCGETS and TCSETS* carry the same struct without its two speed fields, which glibc
* then takes from c_cflag. A site is `movz xN, #lo` then `movk xN, #hi, lsl #16`; the movz gets
* the old request and the movk becomes a no-op.
*/
private fun patchTermiosRequest(buffer: ByteBuffer, pos: Int, end: Int): Boolean {
val movz = buffer.getInt(pos)
if ((movz and 0x7fe00000) != 0x52800000) return false
val low = (movz ushr 5) and 0xffff
if (low !in 0x542a..0x542d) return false
val register = movz and 0x1f
var next = pos + 4
while (next < minOf(end, pos + 4 + 4 * 4)) {
val movk = buffer.getInt(next)
if ((movk and 0x7fe00000) == 0x72a00000 && (movk and 0x1f) == register) {
val request = when ((movk ushr 5) and 0xffff) {
0x802c -> if (low == 0x542a) 0x5401 else return false
0x402c -> if (low != 0x542a) 0x5402 + (low - 0x542b) else return false
else -> return false
}
buffer.putInt(pos, (movz and 0x1f.inv() and (0xffff shl 5).inv()) or (request shl 5) or register)
buffer.putInt(next, NOP)
return true
}
// Anything between that might read or write the register would see the old low half
if (intArrayOf(0, 5, 10, 16).any { (movk ushr it) and 0x1f == register }) return false
next += 4
}
return false
}
/** Patches the file behind [path] (symlinks followed) if it still has unpatched call sites. */
fun patchFile(path: File): Int {
val target = path.canonicalFile
@@ -154,7 +154,6 @@ object SessionFiles {
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
"usr/local/bin/droiddeck-downloads" to "usr/local/bin/droiddeck-downloads",
"usr/local/bin/droiddeck-root" to "usr/local/bin/droiddeck-root",
"usr/local/bin/droiddeck-user" to "usr/local/bin/droiddeck-user",
"usr/local/bin/droiddeck-text" to "usr/local/bin/droiddeck-text",
"usr/local/bin/droiddeck-snapd" to "usr/local/bin/droiddeck-snapd",
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
@@ -359,7 +358,6 @@ object SessionFiles {
Log.e(TAG, "could not write steam-compatibility-label")
}
writeCjkFontConfig(root, etc)
writeSessionBusPolicy(etc)
writeDesktopStrings(context, File(etc, "droiddeck").apply { mkdirs() })
val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() }
val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged")
@@ -882,24 +880,6 @@ object SessionFiles {
}
}
/**
* A session bus admits only its owner, and with droiddeck-user (the native hook's ordinary
* user) a root process and a user's share the bus while the kernel sees one Android uid.
*/
private fun writeSessionBusPolicy(etc: File) {
val xml = """<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<policy context="default">
<allow user="*"/>
</policy>
</busconfig>
"""
val conf = File(etc, "dbus-1/session.d/droiddeck-users.conf")
conf.parentFile?.mkdirs()
if (!FileUtils.writeString(conf, xml)) Log.e(TAG, "could not write the session bus policy")
}
private fun writeCjkFontConfig(root: File, etc: File) {
try {
val confDir = File(etc, "fonts/conf.d").apply { mkdirs() }
@@ -63,24 +63,6 @@ object SessionPrefs {
.takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
fun orientation(context: Context, mode: String?): Int {
val key = when (mode) {
"steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam"
"desktop", SessionService.MODE_DESKTOP -> "orientation.desktop"
else -> null
} ?: return orientation(context)
val stored = prefs(context).getInt(key, Int.MIN_VALUE)
return if (stored == Int.MIN_VALUE) orientation(context)
else stored.takeIf { value -> orientationOptions.any { it.first == value } } ?: orientation(context)
}
fun setOrientation(context: Context, mode: String, orientation: Int) {
require(mode == "steam" || mode == "desktop")
require(orientationOptions.any { it.first == orientation })
val key = if (mode == "steam") "orientation.steam" else "orientation.desktop"
prefs(context).edit().putInt(key, orientation).apply()
}
/** The session menu's width in dp the user dragged it to; null keeps the default. */
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
@@ -93,19 +75,11 @@ object SessionPrefs {
prefs(context).edit().putInt("orientation", orientation).apply()
}
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int, mode: String? = null): Int {
val modeKey = when (mode) {
"steam", SessionService.MODE_STEAM, SessionService.MODE_RUN -> "orientation.steam"
"desktop", SessionService.MODE_DESKTOP -> "orientation.desktop"
else -> null
}
val preferences = prefs(context)
if (modeKey != null && preferences.contains(modeKey)) return orientation(context, mode)
return if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !preferences.contains("orientation"))
fun windowOrientation(context: Context, followScreen: Boolean, smallestWidthDp: Int): Int =
if (followScreen && smallestWidthDp >= SessionDisplay.UNFOLDED_MIN_DP && !prefs(context).contains("orientation"))
ActivityInfo.SCREEN_ORIENTATION_USER else orientation(context)
}
fun portrait(context: Context, mode: String? = null): Boolean = when (orientation(context, mode)) {
fun portrait(context: Context): Boolean = when (orientation(context)) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> true
ActivityInfo.SCREEN_ORIENTATION_USER ->
context.resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
@@ -519,17 +493,6 @@ object SessionPrefs {
prefs(context).edit().putString("drawerPageHidden", keys.joinToString(",")).apply()
}
fun drawerSections(context: Context): Map<String, Boolean> =
idList(prefs(context).getString("drawerSections", null)).mapNotNull { entry ->
val at = entry.lastIndexOf('=').takeIf { it > 0 } ?: return@mapNotNull null
entry.substring(0, at) to (entry.substring(at + 1) == "1")
}.toMap()
fun setDrawerSections(context: Context, sections: Map<String, Boolean>) {
prefs(context).edit().putString("drawerSections", sections.entries.filter { ',' !in it.key }
.joinToString(",") { "${it.key}=${if (it.value) 1 else 0}" }).apply()
}
fun setNavTabHidden(context: Context, keys: Set<String>) {
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
}
@@ -1141,13 +1104,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
}
/** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
fun setDesktopAsUser(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
}
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
@@ -1851,15 +1807,16 @@ object SessionPrefs {
const val PIP_FPS = 30
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false, hostCap: Int = 0): Int {
val limit = listOf(mirrorRefreshLimit, sessionLimit, hostCap).filter { it > 0 }.minOrNull() ?: FPS_UNPACED
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false): Int {
val limit = when {
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
mirrorRefreshLimit <= 0 -> sessionLimit
sessionLimit <= 0 -> mirrorRefreshLimit
else -> minOf(mirrorRefreshLimit, sessionLimit)
}
return if (pip && mirrorRefreshLimit <= 0 && (limit <= 0 || limit > PIP_FPS)) PIP_FPS else limit
}
/** The per-app rate Android holds this window to (Game Mode's FPS override), or 0 when the panel's rate applies. */
fun hostFrameCap(overrideHz: Float, panelHz: Float): Int =
if (overrideHz > 1f && panelHz - overrideHz > 1f) Math.round(overrideHz) else 0
val upscalerChoices = listOf(
2 to "Nearest", 0 to "Linear", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only",
@@ -661,7 +661,7 @@ class SessionService : Service() {
Log.i(TAG, "game resolution: ${w}x$h on a ${size.first}x${size.second} output")
}
if (SessionState.followScreen || size.first < size.second ||
SessionPrefs.orientation(this, SessionState.mode) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
guest.add("DD_FOLLOW_OUTPUT=1")
if (SessionState.hdr) {
guest.add("DD_HDR=1")
@@ -709,7 +709,6 @@ class SessionService : Service() {
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
GameStorage.effective(this)?.let { guest.add("DD_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("DD_STEAM_UI=desktop")
if (SessionPrefs.desktopAsUser(this)) guest.add("DD_DESKTOP_USER=1")
// Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not
// an Adreno, or Setup's switch), and graphics-report.txt for every session.
if (GraphicsReport.detailed(this)) guest.add("DD_GAME_LOGS=1")
@@ -18,7 +18,7 @@ object SettingsReset {
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
@@ -1,142 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/**
* Inside the session menu every top-level settings group folds to its header and a summary of its values.
* Groups start folded; a group the player opens or folds stays that way across sessions.
*/
internal object DrawerSectionState {
private val chosen = mutableStateMapOf<String, Boolean>()
fun load(context: Context) {
if (DevPreview.drawer != null) return
chosen.clear()
chosen.putAll(SessionPrefs.drawerSections(context))
}
fun isOpen(key: String) = chosen[key] ?: false
fun toggle(context: Context, key: String) {
chosen[key] = !isOpen(key)
if (DevPreview.drawer == null) SessionPrefs.setDrawerSections(context, chosen.toMap())
}
}
internal class DrawerSections(val context: Context, val track: (String) -> Modifier)
internal val LocalDrawerSections = compositionLocalOf<DrawerSections?> { null }
@Composable
internal fun DrawerSection(
sections: DrawerSections, key: String, title: String, summary: String?, tag: String?,
content: @Composable ColumnScope.() -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val open = DrawerSectionState.isOpen(key)
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val rotation by animateFloatAsState(if (open) 180f else 0f, Motion.tw(180), label = "sectionArrow")
val state = stringResource(if (open) R.string.widgets_expanded else R.string.widgets_collapsed)
val toggle = { DrawerSectionState.toggle(sections.context, key) }
val shape = RoundedCornerShape(14.dp)
Column(
Modifier.fillMaxWidth().padding(top = 6.dp).clip(shape)
.background(colors.surface).border(1.dp, if (open) pal.line2 else pal.line, shape),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)
.then(sections.track("section-$key"))
.testTag("drawer-section-$key")
.background(if (hot) pal.signal.copy(alpha = 0.12f) else androidx.compose.ui.graphics.Color.Transparent)
.glideBorder(hot, shape, pal.signal)
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = toggle)
.controllerConfirm(onClick = toggle)
.semantics { contentDescription = title; stateDescription = state }
.padding(start = 12.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Text(title.uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp,
color = if (open) colors.onBackground else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f, fill = false))
if (tag != null) Text(
tag, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1,
modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(pal.signal.copy(alpha = 0.14f))
.padding(horizontal = 6.dp, vertical = 2.dp),
)
}
if (!open && !summary.isNullOrEmpty()) Text(
summary, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 2.dp),
)
}
Icon(Icons.Outlined.ExpandMore, contentDescription = null, tint = colors.onSurfaceVariant,
modifier = Modifier.size(22.dp).rotate(rotation))
}
AnimatedVisibility(open, enter = expandVertically(Motion.tw(200)) + fadeIn(Motion.tw(160)),
exit = shrinkVertically(Motion.tw(160)) + fadeOut(Motion.tw(120))) {
Column(Modifier.fillMaxWidth()) {
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
// Only top-level groups fold; groups and dialogs opened from inside one draw normally.
CompositionLocalProvider(LocalDrawerSections provides null) { content() }
}
}
}
}
@@ -26,8 +26,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
fun on(key: String) = cfg[key] == "1"
fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback
SettingsGroup(stringResource(R.string.drawer_hud), key = "performance-hud",
detail = stringResource(if (a.hudOn) R.string.widgets_on else R.string.widgets_off)) {
SettingsGroup(stringResource(R.string.drawer_hud)) {
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud)
if (a.hudOn) ToggleRow(
host, "hud-only-during-game", stringResource(R.string.hud_only_during_game),
@@ -63,7 +62,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
if (a.dashboardAvailable && a.secondScreenDisplays.isNotEmpty()) BottomStripSettings(host, track)
if (!a.hudOn) return
SettingsGroup(stringResource(R.string.hud_group_look), key = "performance-hud-look") {
SettingsGroup(stringResource(R.string.hud_group_look)) {
SliderRow(stringResource(R.string.hud_scale), null, int("hudScale", 100), 50..150, step = 5, format = { "$it%" },
modifier = track("hud-scale")) { a.onHudSetting("hudScale", it.toString()) }
SliderRow(stringResource(R.string.drawer_hud_opacity), null, int("hudOpacity", 80), 0..100, step = 5, format = { "$it%" },
@@ -86,7 +85,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
}
var editing by remember { mutableStateOf(false) }
SettingsGroup(stringResource(R.string.hud_group_metrics), key = "performance-hud-metrics") {
SettingsGroup(stringResource(R.string.hud_group_metrics)) {
ActionRow(stringResource(R.string.hud_group_metrics), null, stringResource(R.string.common_edit),
onClick = { editing = true }, modifier = track("hud-readings"))
val rows = DroidDeckHudSize.rowsFor(DroidDeckHudSize.from(cfg["hudSize"]), cfg)
@@ -104,7 +103,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
)
}
if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps), key = "performance-hud-temps") {
if (on("showTemp") || on("showGpuTemp") || on("showBatteryTemp")) SettingsGroup(stringResource(R.string.hud_group_temps)) {
ChoiceRow(host, "hud-temp-unit", stringResource(R.string.hud_temp_unit), null,
listOf("c" to "°C", "f" to "°F"), if (cfg["tempUnit"].equals("f", true)) "f" else "c",
chipModifier = track("hud-temp-unit")) { a.onHudSetting("tempUnit", it) }
@@ -130,7 +129,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
}
}
SettingsGroup(stringResource(R.string.hud_group_more), key = "performance-hud-more") {
SettingsGroup(stringResource(R.string.hud_group_more)) {
ActionRow(stringResource(R.string.hud_export), stringResource(R.string.hud_export_hint),
stringResource(R.string.hud_export_button), onClick = a.onHudExport, modifier = track("hud-export"))
ActionRow(stringResource(R.string.hud_reset), null, stringResource(R.string.hud_reset_button),
@@ -146,7 +145,7 @@ private fun BottomStripSettings(host: MenuHost, track: (String) -> Modifier) {
var hudOn by remember { mutableStateOf(SessionPrefs.bottomHud(context)) }
var onTabs by remember { mutableStateOf(SessionPrefs.bottomStripOnTabs(context)) }
var shown by remember { mutableStateOf(SessionPrefs.bottomStripMetrics(context)) }
SettingsGroup(stringResource(R.string.bottom_hud_group), key = "performance-bottom-hud") {
SettingsGroup(stringResource(R.string.bottom_hud_group)) {
ToggleRow(host, "bottom-hud", stringResource(R.string.bottom_hud_group), null, hudOn,
chipModifier = track("bottom-hud")) { on ->
hudOn = on
@@ -1,9 +1,6 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.FocusRequester
import android.os.Build
@@ -53,7 +50,6 @@ import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
@@ -156,19 +152,6 @@ internal fun SetupPanel(
) {
val host = rememberMenuHost()
val ctx = LocalContext.current
var steamOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "steam")) }
var desktopOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "desktop")) }
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner, ctx) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
steamOrientation = SessionPrefs.orientation(ctx, "steam")
desktopOrientation = SessionPrefs.orientation(ctx, "desktop")
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
var hideHomeFromRecents by remember { mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.hideHomeFromRecents(ctx)) }
var processLimitBusy by remember { mutableStateOf(false) }
var processLimitMessage by remember { mutableStateOf<String?>(null) }
@@ -533,27 +516,7 @@ internal fun SetupPanel(
ChoiceRow(
host, "orientation", stringResource(R.string.setup_session_orientation), stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
s.orientation, onPick = { value ->
a.onOrientation(value)
steamOrientation = SessionPrefs.orientation(ctx, "steam")
desktopOrientation = SessionPrefs.orientation(ctx, "desktop")
},
)
ChoiceRow(
host, "orientation-steam", stringResource(R.string.setup_session_orientation) + " (Steam)", stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
steamOrientation, onPick = { value ->
steamOrientation = value
SessionPrefs.setOrientation(ctx, "steam", value)
},
)
ChoiceRow(
host, "orientation-desktop", stringResource(R.string.setup_session_orientation) + " (Desktop)", stringResource(R.string.setup_session_orientation_hint),
SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) },
desktopOrientation, onPick = { value ->
desktopOrientation = value
SessionPrefs.setOrientation(ctx, "desktop", value)
},
s.orientation, onPick = a.onOrientation,
)
ToggleRow(
host, "launcher-fullscreen", stringResource(R.string.setup_fullscreen),
@@ -88,7 +88,7 @@ internal fun VrControllerGroups(host: MenuHost, track: (String) -> Modifier = {
androidx.compose.runtime.LaunchedEffect(Unit) { com.droiddeck.launcher.input.VrControllers.load(context) }
val c by com.droiddeck.launcher.input.VrControllers.settings.collectAsState()
val emulate = com.droiddeck.launcher.input.VrControllers.Emulate.entries
SettingsGroup(stringResource(R.string.vr_controllers_group), key = "vr-controllers") {
SettingsGroup(stringResource(R.string.vr_controllers_group)) {
ChoiceRow(host, "vr-emulate", stringResource(R.string.vr_controllers_emulate), stringResource(R.string.vr_controllers_emulate_hint),
emulate.map { it to stringResource(when (it) {
com.droiddeck.launcher.input.VrControllers.Emulate.OFF -> R.string.vr_controllers_off
@@ -142,13 +142,13 @@ internal fun GlassesGroups(
val directView = usesGlasses && picture == GlassesRendering.Picture.STEREO
val menuScreen = !inSession && g.usable && s.gameOnGlasses && s.screen3dof
if (g.canControl && onRecenter != null && s.headTracking && (virtualScreen || menuScreen || (directView && steamVrRunning))) {
SettingsGroup(stringResource(R.string.glasses_quick_actions), compact = true, key = "vr-glasses-quick") {
SettingsGroup(stringResource(R.string.glasses_quick_actions), compact = true) {
ActionRow(stringResource(R.string.glasses_recenter),
if (virtualScreen || menuScreen) stringResource(R.string.glasses_recenter_screen_hint) else null,
stringResource(R.string.cardboard_recenter_button), onRecenter)
}
}
if (display) SettingsGroup(g.model, key = "vr-glasses") {
if (display) SettingsGroup(g.model) {
if (g.experimental) SettingsRow(stringResource(R.string.glasses_control), stringResource(
if (g.supportsDisplayModeControl) R.string.glasses_xreal_experimental else R.string.glasses_pro2_experimental)) {}
val status = if (g.hasDisplay) stringResource(R.string.glasses_status, g.width, g.height, kotlin.math.round(g.hz).toInt(),
@@ -170,7 +170,7 @@ internal fun GlassesGroups(
s.gameOnGlasses, chipModifier = track("glasses-game")) { Glasses.setGameOnGlasses(it) }
}
if (display && g.canControl && g.supportsDisplayModeControl && (inSession || g.sbs || g.sbsSupport == GlassesState.SBS_FAILS)) {
SettingsGroup(stringResource(R.string.glasses_display_mode), key = "vr-glasses-mode") {
SettingsGroup(stringResource(R.string.glasses_display_mode)) {
if (g.sbsSupport == GlassesState.SBS_FAILS && !g.sbs) {
ActionRow(stringResource(R.string.glasses_3d), stringResource(R.string.glasses_3d_failed),
stringResource(R.string.stores_dl_retry), { Glasses.set3d(true) })
@@ -182,12 +182,12 @@ internal fun GlassesGroups(
val profiles = if (inSession) listOf(GlassesDisplayModes.profile(g.sbs, false))
else listOf(GlassesDisplayProfile.TWO_D, GlassesDisplayProfile.THREE_D)
for (profile in profiles) SettingsGroup(stringResource(if (profile == GlassesDisplayProfile.TWO_D)
R.string.glasses_output_2d else R.string.glasses_output_3d), key = "vr-glasses-output-${profile.name.lowercase()}") {
R.string.glasses_output_2d else R.string.glasses_output_3d)) {
GlassesResolutionRow(host, g, s, profile, track)
if ((profile == GlassesDisplayProfile.THREE_D) == g.sbs) GlassesRefreshRow(host, g, s, track)
}
}
if (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_picture_group), key = "vr-glasses-picture") {
if (display && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.glasses_picture_group)) {
ChoiceRow(host, "glasses-picture", stringResource(R.string.glasses_picture), stringResource(R.string.glasses_picture_hint),
listOf(
GlassesSettings.PICTURE_AUTO to stringResource(R.string.glasses_picture_auto),
@@ -213,7 +213,7 @@ internal fun GlassesGroups(
format = { SpatialMeasurements.distance(it / 10f) }, modifier = track("glasses-distance")) { Glasses.setScreenDistanceDm(it) }
}
}
if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr), key = "vr-glasses-steamvr") {
if (vr && (g.canControl || g.hasDisplay)) SettingsGroup(stringResource(R.string.cardboard_steamvr)) {
steamVr()
if (g.supportsDisplayModeControl) ToggleRow(host, "glasses-auto3d", stringResource(R.string.glasses_auto3d),
stringResource(R.string.glasses_auto3d_hint), s.auto3d, chipModifier = track("glasses-auto3d")) { Glasses.setAuto3d(it) }
@@ -226,7 +226,7 @@ internal fun GlassesGroups(
format = { "$it°" }, modifier = track("glasses-vr-fov")) { Glasses.setVrFovDeg(it) }
}
if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) {
SettingsGroup(stringResource(R.string.glasses_head_tracking), key = "vr-glasses-tracking") {
SettingsGroup(stringResource(R.string.glasses_head_tracking)) {
val trackingHint = when {
inSession && !usesGlasses -> R.string.glasses_screen_no_output
spatialVr -> R.string.glasses_head_tracking_spatial_vr_hint
@@ -240,13 +240,13 @@ internal fun GlassesGroups(
chipModifier = track("glasses-tracking")) { Glasses.setHeadTracking(it) }
}
val calibration by Glasses.calibration.collectAsState()
if (calibration.supported) SettingsGroup(stringResource(R.string.glasses_calibration), key = "vr-glasses-calibration") {
if (calibration.supported) SettingsGroup(stringResource(R.string.glasses_calibration)) {
GlassesCalibrationControls(calibration,
onStart = Glasses::startCalibration, onCancel = Glasses::cancelCalibration,
onReset = Glasses::resetCalibration, onDone = { onRecenter?.invoke() })
}
}
if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.glasses_hardware), key = "vr-glasses-hardware") {
if ((tab == null || tab == GlassesTab.HARDWARE) && g.canControl && g.hardwareControls) SettingsGroup(stringResource(R.string.glasses_hardware)) {
if (g.brightnessMax > 0) SliderRow(stringResource(R.string.glasses_brightness), null, g.brightness.coerceAtLeast(0), 0..g.brightnessMax, step = 1,
modifier = track("glasses-brightness")) { Glasses.setBrightness(it) }
if (g.volumeMax > 0) SliderRow(stringResource(R.string.glasses_volume), null, g.volume.coerceAtLeast(0), 0..g.volumeMax, step = 1,
@@ -259,7 +259,7 @@ internal fun GlassesGroups(
androidx.compose.runtime.LaunchedEffect(Unit) { HandTracking.load(context) }
if ((tab == null || tab == GlassesTab.TRACKING) && g.canControl) {
if (g.spatialConnected) {
SettingsGroup(stringResource(R.string.glasses_experimental), key = "vr-glasses-experimental") {
SettingsGroup(stringResource(R.string.glasses_experimental)) {
val spatial by SpatialTracking.status.collectAsState()
ToggleRow(host, "glasses-position", stringResource(R.string.glasses_position), stringResource(R.string.glasses_position_hint),
s.positionalTracking, chipModifier = track("glasses-position")) { Glasses.setPositionalTracking(it) }
@@ -282,7 +282,7 @@ internal fun GlassesGroups(
s.joyConTracking, enabled = s.positionalTracking, chipModifier = track("glasses-joycons")) { Glasses.setJoyConTracking(it) }
}
}
if (hands.usable) SettingsGroup(stringResource(R.string.phone_camera_tracking_group), key = "vr-hand-camera") {
if (hands.usable) SettingsGroup(stringResource(R.string.phone_camera_tracking_group)) {
HandCameraRows(host, track, inSession)
}
}
@@ -44,7 +44,6 @@ import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.hypot
import kotlin.math.max
import kotlin.math.min
@SuppressLint("ViewConstructor")
@@ -64,7 +63,6 @@ class InputSurfaceView(
private val art by lazy(LazyThreadSafetyMode.NONE) { PadArt(context) }
private var artworkDpad = emptyList<HoldButton>()
private val artworkDpadBounds = RectF()
private var crossDpads = emptyList<Pair<List<HoldButton>, RectF>>()
private var requestedLayout = customLayout
init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
@@ -187,7 +185,6 @@ class InputSurfaceView(
private fun renderCustom(pad: PadBridge?) {
artworkDpad = emptyList()
crossDpads = emptyList()
val canvas = object : ViewGroup(context) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val layout = customLayout
@@ -206,7 +203,6 @@ class InputSurfaceView(
child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight)
}
updateArtworkDpad(this)
updateCrossDpad(this)
}
override fun dispatchDraw(canvas: Canvas) {
@@ -248,39 +244,11 @@ class InputSurfaceView(
canvas.getChildAt(index) as? HoldButton
}
val previous = artworkDpad
artworkDpad = if (crossed(buttons, artworkDpadBounds)) buttons else emptyList()
artworkDpad = if (crossed(buttons)) buttons else emptyList()
if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() }
}
private fun updateCrossDpad(canvas: ViewGroup) {
val buttons = (0 until canvas.childCount).map(canvas::getChildAt).filterIsInstance<HoldButton>()
val (ups, rights, downs, lefts) = DIRECTIONS.map { direction -> buttons.filter { (it.tag as? InputSurfaceElement)?.control == direction } }
crossDpads = ups.flatMap { up -> rights.flatMap { right -> downs.flatMap { down ->
lefts.mapNotNull { left -> listOf(up, right, down, left).let { arms -> hole(arms)?.let { arms to it } } } } } }
}
private fun hole(buttons: List<HoldButton>): RectF? {
val (up, right, down, left) = buttons
val hole = RectF(left.right.toFloat(), up.bottom.toFloat(), right.left.toFloat(), down.top.toFloat())
val across = max(up.left, down.left) to min(up.right, down.right)
val along = max(left.top, right.top) to min(left.bottom, right.bottom)
return hole.takeIf {
!it.isEmpty && across.first < across.second && along.first < along.second &&
across.first < it.right && across.second > it.left && along.first < it.bottom && along.second > it.top
}
}
private fun crossTarget(x: Float, y: Float): HoldButton? {
val first = crossDpads.firstOrNull()?.first?.first() ?: return null
val hx = x - (originX(first) - first.left)
val hy = y - (originY(first) - first.top)
return crossDpads.filter { (arms, hole) -> arms.all { it.visibility == VISIBLE } && hole.contains(hx, hy) }
.flatMap { it.first }.distinct().minByOrNull { arm ->
hypot(max(max(arm.left - hx, hx - arm.right), 0f), max(max(arm.top - hy, hy - arm.bottom), 0f))
}
}
private fun crossed(buttons: List<HoldButton>, bounds: RectF): Boolean {
private fun crossed(buttons: List<HoldButton>): Boolean {
if (buttons.size != DIRECTIONS.size) return false
val (up, right, down, left) = buttons
val centerX = (left.left + right.right) / 2f
@@ -290,7 +258,7 @@ class InputSurfaceView(
kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f ||
kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f ||
up.bottom >= down.top || left.right >= right.left) return false
bounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
return true
}
@@ -316,7 +284,6 @@ class InputSurfaceView(
val views = (canvas.childCount - 1 downTo 0).map(canvas::getChildAt).filter { it.visibility == VISIBLE }
views.firstOrNull { !(it is StickView && it.adaptive) && hits(it, x, y, 0f) }?.let { return it }
views.filter { it is HoldButton && hits(it, x, y, slack(it)) }.minByOrNull { distance(it, x, y) }?.let { return it }
crossTarget(x, y)?.let { return it }
if (views.any { it is HoldButton && hits(it, x, y, slack(it) + ADAPTIVE_CLEARANCE_PX) }) return null
return views.filter { it is StickView && it.adaptive && it !in owners.values && (hits(it, x, y, 0f) || it.captures(x - originX(it), y - originY(it))) }
.minByOrNull { distance(it, x, y) }
@@ -116,7 +116,10 @@ internal object NavTabs {
fun more(s: FrontEndState) = listed(s).filter { place(s, it) == TabPlace.MORE }
fun bar(s: FrontEndState): List<String> = listed(s).filter { place(s, it) == TabPlace.BAR } + MORE
fun bar(s: FrontEndState): List<String> {
val shown = listed(s).filter { place(s, it) == TabPlace.BAR }
return if (more(s).isEmpty()) shown else shown + MORE
}
fun setHidden(context: Context, key: String, hide: Boolean) {
hidden = if (hide && hideable(key)) hidden + key else hidden - key
@@ -11,7 +11,7 @@ internal fun PenSettingsGroup(
host: MenuHost, pen: SessionPrefs.Pen, track: (String) -> Modifier = { Modifier },
onPick: (key: String, value: String) -> Unit,
) {
SettingsGroup(stringResource(R.string.mode_pen), key = "controller-pen") {
SettingsGroup(stringResource(R.string.mode_pen)) {
ChoiceRow(host, "pen", stringResource(R.string.mode_pen), null,
listOf(SessionPrefs.PEN_MOUSE to stringResource(R.string.mode_pen_mouse),
SessionPrefs.PEN_TOUCH to stringResource(R.string.mode_pen_touch)),
@@ -49,7 +49,6 @@ fun PerformancePage(
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
nativeUserland: Boolean,
desktopAsUser: Boolean,
cursorComposite: Boolean,
guestHostname: String,
phantomWarning: String?,
@@ -68,7 +67,6 @@ fun PerformancePage(
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onNativeUserland: (Boolean) -> Unit,
onDesktopAsUser: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
onClientCore: (Int, Boolean) -> Unit,
@@ -196,12 +194,6 @@ fun PerformancePage(
modifier = Modifier.width(220.dp).focusGlide(),
)
}
ToggleRow(
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native),
desktopAsUser && nativeUserland, enabled = nativeUserland,
onChange = onDesktopAsUser,
)
}
if (phantomWarning != null) {
Spacer(Modifier.height(16.dp))
@@ -226,7 +218,7 @@ fun PerformancePage(
@Composable
internal fun GpuClockGroup(host: MenuHost, on: Boolean, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) {
SettingsGroup(stringResource(R.string.perf_gpu), key = "performance-gpu") {
SettingsGroup(stringResource(R.string.perf_gpu)) {
ToggleRow(
host, "gpuclock", stringResource(R.string.perf_gpuclock),
null,
@@ -6,18 +6,17 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.SessionPrefs
/** HUD holds the Performance page and GAMES the Game page; the names stay because saved page orders use them. */
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("section-controller-input"),
HUD("section-performance-pacing"),
DISPLAY("section-display"),
EFFECTS("section-effects-look"),
GAMES("section-game-profile"),
VR("section-vr-steamvr"),
SESSION("pause"),
MORE("more-edit"),
ACHIEVEMENTS("achievements"),
CONTROLLER("input-profile"),
GLASSES("glasses-game"),
DISPLAY("fg"),
HUD("hud"),
EFFECTS("look"),
GAMES("anisotropy"),
AGENT("agent-input"),
SESSION("suspend"),
MORE("more-edit"),
VR("steamvr"),
}
internal object DrawerPages {
@@ -72,16 +71,16 @@ internal object DrawerPages {
}
internal fun offeredDrawerPages(
hasAchievements: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> =
DrawerPages.order.filter {
(hasAchievements || it != SessionDrawerPage.ACHIEVEMENTS) &&
(hasGlasses || it != SessionDrawerPage.GLASSES) &&
(hasAgent || it != SessionDrawerPage.AGENT)
}
internal fun sessionDrawerPages(
hasAchievements: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> = offeredDrawerPages(hasAchievements, hasAgent).filter { it !in DrawerPages.hidden }
hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown,
): List<SessionDrawerPage> = offeredDrawerPages(hasGlasses, hasAgent).filter { it !in DrawerPages.hidden }
/** The pages shown as tabs: everything up to and including the More tab. */
internal fun List<SessionDrawerPage>.strip(): List<SessionDrawerPage> {
File diff suppressed because it is too large. Load diff
@@ -89,7 +89,6 @@ internal object SettingsIndex {
s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"),
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
s(SettingsSection.CONTROLLER, R.string.setup_tab_controller, "gamepad", "buttons", "mapping", "profile", "remap"),
SettingsEntry(SettingsPlace.TAB, R.string.rail_storage, tab = "storage", words = listOf("sd card", "space", "uninstall", "disk")),
@@ -443,11 +443,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
}
@Composable
fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, key: String? = null, tag: String? = null, content: @Composable ColumnScope.() -> Unit) {
LocalDrawerSections.current?.let { sections ->
DrawerSection(sections, key ?: title, title, detail, tag, content)
return
}
fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, content: @Composable ColumnScope.() -> Unit) {
val tight = compact || LocalCompactSettings.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -56,7 +56,6 @@ import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
@@ -359,67 +358,6 @@ internal fun SessionAchievementsPanel(label: String, state: AchievementsState, t
}
}
/** The Achievements page of the session menu: the same list as the full panel, inside the menu's own scroll. */
@Composable
internal fun DrawerAchievementsPage(game: StoreAchievements.Game, title: String?, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val label = StoreAchievements.forSource(game.source)?.label.orEmpty()
val state = rememberAchievements(game) ?: AchievementsState.READING
val kinds = remember(state.list) {
val list = state.list.orEmpty()
val split = groups(list)
if (split.size < 2) emptyList() else listOf(R.string.stores_tab_all to list) + split
}
var pick by remember { mutableIntStateOf(0) }
if (pick >= kinds.size) pick = 0
var noteHadFocus by remember { mutableStateOf(false) }
val firstRow = remember { FocusRequester() }
val loaded = !state.list.isNullOrEmpty()
LaunchedEffect(loaded) {
if (loaded && noteHadFocus) {
noteHadFocus = false
withFrameNanos { }
runCatching { firstRow.requestFocus() }
}
}
Column(Modifier.fillMaxWidth().padding(top = 8.dp, start = 4.dp, end = 4.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Text(title.orEmpty(), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
state.list?.takeIf { it.isNotEmpty() }?.let { list ->
if (state.all) Trophy(18.dp, Modifier.padding(end = 6.dp))
Text(stringResource(R.string.achievements_count_short, state.done, list.size), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = pal.signal)
}
}
val list = state.list
if (list.isNullOrEmpty()) {
Text(achievementsNote(state, label).orEmpty(), fontSize = 13.sp, color = colors.onSurfaceVariant,
modifier = Modifier.padding(top = 12.dp).then(track("achievements"))
.onFocusChanged { if (it.isFocused) noteHadFocus = true }.focusable())
return@Column
}
LinearProgressIndicator(
progress = { state.done / list.size.toFloat() }, color = pal.signal, trackColor = pal.line,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().height(4.dp).clip(RoundedCornerShape(2.dp)),
)
if (kinds.isNotEmpty()) TabStrip(
kinds.map { (name, group) -> if (name == R.string.stores_tab_all) stringResource(name) + " · " + group.size else stringResource(name, group.size) },
pick, { pick = it }, Modifier.padding(top = 10.dp), bumpers = false, compact = true,
)
val shown = kinds.getOrNull(pick)?.second ?: list
val sections = if (pick == 0) groups(shown).filter { it.second.isNotEmpty() } else listOf(null to shown)
val first = sections.firstOrNull()?.second?.firstOrNull()?.id
Column(Modifier.padding(top = 6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
for ((group, items) in sections) {
if (group != null) AchievementGroupLabel(stringResource(group, items.size))
for (a in items) androidx.compose.runtime.key(a.id) {
AchievementRow(a, compact = true, if (a.id == first) track("achievements").focusRequester(firstRow) else Modifier)
}
}
}
}
}
@Composable
internal fun DrawerAchievementsRow(progress: Pair<Int, Int>?, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
-3
View File
@@ -654,9 +654,6 @@
<string name="perf_hostname">اسم المضيف</string>
<string name="perf_hostname_hint">الاسم الذي يراه Steam لهذا الجهاز. اتركه خاليًا للاستعادة إلى %1$s.</string>
<string name="perf_hostname_invalid">أحرف وأرقام وشرطات داخلية فقط، حتى 63 حرفًا.</string>
<string name="perf_desktop_as_user">تشغيل سطح المكتب كمستخدم</string>
<string name="perf_desktop_as_user_hint">يعمل سطح المكتب وتطبيقاته وطرفياته كمستخدم عادي باسم deck بدلًا من root، للتطبيقات التي ترفض root. يظل sudo يعمل. يسري على سطح المكتب التالي.</string>
<string name="perf_desktop_as_user_needs_native">يتطلب التشغيل دون proot.</string>
<string name="perf_phantom_warning">Android مهيَّأ لإنهاء هذه الجلسة</string>
<string name="driver_installed">مثبّت</string>
<string name="driver_available">متاح للتنزيل</string>
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nombre del host</string>
<string name="perf_hostname_hint">El nombre que Steam ve para este dispositivo. En blanco restaura %1$s.</string>
<string name="perf_hostname_invalid">Solo letras, dígitos y guiones internos, hasta 63 caracteres.</string>
<string name="perf_desktop_as_user">El escritorio se ejecuta como usuario</string>
<string name="perf_desktop_as_user_hint">El escritorio, sus apps y sus terminales se ejecutan como el usuario común deck en lugar de root, para las apps que rechazan root. sudo sigue funcionando. Se aplica al próximo escritorio.</string>
<string name="perf_desktop_as_user_needs_native">Requiere Ejecutar sin proot.</string>
<string name="perf_phantom_warning">Android está configurado para cerrar esta sesión</string>
<string name="driver_installed">Instalado</string>
<string name="driver_available">Disponible para descargar</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Име на хоста</string>
<string name="perf_hostname_hint">Името, което Steam вижда за това устройство. Оставено празно възстановява %1$s.</string>
<string name="perf_hostname_invalid">Само букви, цифри и тирета по средата, до 63 знака.</string>
<string name="perf_desktop_as_user">Работният плот работи като потребител</string>
<string name="perf_desktop_as_user_hint">Работният плот, приложенията и терминалите му работят като обикновения потребител deck вместо root, за приложения, които отказват root. sudo продължава да работи. Важи за следващия работен плот.</string>
<string name="perf_desktop_as_user_needs_native">Изисква Работа без proot.</string>
<string name="perf_phantom_warning">Android е настроен да прекратява тази сесия</string>
<string name="driver_installed">Инсталиран</string>
<string name="driver_available">Налично за изтегляне</string>
-3
View File
@@ -650,9 +650,6 @@
<string name="perf_hostname">Název hostitele</string>
<string name="perf_hostname_hint">Název, který Steam vidí pro toto zařízení. Prázdné obnoví %1$s.</string>
<string name="perf_hostname_invalid">Pouze písmena, číslice a vnitřní pomlčky, až 63 znaků.</string>
<string name="perf_desktop_as_user">Plocha běží jako uživatel</string>
<string name="perf_desktop_as_user_hint">Plocha, její aplikace a terminály běží jako běžný uživatel deck místo root, kvůli aplikacím, které root odmítají. sudo dál funguje. Projeví se u příští plochy.</string>
<string name="perf_desktop_as_user_needs_native">Vyžaduje Spouštět bez proot.</string>
<string name="perf_phantom_warning">Android je nastaven tak, aby tuto relaci ukončil</string>
<string name="driver_installed">Nainstalováno</string>
<string name="driver_available">K dispozici ke stažení</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Værtsnavn</string>
<string name="perf_hostname_hint">Navnet Steam ser for denne enhed. Tomt gendanner %1$s.</string>
<string name="perf_hostname_invalid">Kun bogstaver, tal og bindestreger i midten, op til 63 tegn.</string>
<string name="perf_desktop_as_user">Skrivebordet kører som bruger</string>
<string name="perf_desktop_as_user_hint">Skrivebordet, dets apps og terminaler kører som den almindelige bruger deck i stedet for root, til apps der afviser root. sudo virker stadig. Gælder fra næste skrivebord.</string>
<string name="perf_desktop_as_user_needs_native">Kræver Kør uden proot.</string>
<string name="perf_phantom_warning">Android er sat til at lukke denne session</string>
<string name="driver_installed">Installeret</string>
<string name="driver_available">Tilgængelig til download</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Hostname</string>
<string name="perf_hostname_hint">Der Name, den Steam für dieses Gerät sieht. Leer lassen stellt %1$s wieder her.</string>
<string name="perf_hostname_invalid">Nur Buchstaben, Ziffern und innere Bindestriche, bis zu 63 Zeichen.</string>
<string name="perf_desktop_as_user">Desktop läuft als Benutzer</string>
<string name="perf_desktop_as_user_hint">Der Desktop, seine Apps und Terminals laufen als normaler Benutzer deck statt als root, für Apps, die root ablehnen. sudo funktioniert weiterhin. Gilt ab dem nächsten Desktop.</string>
<string name="perf_desktop_as_user_needs_native">Erfordert Ohne proot ausführen.</string>
<string name="perf_phantom_warning">Android ist so eingestellt, dass es diese Sitzung beendet</string>
<string name="driver_installed">Installiert</string>
<string name="driver_available">Zum Download verfügbar</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Όνομα κεντρικού υπολογιστή</string>
<string name="perf_hostname_hint">Το όνομα που βλέπει το Steam για αυτή τη συσκευή. Αν το αφήσετε κενό, επανέρχεται σε %1$s.</string>
<string name="perf_hostname_invalid">Μόνο γράμματα, ψηφία και εσωτερικές παύλες, έως 63 χαρακτήρες.</string>
<string name="perf_desktop_as_user">Η επιφάνεια εργασίας εκτελείται ως χρήστης</string>
<string name="perf_desktop_as_user_hint">Η επιφάνεια εργασίας, οι εφαρμογές και τα τερματικά της εκτελούνται ως ο απλός χρήστης deck αντί για root, για εφαρμογές που αρνούνται το root. Το sudo εξακολουθεί να λειτουργεί. Ισχύει από την επόμενη επιφάνεια εργασίας.</string>
<string name="perf_desktop_as_user_needs_native">Απαιτεί Εκτέλεση χωρίς proot.</string>
<string name="perf_phantom_warning">Το Android είναι ρυθμισμένο να διακόπτει αυτή τη συνεδρία</string>
<string name="driver_installed">Εγκατεστημένο</string>
<string name="driver_available">Διαθέσιμο για λήψη</string>
-3
View File
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nombre del host</string>
<string name="perf_hostname_hint">El nombre que Steam ve para este dispositivo. En blanco restaura %1$s.</string>
<string name="perf_hostname_invalid">Solo letras, dígitos y guiones internos, hasta 63 caracteres.</string>
<string name="perf_desktop_as_user">El escritorio se ejecuta como usuario</string>
<string name="perf_desktop_as_user_hint">El escritorio, sus apps y sus terminales se ejecutan como el usuario normal deck en lugar de root, para las apps que rechazan root. sudo sigue funcionando. Se aplica al próximo escritorio.</string>
<string name="perf_desktop_as_user_needs_native">Requiere Ejecutar sin proot.</string>
<string name="perf_phantom_warning">Android está configurado para cerrar esta sesión</string>
<string name="driver_installed">Instalado</string>
<string name="driver_available">Disponible para descargar</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Isäntänimi</string>
<string name="perf_hostname_hint">Nimi, jonka Steam näkee tälle laitteelle. Tyhjä palauttaa arvon %1$s.</string>
<string name="perf_hostname_invalid">Vain kirjaimia, numeroita ja sisäisiä yhdysmerkkejä, enintään 63 merkkiä.</string>
<string name="perf_desktop_as_user">Työpöytä toimii käyttäjänä</string>
<string name="perf_desktop_as_user_hint">Työpöytä, sen sovellukset ja päätteet toimivat tavallisena käyttäjänä deck rootin sijaan, rootin torjuvia sovelluksia varten. sudo toimii edelleen. Koskee seuraavaa työpöytää.</string>
<string name="perf_desktop_as_user_needs_native">Vaatii Suorita ilman prootia.</string>
<string name="perf_phantom_warning">Android on asetettu lopettamaan tämä istunto</string>
<string name="driver_installed">Asennettu</string>
<string name="driver_available">Ladattavissa</string>
-3
View File
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nom d\'hôte</string>
<string name="perf_hostname_hint">Le nom sous lequel Steam voit cet appareil. Laisser vide pour restaurer %1$s.</string>
<string name="perf_hostname_invalid">Ne peut contenir que des lettres, des chiffres et des tirets au milieu, jusqu\'à 63 caractères.</string>
<string name="perf_desktop_as_user">Le bureau s’exécute en tant qu’utilisateur</string>
<string name="perf_desktop_as_user_hint">Le bureau, ses applications et ses terminaux s’exécutent en tant qu’utilisateur ordinaire deck au lieu de root, pour les applications qui refusent root. sudo fonctionne toujours. S’applique au prochain bureau.</string>
<string name="perf_desktop_as_user_needs_native">Nécessite Exécuter sans proot.</string>
<string name="perf_phantom_warning">Android est configuré pour terminer cette session</string>
<string name="driver_installed">Installé</string>
<string name="driver_available">Téléchargeable</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">होस्ट नाम</string>
<string name="perf_hostname_hint">वह नाम जो Steam इस डिवाइस के लिए देखता है। खाली छोड़ने पर %1$s वापस आ जाता है।</string>
<string name="perf_hostname_invalid">सिर्फ़ अक्षर, अंक और बीच के हाइफ़न, 63 वर्णों तक।</string>
<string name="perf_desktop_as_user">डेस्कटॉप उपयोगकर्ता के रूप में चलता है</string>
<string name="perf_desktop_as_user_hint">डेस्कटॉप, उसके ऐप और टर्मिनल root के बजाय सामान्य उपयोगकर्ता deck के रूप में चलते हैं, उन ऐप के लिए जो root को अस्वीकार करते हैं। sudo फिर भी काम करता है। अगले डेस्कटॉप पर लागू होता है।</string>
<string name="perf_desktop_as_user_needs_native">proot के बिना चलाएँ आवश्यक है।</string>
<string name="perf_phantom_warning">Android इस सेशन को बंद करने के लिए सेट है</string>
<string name="driver_installed">इंस्टॉल है</string>
<string name="driver_available">डाउनलोड के लिए उपलब्ध</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Hosztnév</string>
<string name="perf_hostname_hint">A név, amelyet a Steam ehhez az eszközhöz lát. Üresen hagyva visszaállítja: %1$s.</string>
<string name="perf_hostname_invalid">Csak betűk, számok és belső kötőjelek, legfeljebb 63 karakter.</string>
<string name="perf_desktop_as_user">Az asztal felhasználóként fut</string>
<string name="perf_desktop_as_user_hint">Az asztal, az alkalmazásai és a termináljai root helyett a deck nevű átlagos felhasználóként futnak, a root-ot elutasító alkalmazások miatt. A sudo továbbra is működik. A következő asztaltól érvényes.</string>
<string name="perf_desktop_as_user_needs_native">A Futtatás proot nélkül szükséges hozzá.</string>
<string name="perf_phantom_warning">Az Android be van állítva, hogy kilője ezt a munkamenetet</string>
<string name="driver_installed">Telepítve</string>
<string name="driver_available">Letölthető</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">Nama host</string>
<string name="perf_hostname_hint">Nama yang dilihat Steam untuk perangkat ini. Kosongkan untuk memulihkan %1$s.</string>
<string name="perf_hostname_invalid">Hanya huruf, angka, dan tanda hubung di tengah, hingga 63 karakter.</string>
<string name="perf_desktop_as_user">Desktop berjalan sebagai pengguna</string>
<string name="perf_desktop_as_user_hint">Desktop, aplikasi, dan terminalnya berjalan sebagai pengguna biasa deck, bukan root, untuk aplikasi yang menolak root. sudo tetap berfungsi. Berlaku untuk desktop berikutnya.</string>
<string name="perf_desktop_as_user_needs_native">Memerlukan Jalankan tanpa proot.</string>
<string name="perf_phantom_warning">Android diatur untuk menghentikan sesi ini</string>
<string name="driver_installed">Terinstal</string>
<string name="driver_available">Tersedia untuk diunduh</string>
-3
View File
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nome host</string>
<string name="perf_hostname_hint">Il nome con cui Steam vede questo dispositivo. Se vuoto, torna a %1$s.</string>
<string name="perf_hostname_invalid">Solo lettere, cifre e trattini interni, fino a 63 caratteri.</string>
<string name="perf_desktop_as_user">Il desktop viene eseguito come utente</string>
<string name="perf_desktop_as_user_hint">Il desktop, le sue app e i suoi terminali vengono eseguiti come utente normale deck invece che come root, per le app che rifiutano root. sudo funziona comunque. Si applica al prossimo desktop.</string>
<string name="perf_desktop_as_user_needs_native">Richiede Esegui senza proot.</string>
<string name="perf_phantom_warning">Android è impostato per terminare questa sessione</string>
<string name="driver_installed">Installati</string>
<string name="driver_available">Disponibili per il download</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">ホスト名</string>
<string name="perf_hostname_hint">Steamがこのデバイスを認識する名前。空にすると%1$sに戻ります。</string>
<string name="perf_hostname_invalid">英数字と中間のハイフンのみ使用でき、最大63文字です。</string>
<string name="perf_desktop_as_user">デスクトップをユーザーとして実行</string>
<string name="perf_desktop_as_user_hint">デスクトップとそのアプリやターミナルを root ではなく一般ユーザー deck として実行します。root を拒否するアプリ向けです。sudo は引き続き使えます。次回のデスクトップから適用されます。</string>
<string name="perf_desktop_as_user_needs_native">proot なしで実行が必要です。</string>
<string name="perf_phantom_warning">Androidがこのセッションを終了するように設定されています</string>
<string name="driver_installed">インストール済み</string>
<string name="driver_available">ダウンロード可能</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">호스트 이름</string>
<string name="perf_hostname_hint">Steam이 이 기기를 인식하는 이름입니다. 비워 두면 %1$s(으)로 복원됩니다.</string>
<string name="perf_hostname_invalid">영문, 숫자 및 중간 하이픈만 사용할 수 있으며 최대 63자입니다.</string>
<string name="perf_desktop_as_user">데스크톱을 사용자로 실행</string>
<string name="perf_desktop_as_user_hint">데스크톱과 앱, 터미널이 root 대신 일반 사용자 deck으로 실행됩니다. root를 거부하는 앱을 위한 설정입니다. sudo는 계속 사용할 수 있습니다. 다음 데스크톱부터 적용됩니다.</string>
<string name="perf_desktop_as_user_needs_native">proot 없이 실행이 필요합니다.</string>
<string name="perf_phantom_warning">Android가 이 세션을 종료하도록 설정했습니다</string>
<string name="driver_installed">설치됨</string>
<string name="driver_available">다운로드 가능</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">Nama hos</string>
<string name="perf_hostname_hint">Nama yang dilihat Steam untuk peranti ini. Kosongkan untuk memulihkan %1$s.</string>
<string name="perf_hostname_invalid">Huruf, digit dan tanda sempang dalaman sahaja, sehingga 63 aksara.</string>
<string name="perf_desktop_as_user">Desktop berjalan sebagai pengguna</string>
<string name="perf_desktop_as_user_hint">Desktop, aplnya dan terminalnya berjalan sebagai pengguna biasa deck dan bukan root, untuk apl yang menolak root. sudo masih berfungsi. Berkuat kuasa pada desktop seterusnya.</string>
<string name="perf_desktop_as_user_needs_native">Memerlukan Jalankan tanpa proot.</string>
<string name="perf_phantom_warning">Android ditetapkan untuk menamatkan sesi ini</string>
<string name="driver_installed">Dipasang</string>
<string name="driver_available">Tersedia untuk dimuat turun</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Vertsnavn</string>
<string name="perf_hostname_hint">Navnet Steam ser for denne enheten. Tomt gjenoppretter %1$s.</string>
<string name="perf_hostname_invalid">Bare bokstaver, tall og bindestreker inni navnet, opptil 63 tegn.</string>
<string name="perf_desktop_as_user">Skrivebordet kjører som bruker</string>
<string name="perf_desktop_as_user_hint">Skrivebordet, appene og terminalene kjører som den vanlige brukeren deck i stedet for root, for apper som avviser root. sudo virker fortsatt. Gjelder fra neste skrivebord.</string>
<string name="perf_desktop_as_user_needs_native">Krever Kjør uten proot.</string>
<string name="perf_phantom_warning">Android er satt til å avslutte denne sesjonen</string>
<string name="driver_installed">Installert</string>
<string name="driver_available">Tilgjengelig for nedlasting</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Hostnaam</string>
<string name="perf_hostname_hint">De naam die Steam voor dit apparaat ziet. Leeg herstelt %1$s.</string>
<string name="perf_hostname_invalid">Alleen letters, cijfers en koppeltekens binnen de naam, tot 63 tekens.</string>
<string name="perf_desktop_as_user">Bureaublad draait als gebruiker</string>
<string name="perf_desktop_as_user_hint">Het bureaublad, de apps en terminals draaien als de gewone gebruiker deck in plaats van root, voor apps die root weigeren. sudo werkt nog steeds. Geldt vanaf het volgende bureaublad.</string>
<string name="perf_desktop_as_user_needs_native">Vereist Uitvoeren zonder proot.</string>
<string name="perf_phantom_warning">Android is ingesteld om deze sessie te sluiten</string>
<string name="driver_installed">Geïnstalleerd</string>
<string name="driver_available">Beschikbaar om te downloaden</string>
-3
View File
@@ -650,9 +650,6 @@
<string name="perf_hostname">Nazwa hosta</string>
<string name="perf_hostname_hint">Nazwa tego urządzenia widoczna dla Steam. Puste pole przywraca %1$s.</string>
<string name="perf_hostname_invalid">Tylko litery, cyfry i łączniki w środku, do 63 znaków.</string>
<string name="perf_desktop_as_user">Pulpit działa jako użytkownik</string>
<string name="perf_desktop_as_user_hint">Pulpit, jego aplikacje i terminale działają jako zwykły użytkownik deck zamiast root, dla aplikacji, które odrzucają root. sudo nadal działa. Obowiązuje od następnego pulpitu.</string>
<string name="perf_desktop_as_user_needs_native">Wymaga Uruchamiaj bez proot.</string>
<string name="perf_phantom_warning">Android jest ustawiony tak, że zamknie tę sesję</string>
<string name="driver_installed">Zainstalowane</string>
<string name="driver_available">Do pobrania</string>
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nome do anfitrião</string>
<string name="perf_hostname_hint">O nome com que o Steam vê este dispositivo. Em branco, repõe %1$s.</string>
<string name="perf_hostname_invalid">Apenas letras, algarismos e hífenes interiores, até 63 carateres.</string>
<string name="perf_desktop_as_user">O ambiente de trabalho corre como utilizador</string>
<string name="perf_desktop_as_user_hint">O ambiente de trabalho, as suas apps e terminais correm como o utilizador comum deck em vez de root, para apps que recusam root. O sudo continua a funcionar. Aplica-se ao próximo ambiente de trabalho.</string>
<string name="perf_desktop_as_user_needs_native">Requer Executar sem proot.</string>
<string name="perf_phantom_warning">O Android está configurado para terminar esta sessão</string>
<string name="driver_installed">Instalado</string>
<string name="driver_available">Disponível para transferir</string>
-3
View File
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nome do host</string>
<string name="perf_hostname_hint">O nome que a Steam vê para este dispositivo. Em branco, volta a ser %1$s.</string>
<string name="perf_hostname_invalid">Só letras, dígitos e hifens internos, até 63 caracteres.</string>
<string name="perf_desktop_as_user">A área de trabalho roda como usuário</string>
<string name="perf_desktop_as_user_hint">A área de trabalho, seus apps e terminais rodam como o usuário comum deck em vez de root, para apps que recusam root. O sudo continua funcionando. Vale a partir da próxima área de trabalho.</string>
<string name="perf_desktop_as_user_needs_native">Requer Executar sem proot.</string>
<string name="perf_phantom_warning">O Android está configurado para encerrar esta sessão</string>
<string name="driver_installed">Instalados</string>
<string name="driver_available">Disponíveis para download</string>
-3
View File
@@ -648,9 +648,6 @@
<string name="perf_hostname">Nume de host</string>
<string name="perf_hostname_hint">Numele pe care Steam îl vede pentru acest dispozitiv. Gol restaurează %1$s.</string>
<string name="perf_hostname_invalid">Doar litere, cifre și liniuțe interioare, până la 63 de caractere.</string>
<string name="perf_desktop_as_user">Desktopul rulează ca utilizator</string>
<string name="perf_desktop_as_user_hint">Desktopul, aplicațiile și terminalele sale rulează ca utilizatorul obișnuit deck în loc de root, pentru aplicațiile care refuză root. sudo funcționează în continuare. Se aplică la următorul desktop.</string>
<string name="perf_desktop_as_user_needs_native">Necesită Rulează fără proot.</string>
<string name="perf_phantom_warning">Android este setat să închidă această sesiune</string>
<string name="driver_installed">Instalat</string>
<string name="driver_available">Disponibil pentru descărcare</string>
-3
View File
@@ -650,9 +650,6 @@
<string name="perf_hostname">Имя хоста</string>
<string name="perf_hostname_hint">Имя, под которым Steam видит это устройство. Оставьте пустым, чтобы вернуть %1$s.</string>
<string name="perf_hostname_invalid">Только буквы, цифры и дефисы посередине, до 63 символов.</string>
<string name="perf_desktop_as_user">Рабочий стол от имени пользователя</string>
<string name="perf_desktop_as_user_hint">Рабочий стол, его приложения и терминалы работают от имени обычного пользователя deck вместо root — для приложений, которые отказываются работать от root. sudo по-прежнему работает. Применяется к следующему запуску рабочего стола.</string>
<string name="perf_desktop_as_user_needs_native">Требуется «Запуск без proot».</string>
<string name="perf_phantom_warning">Android настроен на завершение этой сессии</string>
<string name="driver_installed">Установлен</string>
<string name="driver_available">Доступен для скачивания</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Värdnamn</string>
<string name="perf_hostname_hint">Namnet Steam ser för den här enheten. Lämna tomt för att återställa till %1$s.</string>
<string name="perf_hostname_invalid">Endast bokstäver, siffror och bindestreck inuti, upp till 63 tecken.</string>
<string name="perf_desktop_as_user">Skrivbordet körs som användare</string>
<string name="perf_desktop_as_user_hint">Skrivbordet, dess appar och terminaler körs som den vanliga användaren deck i stället för root, för appar som vägrar root. sudo fungerar fortfarande. Gäller från nästa skrivbord.</string>
<string name="perf_desktop_as_user_needs_native">Kräver Kör utan proot.</string>
<string name="perf_phantom_warning">Android är inställt på att avsluta den här sessionen</string>
<string name="driver_installed">Installerad</string>
<string name="driver_available">Tillgänglig att ladda ned</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">ชื่อโฮสต์</string>
<string name="perf_hostname_hint">ชื่อที่ Steam มองเห็นสำหรับอุปกรณ์นี้ เว้นว่างไว้เพื่อคืนค่าเป็น %1$s</string>
<string name="perf_hostname_invalid">ใช้ได้เฉพาะตัวอักษร ตัวเลข และยัติภังค์ตรงกลาง ไม่เกิน 63 ตัวอักษร</string>
<string name="perf_desktop_as_user">เดสก์ท็อปทำงานในฐานะผู้ใช้</string>
<string name="perf_desktop_as_user_hint">เดสก์ท็อป แอป และเทอร์มินัลจะทำงานในฐานะผู้ใช้ทั่วไป deck แทน root สำหรับแอปที่ไม่ยอมทำงานด้วย root sudo ยังใช้งานได้ มีผลกับเดสก์ท็อปครั้งถัดไป</string>
<string name="perf_desktop_as_user_needs_native">ต้องเปิด เรียกใช้โดยไม่มี proot</string>
<string name="perf_phantom_warning">Android ถูกตั้งให้ปิดเซสชันนี้</string>
<string name="driver_installed">ติดตั้งแล้ว</string>
<string name="driver_available">พร้อมดาวน์โหลด</string>
-3
View File
@@ -646,9 +646,6 @@
<string name="perf_hostname">Ana bilgisayar adı</string>
<string name="perf_hostname_hint">Steam\'in bu cihaz için gördüğü ad. Boş bırakılırsa %1$s geri yüklenir.</string>
<string name="perf_hostname_invalid">Yalnızca harf, rakam ve arada kısa çizgi; en fazla 63 karakter.</string>
<string name="perf_desktop_as_user">Masaüstü kullanıcı olarak çalışır</string>
<string name="perf_desktop_as_user_hint">Masaüstü, uygulamaları ve terminalleri root yerine sıradan kullanıcı deck olarak çalışır; root’u reddeden uygulamalar içindir. sudo çalışmaya devam eder. Bir sonraki masaüstünde geçerli olur.</string>
<string name="perf_desktop_as_user_needs_native">proot olmadan çalıştır gerekir.</string>
<string name="perf_phantom_warning">Android bu oturumu sonlandıracak şekilde ayarlı</string>
<string name="driver_installed">Yüklü</string>
<string name="driver_available">İndirilebilir</string>
-3
View File
@@ -650,9 +650,6 @@
<string name="perf_hostname">Ім’я хоста</string>
<string name="perf_hostname_hint">Ім’я, яке Steam бачить для цього пристрою. Порожнє значення відновлює %1$s.</string>
<string name="perf_hostname_invalid">Лише літери, цифри та дефіси всередині, до 63 символів.</string>
<string name="perf_desktop_as_user">Робочий стіл від імені користувача</string>
<string name="perf_desktop_as_user_hint">Робочий стіл, його застосунки й термінали працюють від імені звичайного користувача deck замість root — для застосунків, які відмовляються працювати від root. sudo і далі працює. Застосовується до наступного запуску робочого столу.</string>
<string name="perf_desktop_as_user_needs_native">Потрібен «Запуск без proot».</string>
<string name="perf_phantom_warning">Android налаштовано завершувати цей сеанс</string>
<string name="driver_installed">Встановлено</string>
<string name="driver_available">Доступно для завантаження</string>
-3
View File
@@ -644,9 +644,6 @@
<string name="perf_hostname">Tên máy chủ</string>
<string name="perf_hostname_hint">Tên mà Steam thấy cho thiết bị này. Để trống để khôi phục %1$s.</string>
<string name="perf_hostname_invalid">Chỉ chữ, số và gạch ngang ở giữa, tối đa 63 ký tự.</string>
<string name="perf_desktop_as_user">Màn hình nền chạy dưới dạng người dùng</string>
<string name="perf_desktop_as_user_hint">Màn hình nền, các ứng dụng và terminal của nó chạy dưới người dùng thường deck thay vì root, cho các ứng dụng từ chối root. sudo vẫn hoạt động. Áp dụng cho lần mở màn hình nền tiếp theo.</string>
<string name="perf_desktop_as_user_needs_native">Cần bật Chạy không cần proot.</string>
<string name="perf_phantom_warning">Android được đặt để tắt phiên này</string>
<string name="driver_installed">Đã cài</string>
<string name="driver_available">Có thể tải</string>
@@ -644,9 +644,6 @@
<string name="perf_hostname">主机名</string>
<string name="perf_hostname_hint">Steam 看到的本设备名称。留空恢复为 %1$s。</string>
<string name="perf_hostname_invalid">仅限字母、数字,连字符只能位于中间,最多 63 个字符。</string>
<string name="perf_desktop_as_user">桌面以普通用户运行</string>
<string name="perf_desktop_as_user_hint">桌面及其应用和终端以普通用户 deck 而非 root 运行,适用于拒绝以 root 运行的应用。sudo 仍可使用。下次启动桌面时生效。</string>
<string name="perf_desktop_as_user_needs_native">需要开启“不使用 proot 运行”。</string>
<string name="perf_phantom_warning">Android 将会终止此会话</string>
<string name="driver_installed">已安装</string>
<string name="driver_available">可下载</string>
@@ -644,9 +644,6 @@
<string name="perf_hostname">主機名稱</string>
<string name="perf_hostname_hint">Steam 看到的此裝置名稱。留空則還原為 %1$s。</string>
<string name="perf_hostname_invalid">只可使用字母、數字和中間的連字號,最多 63 個字元。</string>
<string name="perf_desktop_as_user">桌面以普通用戶執行</string>
<string name="perf_desktop_as_user_hint">桌面及其應用程式和終端機會以普通用戶 deck 而非 root 執行,適用於拒絕以 root 執行的應用程式。sudo 仍可使用。下次開啟桌面時生效。</string>
<string name="perf_desktop_as_user_needs_native">需要開啟「不使用 proot 執行」。</string>
<string name="perf_phantom_warning">Android 已設定為終止此會話</string>
<string name="driver_installed">已安裝</string>
<string name="driver_available">可供下載</string>
@@ -644,9 +644,6 @@
<string name="perf_hostname">主機名稱</string>
<string name="perf_hostname_hint">Steam 看到的此裝置名稱。留空可還原為 %1$s。</string>
<string name="perf_hostname_invalid">只能包含字母、數字和中間的連字號,最多 63 個字元。</string>
<string name="perf_desktop_as_user">桌面以一般使用者執行</string>
<string name="perf_desktop_as_user_hint">桌面及其應用程式和終端機會以一般使用者 deck 而非 root 執行,適用於拒絕以 root 執行的應用程式。sudo 仍可使用。下次開啟桌面時生效。</string>
<string name="perf_desktop_as_user_needs_native">需要開啟「不使用 proot 執行」。</string>
<string name="perf_phantom_warning">Android 已設定為結束此工作階段</string>
<string name="driver_installed">已安裝</string>
<string name="driver_available">可下載</string>
+1 -19
View File
@@ -678,9 +678,6 @@
<string name="perf_hostname">Host name</string>
<string name="perf_hostname_hint">The name Steam sees for this device. Blank restores %1$s.</string>
<string name="perf_hostname_invalid">Letters, digits and inner hyphens only, up to 63 characters.</string>
<string name="perf_desktop_as_user">Desktop runs as a user</string>
<string name="perf_desktop_as_user_hint">The desktop, its apps and its terminals run as the ordinary user deck instead of root, for apps that refuse root. sudo still works. Applies to the next desktop.</string>
<string name="perf_desktop_as_user_needs_native">Needs Run without proot.</string>
<string name="perf_phantom_warning">Android is set to kill this session</string>
<string name="driver_installed">Installed</string>
<string name="driver_available">Available to download</string>
@@ -710,22 +707,7 @@
<string name="drawer_next_page">Next page</string>
<string name="drawer_manage_pages">Arrange pages</string>
<string name="drawer_page_more">More</string>
<string name="drawer_page_performance">Performance</string>
<string name="drawer_page_game">Game</string>
<string name="drawer_page_vr">VR &amp; glasses</string>
<string name="drawer_section_pacing">Frame pacing</string>
<string name="drawer_section_mouse">Mouse</string>
<string name="drawer_section_keyboard_layout">Keyboard layout</string>
<string name="drawer_section_input">Input profile</string>
<string name="drawer_section_compat">Compatibility</string>
<string name="drawer_section_tuning">Fine tuning</string>
<string name="drawer_tag_controller">controller connected</string>
<string name="drawer_tag_no_controller">no controller</string>
<string name="drawer_tag_running">running</string>
<string name="drawer_tag_custom">custom look</string>
<string name="drawer_tag_attached">attached</string>
<string name="drawer_tag_downloading">downloading</string>
<string name="drawer_pause_game">Pause game</string> <string name="drawer_more_back">Back to %1$s</string>
<string name="drawer_more_back">Back to %1$s</string>
<string name="drawer_more_empty">Nothing is kept here. Arrange pages and move one below the More row.</string>
<string name="drawer_pages_reset">Reset</string>
<string name="drawer_pages_done">Done</string>
@@ -44,40 +44,6 @@ class ElfSeccompPatchTest {
}
}
@Test
fun terminalRequestsUseTheOnesAndroidAllowsOnAPseudoTerminal() {
// glibc 2.43's tcsetattr: TCSETS2 into x0, TCGETS2 into x1, with an unrelated instruction between
val data = elfWith(
0xd28a8560.toInt(), 0x910123e2.toInt(), 0xf2a80580.toInt(),
0xd28a8541.toInt(), 0x93407ea0.toInt(), 0xf2b00581.toInt(),
0x528a85a3.toInt(), 0x72a80583.toInt(),
)
assertEquals(3, ElfSeccompPatch.patch(data))
val b = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN)
val nop = 0xd503201f.toInt()
assertEquals(0xd28a8040.toInt(), b.getInt(0x100)) // mov x0, #0x5402 (TCSETS)
assertEquals(nop, b.getInt(0x108))
assertEquals(0xd28a8021.toInt(), b.getInt(0x10c)) // mov x1, #0x5401 (TCGETS)
assertEquals(nop, b.getInt(0x114))
assertEquals(0x528a8083.toInt(), b.getInt(0x118)) // mov w3, #0x5404 (TCSETSF)
assertEquals(nop, b.getInt(0x11c))
assertEquals(0, ElfSeccompPatch.patch(data))
}
@Test
fun aLookalikeConstantIsLeftAlone() {
// 0x542a with another high half, and one whose high half goes to another register
val data = elfWith(0xd28a8541.toInt(), 0xf2a00021.toInt(), 0xd28a8541.toInt(), 0xf2b00582.toInt())
assertEquals(0, ElfSeccompPatch.patch(data))
}
@Test
fun aSiteWhoseRegisterIsReadBeforeTheHighHalfIsLeftAlone() {
// movz x1, #0x542a; add x2, x1, #1; movk x1, #0x802c, lsl #16; movk x2, #0x402c, lsl #16
val data = elfWith(0xd28a8541.toInt(), 0x91000422.toInt(), 0xf2b00581.toInt(), 0xf2a80582.toInt())
assertEquals(0, ElfSeccompPatch.patch(data))
}
@Test
fun otherSystemCallsAreLeftAlone() {
val svc = 0xd4000001.toInt()
@@ -80,24 +80,6 @@ class OrientationTest {
assertFalse(SessionPrefs.portrait(landscape))
}
@Test fun modeOrientationControlsWindowFollowAndPortraitResolution() {
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, SessionPrefs.windowOrientation(context, true, 700, SessionService.MODE_STEAM))
SessionPrefs.setOrientation(context, "steam", ActivityInfo.SCREEN_ORIENTATION_USER)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(context, true, 700, SessionService.MODE_STEAM))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(context, false, 400, SessionService.MODE_RUN))
val config = android.content.res.Configuration(context.resources.configuration)
config.orientation = android.content.res.Configuration.ORIENTATION_PORTRAIT
val portrait = context.createConfigurationContext(config)
config.orientation = android.content.res.Configuration.ORIENTATION_LANDSCAPE
val landscape = context.createConfigurationContext(config)
assertTrue(SessionPrefs.portrait(portrait, SessionService.MODE_STEAM))
assertFalse(SessionPrefs.portrait(landscape, SessionService.MODE_STEAM))
assertTrue(SessionPrefs.portrait(landscape, SessionService.MODE_DESKTOP))
}
@Test fun invalidLauncherOrientationFallsBackAndInvalidChoicePreservesPreference() {
context.getSharedPreferences("app-ui", Context.MODE_PRIVATE).edit().putInt("orientation", 999).commit()
assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, AppUiPrefs.orientation(context))
@@ -106,20 +88,4 @@ class OrientationTest {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, AppUiPrefs.orientation(context))
}
@Test fun steamAndDesktopOrientationsAreIndependentAndFallBackToLegacyChoice() {
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context, "steam"))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, SessionPrefs.orientation(context, "desktop"))
SessionPrefs.setOrientation(context, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
SessionPrefs.setOrientation(context, "steam", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
SessionPrefs.setOrientation(context, "desktop", ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE)
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, "steam"))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_STEAM))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_RUN))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SessionPrefs.orientation(context, "desktop"))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE, SessionPrefs.orientation(context, SessionService.MODE_DESKTOP))
assertEquals(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, SessionPrefs.orientation(context))
}
}
@@ -30,16 +30,4 @@ class OutputPacingTest {
@Test fun mirroringKeepsTheGlassesRate() {
assertEquals(60, SessionPrefs.compositorFpsLimit(60))
}
@Test fun gameModeOverrideCapsAPanelThatRunsFaster() {
assertEquals(60, SessionPrefs.hostFrameCap(60.000004f, 120.00001f))
assertEquals(0, SessionPrefs.hostFrameCap(120.00001f, 120.00001f))
assertEquals(0, SessionPrefs.hostFrameCap(0f, 120f))
}
@Test fun hostCapPacesSteamSessionsAndYieldsToLowerLimits() {
assertEquals(60, SessionPrefs.compositorFpsLimit(0, 0, hostCap = 60))
assertEquals(45, SessionPrefs.compositorFpsLimit(0, 45, hostCap = 60))
assertEquals(SessionPrefs.PIP_FPS, SessionPrefs.compositorFpsLimit(0, 0, pip = true, hostCap = 60))
}
}
@@ -1,12 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.test.SemanticsNodeInteractionsProvider
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performScrollTo
/** Session menu groups start folded; a test opens the one whose rows it checks. */
internal fun SemanticsNodeInteractionsProvider.openSection(key: String) {
if (DrawerSectionState.isOpen(key)) return
onNodeWithTag("drawer-section-$key").performScrollTo().performClick()
}
@@ -227,81 +227,6 @@ class InputSurfaceTouchTest {
touch(MotionEvent.ACTION_UP, 1 to (750f to 285f))
}
@Test fun theMiddleOfACrossedDpadPressesTheNearestArmInsteadOfFallingThrough() {
val up = InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f)
val down = InputSurfaceElement(InputControl.DOWN, .45f, .45f, .1f, .15f)
show(up, down, InputSurfaceElement(InputControl.LEFT, .3f, .25f, .15f, .2f),
InputSurfaceElement(InputControl.RIGHT, .55f, .25f, .15f, .2f), a)
val missed = mutableListOf<Int>()
view.onTouchMiss = { missed += it.actionMasked }
touch(MotionEvent.ACTION_DOWN, 1 to (500f to 170f))
assertEquals(-1, state().hatY())
touch(MotionEvent.ACTION_MOVE, 1 to (540f to 215f))
assertEquals(1, state().hatX())
assertEquals(0, state().hatY())
touch(MotionEvent.ACTION_UP, 1 to (540f to 215f))
assertEquals(0, state().hatX())
assertTrue(missed.isEmpty())
assertFalse(view.takesTouchAt(250f, 210f))
assertFalse(view.takesTouchAt(800f, 500f))
assertFalse(view.takesTouchAt(350f, 100f))
show(up, down)
assertFalse(view.takesTouchAt(500f, 210f))
view.onTouchMiss = null
}
@Test fun aHandPlacedDpadWithOffArmsStillTakesItsMiddle() {
show(InputSurfaceElement(InputControl.UP, .42f, .1f, .1f, .15f),
InputSurfaceElement(InputControl.DOWN, .42f, .45f, .1f, .15f),
InputSurfaceElement(InputControl.LEFT, .3f, .27f, .15f, .15f),
InputSurfaceElement(InputControl.RIGHT, .5f, .25f, .15f, .2f))
touch(MotionEvent.ACTION_DOWN, 1 to (475f to 225f))
assertTrue(state().hatX() != 0 || state().hatY() != 0)
touch(MotionEvent.ACTION_UP, 1 to (475f to 225f))
assertFalse(view.takesTouchAt(750f, 225f))
}
@Test fun aTallGapPicksTheNearestArmAndSplitArmsAreNoCross() {
show(InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f),
InputSurfaceElement(InputControl.DOWN, .45f, .65f, .1f, .15f),
InputSurfaceElement(InputControl.LEFT, .3f, .35f, .15f, .2f),
InputSurfaceElement(InputControl.RIGHT, .55f, .35f, .15f, .2f))
touch(MotionEvent.ACTION_DOWN, 1 to (530f to 290f))
assertEquals(1, state().hatX())
assertEquals(0, state().hatY())
touch(MotionEvent.ACTION_UP, 1 to (530f to 290f))
touch(MotionEvent.ACTION_DOWN, 1 to (530f to 180f))
assertEquals(-1, state().hatY())
assertEquals(0, state().hatX())
touch(MotionEvent.ACTION_UP, 1 to (530f to 180f))
show(InputSurfaceElement(InputControl.UP, .2f, .1f, .1f, .15f),
InputSurfaceElement(InputControl.DOWN, .7f, .6f, .1f, .15f),
InputSurfaceElement(InputControl.LEFT, .1f, .35f, .15f, .2f),
InputSurfaceElement(InputControl.RIGHT, .8f, .35f, .15f, .2f))
assertFalse(view.takesTouchAt(500f, 300f))
}
@Test fun aSecondUpButtonDoesNotHideTheCross() {
show(InputSurfaceElement(InputControl.UP, .1f, .7f, .1f, .15f, "extra-up"),
InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f),
InputSurfaceElement(InputControl.DOWN, .45f, .45f, .1f, .15f),
InputSurfaceElement(InputControl.LEFT, .3f, .25f, .15f, .2f),
InputSurfaceElement(InputControl.RIGHT, .55f, .25f, .15f, .2f))
touch(MotionEvent.ACTION_DOWN, 1 to (500f to 170f))
assertEquals(-1, state().hatY())
touch(MotionEvent.ACTION_UP, 1 to (500f to 170f))
assertEquals(0, state().hatY())
show(InputSurfaceElement(InputControl.UP, .45f, 0f, .1f, .05f, "extra-up"),
InputSurfaceElement(InputControl.UP, .45f, .1f, .1f, .15f),
InputSurfaceElement(InputControl.DOWN, .45f, .45f, .1f, .15f),
InputSurfaceElement(InputControl.LEFT, .3f, .25f, .15f, .2f),
InputSurfaceElement(InputControl.RIGHT, .55f, .25f, .15f, .2f))
touch(MotionEvent.ACTION_DOWN, 1 to (490f to 170f))
assertEquals(-1, state().hatY())
assertEquals(0, state().hatX())
touch(MotionEvent.ACTION_UP, 1 to (490f to 170f))
}
@Test fun adaptiveSticksCaptureAroundThemAndTheLeftOneToTheEdge() {
val left = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, hideWhenIdle = true)
val right = InputSurfaceElement(InputControl.RS, .6f, .3f, .2f, .4f, hideWhenIdle = true)
@@ -77,17 +77,6 @@ class NavTabsTest {
assertFalse("desktop" in navigationKeys(s))
}
@Test fun moreStaysOnTheBarWhenNoTabIsShelvedSoTabsCanStillBeEdited() {
NavTabs.more(state()).forEach { place(it, TabPlace.HIDDEN) }
assertTrue(NavTabs.more(state()).isEmpty())
assertEquals(NavTabs.MORE, navigationKeys(state()).last())
NavTabs.reset(ctx)
NavTabs.more(state()).forEach { place(it, TabPlace.BAR) }
assertTrue(NavTabs.more(state()).isEmpty())
assertEquals(NavTabs.MORE, navigationKeys(state()).last())
assertEquals(1, navigationKeys(state()).count { it == NavTabs.MORE })
}
@Test fun appsAndTheDevHarnessCanBeShownWithoutHomeScreenOrDeveloperTools() {
place("android-apps", TabPlace.MORE)
assertTrue("android-apps" in NavTabs.more(state()))
@@ -31,9 +31,7 @@ class PenSettingsGroupTest {
@Test fun theDrawerHasNoPenGroupUntilAPenIsKnown() {
compose.setContent { DroidDeckTheme { SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(pen = null)) } }
compose.openSection("controller-touch")
compose.onNodeWithTag("setting-touch").assertExists()
compose.onNodeWithTag("drawer-section-controller-pen").assertDoesNotExist()
compose.onNodeWithTag("setting-pen").assertDoesNotExist()
compose.onNodeWithTag("setting-pen-button").assertDoesNotExist()
}
@@ -45,7 +43,6 @@ class PenSettingsGroupTest {
SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, actions(SessionPrefs.Pen()) { k, v -> picks += k to v })
}
}
compose.openSection("controller-pen")
compose.onNodeWithTag("setting-pen-button").performScrollTo().performClick()
compose.onNodeWithText(context.getString(R.string.gesture_middle_click)).performScrollTo().performClick()
compose.onNodeWithTag("setting-pen").performScrollTo().performClick()
@@ -4,51 +4,60 @@ import org.junit.Assert.*
import org.junit.Test
class SessionDrawerPageTest {
@Test fun navigationRunsControllerPerformanceDisplayEffectsGameVrSession() {
@Test fun navigationStartsWithControllerAndGoesStraightToDisplay() {
val pages = sessionDrawerPages(hasAgent = false)
assertEquals(
listOf(SessionDrawerPage.CONTROLLER, SessionDrawerPage.HUD, SessionDrawerPage.DISPLAY, SessionDrawerPage.EFFECTS,
SessionDrawerPage.GAMES, SessionDrawerPage.VR, SessionDrawerPage.SESSION, SessionDrawerPage.MORE),
pages.strip(),
)
assertEquals(SessionDrawerPage.MORE, pages.step(SessionDrawerPage.CONTROLLER, -1))
assertEquals(SessionDrawerPage.CONTROLLER, pages.first())
assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1))
assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.CONTROLLER, -1))
assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1))
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1))
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.EFFECTS, 1))
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
}
@Test fun achievementsAndTheAgentStartInsideMore() {
val pages = sessionDrawerPages(hasAchievements = true, hasAgent = true)
assertEquals(listOf(SessionDrawerPage.ACHIEVEMENTS, SessionDrawerPage.AGENT), pages.inMore())
assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.ACHIEVEMENTS))
@Test fun moreKeepsSteamVrByDefaultAndStandsInForThePagesInsideIt() {
val pages = sessionDrawerPages(hasAgent = false)
assertEquals(listOf(SessionDrawerPage.VR), pages.inMore())
assertEquals(SessionDrawerPage.MORE, pages.strip().last())
assertFalse(SessionDrawerPage.VR in pages.strip())
assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.VR))
assertEquals(SessionDrawerPage.GAMES, pages.tabFor(SessionDrawerPage.GAMES))
val strip = pages.strip()
assertEquals(SessionDrawerPage.CONTROLLER, strip.step(pages.tabFor(SessionDrawerPage.AGENT), 1))
}
@Test fun achievementsAreOfferedOnlyForAGameThatHasThem() {
assertFalse(SessionDrawerPage.ACHIEVEMENTS in sessionDrawerPages(hasAchievements = false, hasAgent = false))
assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false))
assertTrue(sessionDrawerPages(hasAgent = false).inMore().isEmpty())
assertEquals(SessionDrawerPage.MORE, strip.step(SessionDrawerPage.SESSION, 1))
assertEquals(SessionDrawerPage.CONTROLLER, strip.step(SessionDrawerPage.MORE, 1))
assertEquals(SessionDrawerPage.SESSION, strip.step(pages.tabFor(SessionDrawerPage.VR), -1))
}
@Test fun anOlderSavedOrderKeepsItsPagesAndGetsAMoreTabAfterSession() {
val saved = listOf("CONTROLLER", "GLASSES", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION")
val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "VR", "GAMES", "AGENT", "SESSION")
val out = DrawerPages.arrange(saved)
assertEquals(SessionDrawerPage.entries.toSet(), out.toSet())
assertEquals(SessionDrawerPage.MORE, out[out.indexOf(SessionDrawerPage.SESSION) + 1])
assertEquals(listOf(SessionDrawerPage.ACHIEVEMENTS), out.inMore())
assertTrue(SessionDrawerPage.AGENT in out.strip())
assertTrue(out.indexOf(SessionDrawerPage.VR) < out.indexOf(SessionDrawerPage.EFFECTS) + 2)
assertTrue(out.inMore().isEmpty())
}
@Test fun sessionCanBeKeptInsideMore() {
val saved = listOf("CONTROLLER", "DISPLAY", "HUD", "EFFECTS", "GAMES", "AGENT", "MORE", "SESSION", "VR")
val out = DrawerPages.arrange(saved)
assertEquals(listOf(SessionDrawerPage.ACHIEVEMENTS, SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore())
assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.VR), out.inMore())
assertFalse(SessionDrawerPage.SESSION in out.strip())
}
@Test fun moreAndSessionCannotBeHidden() {
assertFalse(DrawerPages.hideable(SessionDrawerPage.MORE))
assertFalse(DrawerPages.hideable(SessionDrawerPage.SESSION))
assertTrue(DrawerPages.hideable(SessionDrawerPage.HUD))
}
@Test fun glassesAddTheirPageAfterController() {
val pages = sessionDrawerPages(hasGlasses = true, hasAgent = false)
assertEquals(SessionDrawerPage.GLASSES, pages.step(SessionDrawerPage.CONTROLLER, 1))
assertEquals(sessionDrawerPages(hasAgent = false), pages.filter { it != SessionDrawerPage.GLASSES })
}
@Test fun theAgentPageComesBeforeSessionOnlyWhenTheTabIsShown() {
val with = sessionDrawerPages(hasAgent = true)
assertEquals(SessionDrawerPage.AGENT, with.step(SessionDrawerPage.GAMES, 1))
assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1))
assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false))
}
@Test fun arrangeKeepsSavedOrderAndSlotsNewPagesAfterTheirNeighbour() {
@@ -58,4 +67,9 @@ class SessionDrawerPageTest {
assertEquals(listOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD), out.filter { it in setOf(SessionDrawerPage.SESSION, SessionDrawerPage.HUD) })
assertTrue(out.indexOf(SessionDrawerPage.HUD) < out.indexOf(SessionDrawerPage.CONTROLLER))
}
@Test fun sessionPageCannotBeHidden() {
assertFalse(DrawerPages.hideable(SessionDrawerPage.SESSION))
assertTrue(DrawerPages.hideable(SessionDrawerPage.HUD))
}
}
@@ -130,8 +130,6 @@ class SessionSecondScreenTest {
actions(true, listOf(SecondScreenDisplay(1, "Bottom screen"), SecondScreenDisplay(2, "Monitor")), gameSwap = true))
}
}
compose.onNodeWithText(context.getString(R.string.swap_game_screen)).assertDoesNotExist()
compose.openSection("display-second")
compose.onNodeWithText(context.getString(R.string.swap_game_screen)).performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Bottom screen").performScrollTo().assertIsDisplayed()
}
@@ -267,7 +265,7 @@ class SessionSecondScreenTest {
state<Boolean>("drawerOpenState").value = true
state<Boolean>("drawerControllerActive").value = true
state<List<SecondScreenDisplay>>("secondScreenDisplays").value = listOf(SecondScreenDisplay(1, "Bottom screen"))
for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.HUD,
for ((button, page) in listOf(KeyEvent.KEYCODE_BUTTON_R1 to SessionDrawerPage.DISPLAY,
KeyEvent.KEYCODE_BUTTON_L1 to SessionDrawerPage.CONTROLLER)) {
assertTrue(activity.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, button, 0, 0,
device.id, 0, 0, InputDevice.SOURCE_GAMEPAD)))
@@ -311,7 +309,6 @@ class SessionSecondScreenTest {
actions(true, emptyList(), micAvailable = true, micEnabled = true, onMic = changes::add))
}
}
compose.openSection("session-behavior")
compose.onNodeWithTag("setting-microphone").assertIsEnabled()
.assert(SemanticsMatcher.expectValue(StateDescription, context.getString(R.string.widgets_on))).performClick()
assertEquals(listOf(false), changes)
@@ -325,7 +322,6 @@ class SessionSecondScreenTest {
actions(true, emptyList(), micAvailable = true, onMic = changes::add))
}
}
compose.openSection("session-behavior")
compose.onNodeWithTag("setting-microphone").assertIsEnabled()
.assert(SemanticsMatcher.expectValue(StateDescription, context.getString(R.string.widgets_off))).performClick()
assertEquals(listOf(true), changes)
@@ -337,7 +333,6 @@ class SessionSecondScreenTest {
SessionDrawer(true, SessionDrawerPage.SESSION, false, {}, actions(false, emptyList()))
}
}
compose.openSection("session-behavior")
compose.onNodeWithTag("setting-microphone").assertDoesNotExist()
compose.onNodeWithText(context.getString(R.string.mode_mic)).assertDoesNotExist()
}
@@ -359,7 +354,6 @@ class SessionSecondScreenTest {
onInputSelection = { panel.refreshControls() }, onClose = { open.value = false }))
}
}
compose.openSection("controller-input")
compose.onNodeWithTag("setting-input-profile").performScrollTo().performClick()
compose.onNodeWithText("Desktop").performScrollTo().performClick()
compose.onNodeWithTag("input-profile-expand").performScrollTo().performClick()
-1
View File
@@ -32,7 +32,6 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc
| Run without proot (experimental) | Settings › Performance (`droiddeck://settings/performance`) | proot |
| Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor |
| Host name | Settings › Performance (`droiddeck://settings/performance`) | name |
| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot |
| Controller | Settings › Controller (`droiddeck://settings/controller`) | gamepad, buttons, mapping, profile, remap |
| Smart glasses | Settings › Smart glasses (`droiddeck://settings/glasses`) | xreal, viture, vr, ar |
| Theme | Settings › Launcher (`droiddeck://settings/launcher`) | color, dark |
+1 -2
View File
@@ -86,8 +86,7 @@ RTD=$APP/.wayland-rt
export VK_ICD_FILENAMES=$PACK/adapter/icd.json ADRENOTOOLS_DRIVER_PATH=$DRVDIR/ ADRENOTOOLS_HOOKS_PATH=$PACK/lib
export ADRENOTOOLS_DRIVER_NAME=$(drvlib "$DRVDIR")
export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0}
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=0
echo "WSI forced XWayland bypass disabled (GAMESCOPE_WSI_FORCE_BYPASS=$GAMESCOPE_WSI_FORCE_BYPASS)"
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=1
[ -e "$RTD/droiddeck-gamescope-limiter" ] && export GAMESCOPE_LIMITER_FILE=$RTD/droiddeck-gamescope-limiter
# Wine: DXVK/VKD3D over the builtins, X11 inside gamescope (winewayland would pick DroidDeck's compositor),
+1 -11
View File
@@ -494,15 +494,5 @@ gamescope returned the buffer to the client on that release, and a client whose
fences attached to a dma-buf then drew into it while the display was still scanning it out, which showed as black
tiles in compressed buffers. A forwarded client buffer now stays held until `poll(POLLOUT)` on its dma-buf reports
that the display has finished with it, on a waiter thread so nothing else blocks. A release that arrives after the
buffer was shown again is dropped, so the later release decides. A pending wait holds its own reference on the
buffer, since that later release can drop the host's reference before the wait ends. Composite output images keep the 0146 path, and a
buffer was shown again is dropped, so the later release decides. Composite output images keep the 0146 path, and a
host that waits for the fence itself releases buffers that are already idle, so nothing changes there.
## 0148 Wayland backend: composite every frame when the host releases buffers before scanout
With 0147 a forwarded client buffer stays held until the display has finished scanning it out, about one refresh after
the host releases it. Steam's web helper cycles three buffers of its own, so forwarding them held the Steam UI at 80 fps
on a 120 Hz screen (frames alternately one and two refreshes apart). The first time a forwarded buffer comes back while
it is still being scanned out, the backend now composites every frame into its own output images. Those are reused at
latch under 0146, and the client's buffers return as soon as the composite has read them: the Steam UI then runs at
the full 120 fps. Hosts that release a buffer only after scanout never take this path and keep forwarding.
@@ -1,5 +1,5 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 12f0f50..d9db2e6 100644
index 12f0f50..a0fedd4 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -3,24 +3,28 @@
@@ -31,7 +31,7 @@ index 12f0f50..d9db2e6 100644
#include <libdecor.h>
#include "wlr_begin.hpp"
@@ -485,44 +489,86 @@ namespace gamescope
@@ -485,44 +489,82 @@ namespace gamescope
// One backing plane plus every layer steamcompmgr can hand us.
CWaylandPlane m_Planes[k_nMaxLayers + 1];
@@ -78,12 +78,8 @@ index 12f0f50..d9db2e6 100644
+ , m_nFd{ nFd }
+ , m_ulAcquireSerial{ ulAcquireSerial }
+ {
+ // A later acquire and release can drop the compositor's reference before this wait ends.
+ m_pFb->IncRef();
+ }
+
+ ~CWaylandScanoutRelease() { m_pFb->DecRef(); }
+
+ int GetFD() override { return m_nFd; }
+ void OnPollOut() override { Finish(); }
+ void OnPollHangUp() override { Finish(); }
@@ -119,7 +115,7 @@ index 12f0f50..d9db2e6 100644
~CWaylandInputThread();
bool Init( CWaylandBackend *pBackend );
@@ -969,73 +1015,108 @@ namespace gamescope
@@ -969,73 +1011,108 @@ namespace gamescope
.action = WAYLAND_NULL(),
};
const zwp_primary_selection_source_v1_listener CWaylandBackend::s_PrimarySelectionSourceListener =
@@ -239,7 +235,7 @@ index 12f0f50..d9db2e6 100644
, m_pBackend( pBackend )
, m_Planes{ this, this, this, this, this, this, this, this, this }
{
@@ -2349,25 +2430,26 @@ namespace gamescope
@@ -2349,25 +2426,26 @@ namespace gamescope
pDmaBuf->format,
0u );
@@ -1,116 +0,0 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index d9db2e6..5c4cd86 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -804,24 +804,31 @@ namespace gamescope
{
auto iter = m_pOutputs.find( pOutput );
if ( iter == m_pOutputs.end() )
return nullptr;
return &iter->second;
}
wl_region *GetEmptyRegion() const { return m_pEmptyRegion; }
wl_region *GetFullRegion() const { return m_pFullRegion; }
CWaylandFb *GetBlackFb() const { return m_BlackFb.get(); }
+ bool HostReleasesBeforeScanout() const { return m_bHostReleasesBeforeScanout; }
+ void OnHostReleasedBeforeScanout()
+ {
+ if ( !m_bHostReleasesBeforeScanout.exchange( true ) )
+ xdg_log.infof( "Host releases buffers before scanout ends: compositing every frame into our own images" );
+ }
+
void OnConnectorDestroyed( CWaylandConnector *pConnector )
{
m_pFocusConnector.compare_exchange_strong( pConnector, nullptr );
}
private:
void Wayland_Registry_Global( wl_registry *pRegistry, uint32_t uName, const char *pInterface, uint32_t uVersion );
static const wl_registry_listener s_RegistryListener;
void Wayland_Modifier( zwp_linux_dmabuf_v1 *pDmabuf, uint32_t uFormat, uint32_t uModifierHi, uint32_t uModifierLo );
@@ -871,24 +878,25 @@ namespace gamescope
wl_display *m_pDisplay = nullptr;
wl_shm *m_pShm = nullptr;
wl_compositor *m_pCompositor = nullptr;
wp_single_pixel_buffer_manager_v1 *m_pSinglePixelBufferManager = nullptr;
wl_subcompositor *m_pSubcompositor = nullptr;
zwp_linux_dmabuf_v1 *m_pLinuxDmabuf = nullptr;
xdg_wm_base *m_pXdgWmBase = nullptr;
wp_viewporter *m_pViewporter = nullptr;
wl_region *m_pEmptyRegion = nullptr;
wl_region *m_pFullRegion = nullptr;
Rc<CWaylandFb> m_BlackFb;
+ std::atomic<bool> m_bHostReleasesBeforeScanout = { false };
OwningRc<CWaylandFb> m_pOwnedBlackFb;
OwningRc<CVulkanTexture> m_pBlackTexture;
wp_presentation *m_pPresentation = nullptr;
droiddeck_refresh_v1 *m_pHostRefresh = nullptr;
std::array<uint32_t, 16> m_HostRefreshRates{};
std::atomic<uint32_t> m_uHostRefreshRateCount = { 0 };
std::vector<uint32_t> m_PendingHostRefreshRates;
int m_nSentHostRefresh = 0;
int m_nSentHostFrameRate = 0;
frog_color_management_factory_v1 *m_pFrogColorMgmtFactory = nullptr;
wp_color_manager_v1 *m_pWPColorManager = nullptr;
wp_image_description_v1 *m_pWPImageDescriptions[ GamescopeAppTextureColorspace_Count ]{};
@@ -1083,24 +1091,25 @@ namespace gamescope
xdg_log.errorf( "Compositor released us but we were not acquired. Oh no." );
}
void CWaylandFb::Wayland_Buffer_Release( wl_buffer *pBuffer )
{
assert( m_pHostBuffer );
assert( m_pHostBuffer == pBuffer );
xdg_log.debugf( "buffer_release: %p", pBuffer );
if ( ShowsClientBuffer() && gamescope::DmabufScanoutPending( m_nDmabufFd ) )
{
+ m_pBackend->OnHostReleasedBeforeScanout();
int nFd = fcntl( m_nDmabufFd, F_DUPFD_CLOEXEC, 0 );
if ( nFd >= 0 )
{
uint64_t ulSerial;
{
std::scoped_lock lock( m_AcquireMutex );
ulSerial = m_ulAcquireSerial;
}
auto *pWait = new CWaylandScanoutRelease( this, nFd, ulSerial );
if ( CWaylandScanoutRelease::Waiter().AddWaitable( pWait, EPOLLOUT | EPOLLHUP | EPOLLONESHOT ) )
return;
delete pWait;
@@ -1194,24 +1203,27 @@ namespace gamescope
plane.Present( nullptr );
}
else
{
// TODO: Dedupe some of this composite check code between us and drm.cpp
bool bLayer0ScreenSize = close_enough(pFrameInfo->layers.get( 0 ).scale.x, 1.0f) && close_enough(pFrameInfo->layers.get( 0 ).scale.y, 1.0f);
GamescopeUpscaleFilter eLayer0Filter = pFrameInfo->layers.get( 0 ).filter;
bool bNeedsCompositeFromFilter = ( eLayer0Filter == GamescopeUpscaleFilter::NEAREST ||
eLayer0Filter == GamescopeUpscaleFilter::PIXEL ) && !bLayer0ScreenSize;
bNeedsFullComposite |= cv_composite_force;
+ // A forwarded buffer would stay out of its client's hands until scanout ends, which caps a
+ // three-image client at two thirds of the refresh rate. Our own output images are reused at latch.
+ bNeedsFullComposite |= m_pBackend->HostReleasesBeforeScanout();
bNeedsFullComposite |= cv_wayland_overlay_planes >= 0 && pFrameInfo->layers.count() > 1 + cv_wayland_overlay_planes;
bNeedsFullComposite |= pFrameInfo->useFSRLayer0;
bNeedsFullComposite |= pFrameInfo->useNISLayer0;
bNeedsFullComposite |= pFrameInfo->useSGSRLayer0;
bNeedsFullComposite |= pFrameInfo->blurLayer0;
bNeedsFullComposite |= bNeedsCompositeFromFilter;
bNeedsFullComposite |= g_bColorSliderInUse;
bNeedsFullComposite |= pFrameInfo->bFadingOut;
bNeedsFullComposite |= !g_reshade_effect.empty();
if ( g_bOutputHDREnabled )
bNeedsFullComposite |= g_bHDRItmEnable;
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-17928792
GAMESCOPE_SHA256=b25680d5f81c8ba1f3e0f6f49894686a148baa296647c3bf3dafa3a04697b7c8
GAMESCOPE_TAG=gamescope-3.16.29-cb9c4861
GAMESCOPE_SHA256=89a3d70124a13bb5de0b4c67ff75d748a5d7ba6f29590194621754e3550b1f31
+1 -6
View File
@@ -233,12 +233,7 @@ return_gaming=/run/droiddeck/return-gaming
mkdir -p /run/droiddeck
rm -f "$return_gaming"
echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"
as_user=
if [ "${DD_DESKTOP_USER:-}" = 1 ] && [ -n "${DDNATV_ROOT:-}" ]; then
as_user=/usr/local/bin/droiddeck-user
echo "== droiddeck-desktop: Plasma runs as an ordinary user"
fi
$as_user dbus-run-session -- startplasma-wayland
dbus-run-session -- startplasma-wayland
rc=$?
/usr/local/bin/droiddeck-pipewire stop
echo "== droiddeck-desktop: Plasma ended ($rc)"
@@ -81,6 +81,10 @@ STEAM_VERBS = ("run", "waitforexitandrun")
ESCAPE = re.compile(rb"\\([0-7]{3})")
DEVICE_FONTS = "/usr/local/share/fonts/android"
FONT_RULES = "/etc/fonts/conf.d/66-droiddeck-device-fonts.conf"
PROC_MAPS = "/proc/self/maps"
JVM_DEPTH = 6
X86_ZGC_ADDRESS_BITS = 45
WITHOUT_ZGC = "-XX:+UnlockExperimentalVMOptions -XX:-UseZGC"
def say(message):
@@ -749,6 +753,47 @@ def vulkan_thunk_loads(fex, folder):
return True
def host_address_bits():
try:
with open(PROC_MAPS) as maps:
ends = [int(line.split("-", 1)[1].split(None, 1)[0], 16) for line in maps if "-" in line]
except (OSError, ValueError, IndexError):
return None
return max(ends).bit_length() if ends else None
def bundled_zgc_jvm(folder):
seen = 0
base = folder.rstrip("/").count("/")
for directory, dirs, files in os.walk(folder):
seen += 1
if seen > SCAN_LIMIT:
return None
if directory.count("/") - base >= JVM_DEPTH:
dirs[:] = []
jvm = os.path.join(directory, "libjvm.so")
if "libjvm.so" in files and elf_arch(jvm) == "x86_64":
try:
with open(jvm, "rb") as f:
if b"UseZGC" in f.read():
return jvm
except OSError:
pass
return None
def without_zgc(guest, folder):
bits = host_address_bits()
if bits is None or bits >= X86_ZGC_ADDRESS_BITS:
return
jvm = bundled_zgc_jvm(folder)
if not jvm:
return
guest["_JAVA_OPTIONS"] = " ".join(part for part in (guest.get("_JAVA_OPTIONS"), WITHOUT_ZGC) if part)
say("%s: ZGC cannot reserve its x86 heap in this device's %d-bit address space, so Java uses its default collector"
% (jvm, bits))
def required_runtime(program):
text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or ""
match = re.search(r'"require_tool_appid"\s+"(\d+)"', text)
@@ -777,6 +822,7 @@ def launch(command, env, mode, decide=None):
and vulkan_thunk_loads(fex, folder):
guest["LD_LIBRARY_PATH"] = ":".join(["/usr/" + VULKAN_PIN_DIR] + split_paths(guest.get("LD_LIBRARY_PATH")))
thunks = "on, its own Vulkan loader too"
without_zgc(guest, folder)
say("running %s with %s (runtime %s, thunks %s)" % (program, fex["bin"], guest.get("FEX_ROOTFS", "none"), thunks))
return os.execve(fex["bin"], [fex["bin"], program] + command[1:], guest)
@@ -569,10 +569,6 @@ if [ -z "${DD_INSIDE:-}" ]; then
fi
[ "$mode" = steam ] && args+=(--default-touch-mode 4)
[ "${DD_HDR:-0}" = 1 ] && args+=(--hdr-enabled)
# An SDR game reaches Android as its own SDR buffer, but whenever gamescope composites (a Steam
# toast, the volume slider) an HDR output encodes the frame in PQ, which the display tone-maps
# darker and shifted in colour. The output turns HDR only while a window presents HDR.
export gamescope_hdr_content_driven=1
[ -n "${DD_GAMESCOPE_ARGS:-}" ] && read -r -a _dd_extra <<<"$DD_GAMESCOPE_ARGS" && args+=("${_dd_extra[@]}")
if [ "$mode" = steam ] && [ "${DD_MANGOAPP:-1}" = 1 ] \
&& [ "${DD_STEAM_UI:-}" != desktop ] && command -v mangoapp >/dev/null 2>&1; then
@@ -1,15 +0,0 @@
#!/bin/sh
# Runs COMMAND, or a shell, as an ordinary user ("deck", the app's own Android user) instead of
# root, for programs that refuse root or check who owns their files. Everything started from it
# stays that user; sudo and su still give root, and exit goes back.
case ${1:-} in
-h|--help) echo "usage: droiddeck-user [COMMAND [ARG...]]"; exit 0 ;;
esac
if [ -z "${DDNATV_ROOT:-}" ]; then
echo "droiddeck-user: needs the native userland (Settings > Performance > Run without proot)" >&2
exit 1
fi
export DDNATV_BECOME=app USER=deck LOGNAME=deck
[ $# -gt 0 ] && exec "$@"
[ -t 2 ] && echo "Programs here run as an ordinary user (deck), not root. sudo still works; exit goes back." >&2
exec "${SHELL:-/bin/bash}"
-14
View File
@@ -17,20 +17,6 @@ same length: the code compares environment names by length) and extended with:
Build: `tools/nativeguest/build.sh out.so` with an aarch64 glibc cross compiler.
## Root or an ordinary user
Every program sees itself as root by default, which apt, dpkg and the session expect.
`DDNATV_USER=app` in a process's environment makes it, and everything it starts, the app's own
Android user instead, named `deck` (home `/root`): its ids, its files' owners, `/proc/*/status` and
peer credentials are the kernel's, and it may not change its ids. `DDNATV_BECOME=root` or `=app` in
a started program's environment switches that program and its children; the hook drops both
variables and puts `DDNATV_USER=app` first in the environment, where a peer's mode is read from
`/proc/<pid>/environ`. A set-user-ID program owned by the app (shown as root's) starts as root.
`droiddeck-user [COMMAND]` starts a shell or command that way, `sudo` and `su` return to root, and
Performance > "Desktop runs as a user" starts the whole Plasma session as `deck`. Statically linked
Go programs are patched once on disk and still see root.
## Testing under Android's seccomp filter
Some devices (eng builds, `setenforce 0` ROMs) run apps with no seccomp filter, so a hook that
+1 -17
View File
@@ -99,7 +99,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
int has_exec_loader = 0;
int has_preload_list = 0;
const char *preload_value = NULL;
const char *become = NULL;
while (envp && envp[count]) {
const char *e = envp[count];
switch (e[0]) {
@@ -128,7 +127,6 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
else if (strncmp(e, "DDNATV_HOSTNAME=", 16) == 0) has_hostname = 1;
else if (strncmp(e, "DDNATV_LINK_ROOT=", 17) == 0) has_link_root = 1;
else if (strncmp(e, "DDNATV_EXEC=", 12) == 0) has_exec_loader = 1;
else if (strncmp(e, "DDNATV_BECOME=", 14) == 0) become = e + 14;
else if (strncmp(e, "DPKG_DEB_THREADS_MAX=", 21) == 0) has_threads_max = 1;
else if (strncmp(e, "DEBIAN_FRONTEND=", 16) == 0) has_frontend = 1;
else if (strncmp(e, "DEBCONF_FRONTEND=", 17) == 0) has_debconf_frontend = 1;
@@ -140,23 +138,9 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
count++;
}
char **new_env = calloc(count + 26, sizeof(char *));
char **new_env = calloc(count + 25, sizeof(char *));
int dst = 0;
// The user the program runs as (hardlinks.c): this process's, whatever the environment it passes
// says, unless DDNATV_BECOME asks for one, or the program is set-user-ID root's (the app's files
// are root's), as the kernel would start it. First in the block, where a peer looks (sockets.c).
int as_app = app_user_mode();
if (become) as_app = strcmp(become, "app") == 0;
else if (as_app && real_exe && real_exe[0] == '/') {
struct stat st;
if (real_fstatat(AT_FDCWD, real_exe, &st, 0) == 0 && S_ISREG(st.st_mode) && (st.st_mode & S_ISUID)
&& st.st_uid == app_uid_now()) as_app = 0;
}
if (as_app) new_env[dst++] = strdup("DDNATV_USER=app");
for (int i = 0; i < count; i++) {
if (envp[i][0] == 'D' && (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0)) {
continue;
}
if (has_preload && envp[i][0] == 'L' && strncmp(envp[i], "LD_PRELOAD=", 11) == 0) {
// ld.so opens these itself: the guest's paths are mapped to the rootfs, and the libraries every
// program loads (DDNATV_PRELOAD) come first
+5 -3
View File
@@ -538,9 +538,11 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
errno = ELOOP;
ret = -1;
} else {
// The interpreter's exec prepares the environment, as posix_spawn's does: done here
// too, it dropped DDNATV_BECOME before the interpreter could take it (sudo SCRIPT)
ret = ddnatv_execve(rewritten_interp, new_argv, envp, depth + 1);
char **ddnatv_env = prepare_ddnatv_env(envp, NULL, NULL);
ret = ddnatv_execve(rewritten_interp, new_argv, ddnatv_env, depth + 1);
int saved_errno = errno;
free_modified_env(ddnatv_env, envp);
errno = saved_errno;
}
free(new_argv);
return ret;
+1 -1
View File
@@ -155,7 +155,7 @@ static void proc_status_root_ids(char *text, size_t len, const char *field, unsi
// The status file with the app's ids as root's, in a memory file; -2 when `path` is no such file
// or is opened for writing.
static int open_proc_status(const char *path, int flags) {
if ((flags & O_ACCMODE) != O_RDONLY || app_user_mode() || !is_proc_status_path(path) || !reader_compares_process_ids()) return -2;
if ((flags & O_ACCMODE) != O_RDONLY || !is_proc_status_path(path) || !reader_compares_process_ids()) return -2;
int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return -1;
char text[16384];
-48
View File
@@ -445,49 +445,6 @@ static void load_app_ids(void) {
__atomic_store_n(&g_app_uid, uid, __ATOMIC_RELAXED);
}
// DDNATV_USER=app: this process and what it starts run as the app's own user, an ordinary user
// ("deck"), instead of root. Its ids, its files' owners and its peers' ids are then the kernel's,
// so programs that refuse root (Firefox, Chromium, makepkg) or compare owners need no exception.
// DDNATV_BECOME in a started program's environment ("root" for sudo, "app" for droiddeck-user)
// changes the user for that program and everything it starts (env.c).
static int g_user_mode = -1;
static int app_user_mode(void) {
int mode = __atomic_load_n(&g_user_mode, __ATOMIC_RELAXED);
if (mode < 0) {
const char *value = getenv("DDNATV_USER");
mode = value && strcmp(value, "app") == 0;
__atomic_store_n(&g_user_mode, mode, __ATOMIC_RELAXED);
}
return mode;
}
static uid_t app_uid_now(void) {
if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids();
return __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED);
}
static gid_t app_gid_now(void) {
if (__atomic_load_n(&g_app_uid, __ATOMIC_RELAXED) == (uid_t)-1) load_app_ids();
return __atomic_load_n(&g_app_gid, __ATOMIC_RELAXED);
}
// What the process calls its own user and group: root's, or the app's in app user mode
static uid_t presented_uid(void) { return app_user_mode() ? app_uid_now() : 0; }
static gid_t presented_gid(void) { return app_user_mode() ? app_gid_now() : 0; }
// Whether a set*id() call may set these ids (-1 leaves one as it is): root may set any; an ordinary
// user only the one it has, as there is no other to have
static int may_set_ids(int group, uint32_t a, uint32_t b, uint32_t c) {
if (!app_user_mode()) return 1;
uint32_t own = group ? (uint32_t)app_gid_now() : (uint32_t)app_uid_now();
uint32_t ids[3] = {a, b, c};
for (int i = 0; i < 3; i++) {
if (ids[i] != UINT32_MAX && ids[i] != own) return 0;
}
return 1;
}
#define ANDROID_MEDIA_RW_GID ((gid_t)1023)
static void present_owner_as_root(uid_t *uid, gid_t *gid) {
@@ -495,11 +452,6 @@ static void present_owner_as_root(uid_t *uid, gid_t *gid) {
uid_t app_uid = __atomic_load_n(&g_app_uid, __ATOMIC_RELAXED);
gid_t app_gid = __atomic_load_n(&g_app_gid, __ATOMIC_RELAXED);
if (app_uid == (uid_t)-1) return;
if (app_user_mode()) {
// Shared storage is the user's, as it is root's otherwise
if (uid && gid && *gid == ANDROID_MEDIA_RW_GID) *uid = app_uid;
return;
}
if (uid && *uid == app_uid) *uid = 0;
if (uid && gid && *gid == ANDROID_MEDIA_RW_GID) *uid = 0;
if (gid && *gid == app_gid) *gid = 0;
+15 -100
View File
@@ -5,28 +5,20 @@
#ifndef DDNATV_HOST_TEST
// Fakeroot identity hooks for APT and DPKG to operate without superuser restrictions. In app user
// mode (hardlinks.c) the ids are the app's and may only be "changed" to themselves, as the kernel
// allows an ordinary user; Android's seccomp filter refuses the real calls to apps.
uid_t getuid(void) { return presented_uid(); }
uid_t geteuid(void) { return presented_uid(); }
gid_t getgid(void) { return presented_gid(); }
gid_t getegid(void) { return presented_gid(); }
// Fakeroot identity hooks for APT and DPKG to operate without superuser restrictions
uid_t getuid(void) { return 0; }
uid_t geteuid(void) { return 0; }
gid_t getgid(void) { return 0; }
gid_t getegid(void) { return 0; }
static int set_own_ids(int group, uint32_t a, uint32_t b, uint32_t c) {
if (may_set_ids(group, a, b, c)) return 0;
errno = EPERM;
return -1;
}
int setuid(uid_t uid) { return set_own_ids(0, uid, -1, -1); }
int seteuid(uid_t uid) { return set_own_ids(0, uid, -1, -1); }
int setgid(gid_t gid) { return set_own_ids(1, gid, -1, -1); }
int setegid(gid_t gid) { return set_own_ids(1, gid, -1, -1); }
int setreuid(uid_t ruid, uid_t euid) { return set_own_ids(0, ruid, euid, -1); }
int setregid(gid_t rgid, gid_t egid) { return set_own_ids(1, rgid, egid, -1); }
int setresuid(uid_t ruid, uid_t euid, uid_t suid) { return set_own_ids(0, ruid, euid, suid); }
int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { return set_own_ids(1, rgid, egid, sgid); }
int setuid(uid_t uid) { (void)uid; return 0; }
int seteuid(uid_t uid) { (void)uid; return 0; }
int setgid(gid_t gid) { (void)gid; return 0; }
int setegid(gid_t gid) { (void)gid; return 0; }
int setreuid(uid_t ruid, uid_t euid) { (void)ruid; (void)euid; return 0; }
int setregid(gid_t rgid, gid_t egid) { (void)rgid; (void)egid; return 0; }
int setresuid(uid_t ruid, uid_t euid, uid_t suid) { (void)ruid; (void)euid; (void)suid; return 0; }
int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { (void)rgid; (void)egid; (void)sgid; return 0; }
int getgroups(int size, gid_t list[]) {
if (size > 0 && list != NULL && syscall(__NR_getresgid, list, list, list) != 0) return -1;
@@ -40,14 +32,8 @@ int __getgroups_chk(int size, gid_t list[], size_t listlen) {
if (size > 0 && (size_t)size * sizeof(gid_t) > listlen) __chk_fail();
return getgroups(size, list);
}
int setgroups(size_t size, const gid_t *list) {
(void)size;
(void)list;
if (!app_user_mode()) return 0;
errno = EPERM;
return -1;
}
int initgroups(const char *user, gid_t group) { (void)user; return setgroups(1, &group); }
int setgroups(size_t size, const gid_t *list) { (void)size; (void)list; return 0; }
int initgroups(const char *user, gid_t group) { (void)user; (void)group; return 0; }
int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups) {
(void)user;
@@ -672,60 +658,12 @@ struct spwd *getspnam(const char *name) {
}
#endif /* !DDNATV_HOST_TEST */
// In app user mode the app's ids are an ordinary user, "deck", whose home is root's (where the
// session keeps everything). The rootfs lists the app's uid as root's for proot, so these come first.
#define DDNATV_APP_USER "deck"
static int app_user_passwd(const char *name, uid_t uid, int by_name, struct passwd *pwd, char *buf, size_t buflen) {
if (!app_user_mode()) return ENOENT;
if (by_name ? (!name || strcmp(name, DDNATV_APP_USER) != 0) : uid != app_uid_now()) return ENOENT;
static const char *const fields[] = {DDNATV_APP_USER, "x", "DroidDeck", "/root", "/bin/bash"};
size_t need = 0;
for (size_t i = 0; i < 5; i++) need += strlen(fields[i]) + 1;
if (!pwd || !buf || need > buflen) return ERANGE;
char *out[5];
char *cursor = buf;
for (size_t i = 0; i < 5; i++) {
size_t len = strlen(fields[i]) + 1;
memcpy(cursor, fields[i], len);
out[i] = cursor;
cursor += len;
}
pwd->pw_name = out[0];
pwd->pw_passwd = out[1];
pwd->pw_gecos = out[2];
pwd->pw_dir = out[3];
pwd->pw_shell = out[4];
pwd->pw_uid = app_uid_now();
pwd->pw_gid = app_gid_now();
return 0;
}
static int app_user_group(const char *name, gid_t gid, int by_name, struct group *grp, char *buf, size_t buflen) {
if (!app_user_mode()) return ENOENT;
if (by_name ? (!name || strcmp(name, DDNATV_APP_USER) != 0) : gid != app_gid_now()) return ENOENT;
size_t ptrs = 2 * sizeof(char *);
if (!grp || !buf || ptrs + sizeof(DDNATV_APP_USER) + 2 > buflen) return ERANGE;
char **members = (char **)buf;
char *cursor = buf + ptrs;
memcpy(cursor, DDNATV_APP_USER, sizeof(DDNATV_APP_USER));
grp->gr_name = cursor;
cursor += sizeof(DDNATV_APP_USER);
memcpy(cursor, "x", 2);
grp->gr_passwd = cursor;
members[0] = NULL;
grp->gr_mem = members;
grp->gr_gid = app_gid_now();
return 0;
}
static struct group s_grp_storage;
static char s_grp_buf[2048];
static struct passwd s_pwd_storage;
static char s_pwd_buf[2048];
struct group *DDNATV_NSS_SYM(getgrgid)(gid_t gid) {
if (app_user_group(NULL, gid, 0, &s_grp_storage, s_grp_buf, sizeof(s_grp_buf)) == 0) return &s_grp_storage;
#ifndef DDNATV_HOST_TEST
static struct group *(*orig_getgrgid)(gid_t) = NULL;
if (!orig_getgrgid) orig_getgrgid = (struct group *(*)(gid_t))dlsym(RTLD_NEXT, "getgrgid");
@@ -739,7 +677,6 @@ struct group *DDNATV_NSS_SYM(getgrgid)(gid_t gid) {
}
struct group *DDNATV_NSS_SYM(getgrnam)(const char *name) {
if (app_user_group(name, 0, 1, &s_grp_storage, s_grp_buf, sizeof(s_grp_buf)) == 0) return &s_grp_storage;
#ifndef DDNATV_HOST_TEST
static struct group *(*orig_getgrnam)(const char *) = NULL;
if (!orig_getgrnam) orig_getgrnam = (struct group *(*)(const char *))dlsym(RTLD_NEXT, "getgrnam");
@@ -753,11 +690,6 @@ struct group *DDNATV_NSS_SYM(getgrnam)(const char *name) {
}
int DDNATV_NSS_SYM(getgrgid_r)(gid_t gid, struct group *grp, char *buf, size_t buflen, struct group **result) {
int own = app_user_group(NULL, gid, 0, grp, buf, buflen);
if (own != ENOENT) {
if (result) *result = own == 0 ? grp : NULL;
return own;
}
#ifndef DDNATV_HOST_TEST
static int (*orig_getgrgid_r)(gid_t, struct group *, char *, size_t, struct group **) = NULL;
if (!orig_getgrgid_r) orig_getgrgid_r = (int (*)(gid_t, struct group *, char *, size_t, struct group **))dlsym(RTLD_NEXT, "getgrgid_r");
@@ -782,11 +714,6 @@ int DDNATV_NSS_SYM(getgrgid_r)(gid_t gid, struct group *grp, char *buf, size_t b
}
int DDNATV_NSS_SYM(getgrnam_r)(const char *name, struct group *grp, char *buf, size_t buflen, struct group **result) {
int own = app_user_group(name, 0, 1, grp, buf, buflen);
if (own != ENOENT) {
if (result) *result = own == 0 ? grp : NULL;
return own;
}
#ifndef DDNATV_HOST_TEST
static int (*orig_getgrnam_r)(const char *, struct group *, char *, size_t, struct group **) = NULL;
if (!orig_getgrnam_r) orig_getgrnam_r = (int (*)(const char *, struct group *, char *, size_t, struct group **))dlsym(RTLD_NEXT, "getgrnam_r");
@@ -829,7 +756,6 @@ static struct passwd *present_privsep_user_as_root(struct passwd *pwd) {
}
struct passwd *DDNATV_NSS_SYM(getpwuid)(uid_t uid) {
if (app_user_passwd(NULL, uid, 0, &s_pwd_storage, s_pwd_buf, sizeof(s_pwd_buf)) == 0) return &s_pwd_storage;
#ifndef DDNATV_HOST_TEST
static struct passwd *(*orig_getpwuid)(uid_t) = NULL;
if (!orig_getpwuid) orig_getpwuid = (struct passwd *(*)(uid_t))dlsym(RTLD_NEXT, "getpwuid");
@@ -843,7 +769,6 @@ struct passwd *DDNATV_NSS_SYM(getpwuid)(uid_t uid) {
}
struct passwd *DDNATV_NSS_SYM(getpwnam)(const char *name) {
if (app_user_passwd(name, 0, 1, &s_pwd_storage, s_pwd_buf, sizeof(s_pwd_buf)) == 0) return &s_pwd_storage;
#ifndef DDNATV_HOST_TEST
static struct passwd *(*orig_getpwnam)(const char *) = NULL;
if (!orig_getpwnam) orig_getpwnam = (struct passwd *(*)(const char *))dlsym(RTLD_NEXT, "getpwnam");
@@ -857,11 +782,6 @@ struct passwd *DDNATV_NSS_SYM(getpwnam)(const char *name) {
}
int DDNATV_NSS_SYM(getpwuid_r)(uid_t uid, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) {
int own = app_user_passwd(NULL, uid, 0, pwd, buf, buflen);
if (own != ENOENT) {
if (result) *result = own == 0 ? pwd : NULL;
return own;
}
#ifndef DDNATV_HOST_TEST
static int (*orig_getpwuid_r)(uid_t, struct passwd *, char *, size_t, struct passwd **) = NULL;
if (!orig_getpwuid_r) orig_getpwuid_r = (int (*)(uid_t, struct passwd *, char *, size_t, struct passwd **))dlsym(RTLD_NEXT, "getpwuid_r");
@@ -890,11 +810,6 @@ int DDNATV_NSS_SYM(getpwuid_r)(uid_t uid, struct passwd *pwd, char *buf, size_t
}
int DDNATV_NSS_SYM(getpwnam_r)(const char *name, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) {
int own = app_user_passwd(name, 0, 1, pwd, buf, buflen);
if (own != ENOENT) {
if (result) *result = own == 0 ? pwd : NULL;
return own;
}
#ifndef DDNATV_HOST_TEST
static int (*orig_getpwnam_r)(const char *, struct passwd *, char *, size_t, struct passwd **) = NULL;
if (!orig_getpwnam_r) orig_getpwnam_r = (int (*)(const char *, struct passwd *, char *, size_t, struct passwd **))dlsym(RTLD_NEXT, "getpwnam_r");
+27 -27
View File
@@ -529,7 +529,7 @@ static long nested_path_syscall(long number, unsigned long dirfd, unsigned long
static long fake_root_ids(long number, unsigned int *real, unsigned int *effective, unsigned int *saved) {
long rc = call_orig_syscall(number, (unsigned long)real, (unsigned long)effective, (unsigned long)saved, 0, 0, 0);
if (rc == 0 && !app_user_mode()) *real = *effective = *saved = 0;
if (rc == 0) *real = *effective = *saved = 0;
return rc;
}
@@ -821,82 +821,82 @@ long syscall(long number, ...) {
#endif
#if defined(__NR_setresuid)
if (number == __NR_setresuid) return (long)setresuid((uid_t)arg1, (uid_t)arg2, (uid_t)arg3);
if (number == __NR_setresuid) return 0;
#endif
#if defined(__NR_setresuid32)
if (number == __NR_setresuid32) return (long)setresuid((uid_t)arg1, (uid_t)arg2, (uid_t)arg3);
if (number == __NR_setresuid32) return 0;
#endif
#if defined(__NR_setresgid)
if (number == __NR_setresgid) return (long)setresgid((gid_t)arg1, (gid_t)arg2, (gid_t)arg3);
if (number == __NR_setresgid) return 0;
#endif
#if defined(__NR_setresgid32)
if (number == __NR_setresgid32) return (long)setresgid((gid_t)arg1, (gid_t)arg2, (gid_t)arg3);
if (number == __NR_setresgid32) return 0;
#endif
#if defined(__NR_setuid)
if (number == __NR_setuid) return (long)setuid((uid_t)arg1);
if (number == __NR_setuid) return 0;
#endif
#if defined(__NR_setuid32)
if (number == __NR_setuid32) return (long)setuid((uid_t)arg1);
if (number == __NR_setuid32) return 0;
#endif
#if defined(__NR_setgid)
if (number == __NR_setgid) return (long)setgid((gid_t)arg1);
if (number == __NR_setgid) return 0;
#endif
#if defined(__NR_setgid32)
if (number == __NR_setgid32) return (long)setgid((gid_t)arg1);
if (number == __NR_setgid32) return 0;
#endif
#if defined(__NR_setreuid)
if (number == __NR_setreuid) return (long)setreuid((uid_t)arg1, (uid_t)arg2);
if (number == __NR_setreuid) return 0;
#endif
#if defined(__NR_setreuid32)
if (number == __NR_setreuid32) return (long)setreuid((uid_t)arg1, (uid_t)arg2);
if (number == __NR_setreuid32) return 0;
#endif
#if defined(__NR_setregid)
if (number == __NR_setregid) return (long)setregid((gid_t)arg1, (gid_t)arg2);
if (number == __NR_setregid) return 0;
#endif
#if defined(__NR_setregid32)
if (number == __NR_setregid32) return (long)setregid((gid_t)arg1, (gid_t)arg2);
if (number == __NR_setregid32) return 0;
#endif
#if defined(__NR_setgroups)
if (number == __NR_setgroups) return (long)setgroups((size_t)arg1, (const gid_t *)arg2);
if (number == __NR_setgroups) return 0;
#endif
#if defined(__NR_setgroups32)
if (number == __NR_setgroups32) return (long)setgroups((size_t)arg1, (const gid_t *)arg2);
if (number == __NR_setgroups32) return 0;
#endif
#if defined(__NR_setfsuid)
if (number == __NR_setfsuid) return (long)presented_uid();
if (number == __NR_setfsuid) return 0;
#endif
#if defined(__NR_setfsuid32)
if (number == __NR_setfsuid32) return (long)presented_uid();
if (number == __NR_setfsuid32) return 0;
#endif
#if defined(__NR_setfsgid)
if (number == __NR_setfsgid) return (long)presented_gid();
if (number == __NR_setfsgid) return 0;
#endif
#if defined(__NR_setfsgid32)
if (number == __NR_setfsgid32) return (long)presented_gid();
if (number == __NR_setfsgid32) return 0;
#endif
#if defined(__NR_getuid)
if (number == __NR_getuid) return (long)presented_uid();
if (number == __NR_getuid) return 0;
#endif
#if defined(__NR_getuid32)
if (number == __NR_getuid32) return (long)presented_uid();
if (number == __NR_getuid32) return 0;
#endif
#if defined(__NR_geteuid)
if (number == __NR_geteuid) return (long)presented_uid();
if (number == __NR_geteuid) return 0;
#endif
#if defined(__NR_geteuid32)
if (number == __NR_geteuid32) return (long)presented_uid();
if (number == __NR_geteuid32) return 0;
#endif
#if defined(__NR_getgid)
if (number == __NR_getgid) return (long)presented_gid();
if (number == __NR_getgid) return 0;
#endif
#if defined(__NR_getgid32)
if (number == __NR_getgid32) return (long)presented_gid();
if (number == __NR_getgid32) return 0;
#endif
#if defined(__NR_getegid)
if (number == __NR_getegid) return (long)presented_gid();
if (number == __NR_getegid) return 0;
#endif
#if defined(__NR_getegid32)
if (number == __NR_getegid32) return (long)presented_gid();
if (number == __NR_getegid32) return 0;
#endif
#if defined(__NR_getresuid)
if (number == __NR_getresuid) return fake_root_ids(number, (unsigned int *)arg1, (unsigned int *)arg2, (unsigned int *)arg3);
-2
View File
@@ -36,8 +36,6 @@ static void init_ddnatv_hook(void) {
}
}
}
// The SIGSYS handler answers id calls with these and cannot look them up itself
if (app_user_mode()) load_app_ids();
ddnatv_load_binds(getenv("DDNATV_BINDS"), getenv("DDNATV_BINDS_KERNEL"));
const char *mount_table = getenv("DDNATV_MOUNTINFO");
if (mount_table && mount_table[0] == '/' && strlen(mount_table) < sizeof(g_mount_table))
-24
View File
@@ -33,27 +33,6 @@ static void remember_app_sigsys(const struct sigaction *act, struct sigaction *o
}
}
#if defined(__aarch64__)
// An id change the filter refused: root's succeed, an ordinary user's only to the ids it has (as in
// identity.c). setfsuid() and setfsgid() return the id they had.
static long sigsys_id_change(int nr, const unsigned long long *regs, long ret_val) {
if (!app_user_mode()) return ret_val;
uint32_t a = (uint32_t)regs[0], b = (uint32_t)regs[1], c = (uint32_t)regs[2];
switch (nr) {
case 146: return may_set_ids(0, a, UINT32_MAX, UINT32_MAX) ? 0 : -EPERM; // setuid
case 144: return may_set_ids(1, a, UINT32_MAX, UINT32_MAX) ? 0 : -EPERM; // setgid
case 145: return may_set_ids(0, a, b, UINT32_MAX) ? 0 : -EPERM; // setreuid
case 143: return may_set_ids(1, a, b, UINT32_MAX) ? 0 : -EPERM; // setregid
case 147: return may_set_ids(0, a, b, c) ? 0 : -EPERM; // setresuid
case 149: return may_set_ids(1, a, b, c) ? 0 : -EPERM; // setresgid
case 151: return (long)app_uid_now(); // setfsuid
case 152: return (long)app_gid_now(); // setfsgid
case 159: return -EPERM; // setgroups
default: return ret_val;
}
}
#endif
// Intercept SECCOMP blocked syscalls (SIGSYS), resolve sandbox/landlock gracefully, and advance PC
static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
if (!ctx || !info) return;
@@ -78,9 +57,6 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
int sys_nr = info->si_syscall;
long ret_val = is_sigsys_synthetic_success_syscall(sys_nr) ? 0 : -ENOSYS;
#if defined(__aarch64__)
ret_val = sigsys_id_change(sys_nr, uctx->uc_mcontext.regs, ret_val);
#endif
#if defined(__aarch64__)
uctx->uc_mcontext.regs[0] = (uint64_t)ret_val;
+2 -24
View File
@@ -234,31 +234,9 @@ ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags) {
return orig_sendmsg ? orig_sendmsg(sockfd, msg, flags) : -1;
}
// Whether process pid runs as the app's user (DDNATV_USER=app, which env.c puts first in the
// environment of every program it starts that way)
static int peer_runs_as_app(pid_t pid) {
if (pid <= 0) return 0;
if (pid == getpid()) return app_user_mode();
char path[48];
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
int fd = (int)call_orig_syscall(__NR_openat, AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0);
if (fd < 0) return 0;
// Servers that pass credentials get them with every message, so only the first entry is read
static const char k_var[] = "DDNATV_USER=app";
char buf[sizeof(k_var)];
long n = call_orig_syscall(__NR_read, fd, (unsigned long)buf, sizeof(buf), 0, 0, 0);
call_orig_syscall(__NR_close, fd, 0, 0, 0, 0, 0);
return n == (long)sizeof(buf) && memcmp(buf, k_var, sizeof(buf)) == 0;
}
// The app's ids are root's for a peer that runs as root, and its own for one that runs as the
// app's user, whichever this process is: a server compares them with what the peer says it is.
static void present_peer_as_root(struct ucred *cred) {
uid_t app_uid = (uid_t)call_orig_syscall(DDNATV_NR_REAL_GETUID, 0, 0, 0, 0, 0, 0);
gid_t app_gid = (gid_t)call_orig_syscall(DDNATV_NR_REAL_GETGID, 0, 0, 0, 0, 0, 0);
if ((cred->uid != app_uid && cred->gid != app_gid) || peer_runs_as_app(cred->pid)) return;
if (cred->uid == app_uid) cred->uid = 0;
if (cred->gid == app_gid) cred->gid = 0;
if (cred->uid == (uid_t)call_orig_syscall(DDNATV_NR_REAL_GETUID, 0, 0, 0, 0, 0, 0)) cred->uid = 0;
if (cred->gid == (gid_t)call_orig_syscall(DDNATV_NR_REAL_GETGID, 0, 0, 0, 0, 0, 0)) cred->gid = 0;
}
// A server compares a peer's credentials with the user the peer claims, which is getuid()'s 0
+43
View File
@@ -52,6 +52,7 @@ class FexTestCase(unittest.TestCase):
"FONT_RULES": str(self.tmp / "66-droiddeck-device-fonts.conf"),
"OWN_FEX": str(self.tmp / "own"),
"OWN_FEX_TAG": str(self.tmp / "own/share/fex-emu/.droiddeck-tag"),
"PROC_MAPS": str(self.tmp / "maps"),
}
patcher = mock.patch.dict(G, patches)
patcher.start()
@@ -1269,6 +1270,48 @@ class LaunchTest(FexTestCase):
native.assert_called_once()
emulated.assert_not_called()
def test_a_bundled_java_runtime_leaves_zgc_when_its_x86_heap_cannot_fit(self):
self.fex_tool()
self.runtime()
maps = self.tmp / "maps"
def host(top):
maps.write_text("5580000000-5580001000 r-xp 00000000 fe:00 1 /usr/bin/python3\n"
"%x-%x rw-p 00000000 00:00 0 [stack]\n" % (top - 0x21000, top))
def app(name, jvm=elf(62) + b"\0UseZGC\0UseG1GC\0", where="usr/lib/game/runtime/lib/server"):
run = self.write(self.tmp / name / "AppRun", "#!/bin/sh\n", 0o755)
if jvm is not None:
self.write(self.tmp / name / where / "libjvm.so", jvm)
return run
def started(program, env=None):
with mock.patch("os.execve") as emulated:
_, said = self.quiet(FEX["launch"], [str(program)], dict(env or {}), "on")
return emulated.call_args[0][2], said
host(0x7FFFFFF000)
env, said = started(app("zgc"))
self.assertEqual(env["_JAVA_OPTIONS"], "-XX:+UnlockExperimentalVMOptions -XX:-UseZGC")
self.assertIn("39-bit address space", said)
env, _ = started(app("zgc"), {"_JAVA_OPTIONS": "-Xmx2g"})
self.assertEqual(env["_JAVA_OPTIONS"], "-Xmx2g -XX:+UnlockExperimentalVMOptions -XX:-UseZGC")
env, _ = started(app("jdk8", where="jre/lib/amd64/server", jvm=elf(62) + b"\0UseG1GC\0"))
self.assertNotIn("_JAVA_OPTIONS", env)
env, _ = started(app("arm-jvm", jvm=elf(183) + b"\0UseZGC\0"))
self.assertNotIn("_JAVA_OPTIONS", env)
env, said = started(app("no-java", jvm=None), {"_JAVA_OPTIONS": "-Xmx2g"})
self.assertEqual(env["_JAVA_OPTIONS"], "-Xmx2g")
self.assertNotIn("ZGC", said)
env, _ = started(app("too-deep", where="a/b/c/d/e/f/g/server"))
self.assertNotIn("_JAVA_OPTIONS", env)
host(0xFFFFFFFFF000)
env, _ = started(app("zgc"))
self.assertNotIn("_JAVA_OPTIONS", env)
maps.unlink()
env, _ = started(app("zgc"))
self.assertNotIn("_JAVA_OPTIONS", env)
def test_programs_that_bring_a_new_enough_runtime_get_the_vulkan_thunk(self):
tool = self.fex_tool()
self.runtime()
@@ -136,21 +136,10 @@ int main( int argc, char **argv ) {
assert( fb.refs == 2 );
d.scanning();
fb.Wayland_Buffer_Release( fb.m_pHostBuffer );
assert( fb.refs == 3 && fb.m_bCompositorAcquired );
assert( fb.refs == 2 && fb.m_bCompositorAcquired );
d.done();
fire();
assert( fb.refs == 1 && !fb.m_bCompositorAcquired && xdg_log.oh_no == 0 );
} else if ( which == "stale-wait-keeps-buffer" ) {
fb.client = true;
fb.OnCompositorAcquire();
d.scanning();
fb.Wayland_Buffer_Release( fb.m_pHostBuffer );
fb.OnCompositorAcquire();
d.done();
fb.Wayland_Buffer_Release( fb.m_pHostBuffer );
assert( fb.refs == 2 && !fb.m_bCompositorAcquired );
fire();
assert( fb.refs == 1 && xdg_log.oh_no == 0 );
} else if ( which == "client-idle" ) {
fb.client = true;
fb.OnCompositorAcquire();
@@ -225,9 +214,6 @@ class ForwardedBufferScanoutTest(unittest.TestCase):
def test_buffer_shown_again_waits_for_its_next_release(self):
self.scenario("shown-again")
def test_pending_wait_keeps_the_buffer_after_a_later_release(self):
self.scenario("stale-wait-keeps-buffer")
def test_buffer_without_dmabuf_is_released_at_once(self):
self.scenario("no-dmabuf")
-172
View File
@@ -1,172 +0,0 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
# After the hook: prints the environment the hook hands the next program
RECORDER = r"""
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int execve(const char *path, char *const argv[], char *const envp[]) {
(void)path; (void)argv;
for (int i = 0; envp[i]; i++) {
if (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0)
printf("env\t%d\t%s\n", i, envp[i]);
}
printf("exec\n");
fflush(stdout);
_exit(0);
}
"""
PROBE = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <grp.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (argc > 1 && strcmp(argv[1], "exec") == 0) {
char *envp[] = {"PATH=/bin", argc > 2 ? argv[2] : NULL, NULL};
const char *program = argc > 3 ? argv[3] : "/bin/true";
char *args[] = {(char *)program, NULL};
execve(program, args, envp);
return 1;
}
printf("ids\t%u\t%u\t%u\t%u\n", getuid(), geteuid(), getgid(), getegid());
printf("syscall\t%ld\n", syscall(SYS_getuid));
struct passwd *pw = getpwuid(getuid());
printf("user\t%s\t%s\n", pw ? pw->pw_name : "-", pw ? pw->pw_dir : "-");
struct passwd *root = getpwnam("root");
printf("root\t%u\n", root ? root->pw_uid : 999);
struct group *gr = getgrgid(getgid());
printf("group\t%s\n", gr ? gr->gr_name : "-");
struct stat st;
stat("/bin/true", &st);
printf("owner\t%d\n", st.st_uid == getuid());
errno = 0;
int to_root = setuid(0);
printf("setuid0\t%d\t%d\n", to_root, errno);
printf("setuid_own\t%d\n", setuid(getuid()));
int sv[2];
socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
pid_t child = fork();
if (child == 0) { pause(); _exit(0); }
struct ucred cred;
socklen_t len = sizeof(cred);
getsockopt(sv[0], SOL_SOCKET, SO_PEERCRED, &cred, &len);
printf("peer\t%d\n", cred.uid == getuid());
kill(child, 9);
waitpid(child, NULL, 0);
return 0;
}
"""
class NativeHookUserModeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "recorder.c").write_text(RECORDER)
cls.recorder = tmp / "recorder.so"
subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.root = tmp / "root"
(cls.root / "bin").mkdir(parents=True)
(cls.root / "etc").mkdir()
(cls.root / "etc/passwd").write_text(f"root:x:{os.getuid()}:{os.getgid()}:root:/root:/bin/bash\nroot:x:0:0:root:/root:/bin/bash\n")
(cls.root / "bin/true").write_text("")
(cls.root / "bin/true").chmod(0o755)
(cls.root / "bin/script").write_text("#!/bin/true\n")
(cls.root / "bin/script").chmod(0o755)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_probe(self, *args, user=None):
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"}
if user:
hook_env["DDNATV_USER"] = user
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_USER")}
if user:
# A peer's user is the first entry of /proc/PID/environ, which under qemu is qemu's own
env = {"DDNATV_USER": user, **env}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(self.probe), *args], env=env, capture_output=True, text=True, timeout=120)
result = {}
for line in out.stdout.splitlines():
key, *values = line.split("\t")
result.setdefault(key, []).append(values)
self.assertTrue(result, out.stdout + out.stderr)
return result
def test_programs_are_root_by_default(self):
r = self.run_probe()
self.assertEqual([["0", "0", "0", "0"]], r["ids"])
self.assertEqual([["0"]], r["syscall"])
self.assertEqual("root", r["user"][0][0])
self.assertEqual([["1"]], r["owner"])
self.assertEqual([["0", "0"]], r["setuid0"])
self.assertEqual([["1"]], r["peer"])
def test_the_app_user_sees_its_real_ids_and_cannot_become_root(self):
uid, gid = os.getuid(), os.getgid()
if uid == 0:
self.skipTest("the app's user is root's uid on this runner, so root's ids are its own")
r = self.run_probe(user="app")
self.assertEqual([[str(uid), str(uid), str(gid), str(gid)]], r["ids"])
self.assertEqual([[str(uid)]], r["syscall"])
self.assertEqual([["deck", "/root"]], r["user"])
self.assertEqual([["deck"]], r["group"])
self.assertEqual([["0"]], r["root"])
self.assertEqual([["1"]], r["owner"])
self.assertEqual([["-1", "1"]], r["setuid0"])
self.assertEqual([["0"]], r["setuid_own"])
self.assertEqual([["1"]], r["peer"])
def test_programs_an_app_user_starts_stay_that_user_whatever_their_environment(self):
r = self.run_probe("exec", "DDNATV_USER=root", user="app")
self.assertEqual([["0", "DDNATV_USER=app"]], r["env"])
def test_become_switches_the_started_program_once(self):
self.assertNotIn("env", self.run_probe("exec", "DDNATV_BECOME=root", user="app"))
self.assertEqual([["0", "DDNATV_USER=app"]], self.run_probe("exec", "DDNATV_BECOME=app")["env"])
def test_become_reaches_a_scripts_interpreter(self):
self.assertNotIn("env", self.run_probe("exec", "DDNATV_BECOME=root", "/bin/script", user="app"))
self.assertEqual([["0", "DDNATV_USER=app"]], self.run_probe("exec", "DDNATV_BECOME=app", "/bin/script")["env"])
def test_root_never_passes_an_app_user_on(self):
self.assertNotIn("env", self.run_probe("exec", "DDNATV_USER=app"))
if __name__ == "__main__":
unittest.main()
+5 -14
View File
@@ -15,8 +15,6 @@ SRC = TESTS.parents[1] / "app/src/main/cpp/waylandcomp/src"
LAYER_HARNESS = r'''
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <vulkan/vulkan.h>
#include "vk_external_image_sync.h"
#include "vk_linear_dmabuf.h"
@@ -44,11 +42,6 @@ static const uint32_t g_qfam = 2;
%(width)s
%(height)s
static int black_fill_below(const struct draw_list *dl, int n) { (void)dl; (void)n; return 0; }
#define LAYER_CANDIDATE_DIAGNOSTICS 32u
static unsigned g_layer_candidate_diag_count;
static int g_layer_candidate_diag_limit;
static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; }
%(candidate_skip)s
%(candidate)s
static int candidate(struct vkp_image *img) {
@@ -142,7 +135,6 @@ class VkLinearDmabufTest(unittest.TestCase):
"is_dmabuf": function(vk, "vkp_image_is_dmabuf"),
"width": function(vk, "vkp_image_width"),
"height": function(vk, "vkp_image_height"),
"candidate_skip": function(comp, "note_layer_candidate_skip"),
"candidate": function(comp, "layer_candidate"),
}
with tempfile.TemporaryDirectory(prefix="droiddeck-vk-linear-layer-") as tmp:
@@ -152,11 +144,10 @@ class VkLinearDmabufTest(unittest.TestCase):
def test_layer_import_failure_requests_compositor_fallback(self):
source = (SRC / "sc_layer.c").read_text()
game = function(source, "sc_layer_present")
self.assertRegex(game, r"if \(idx < 0\) \{\s*log_drop\(l\);\s*if \(g_alloc_failed\) return -1;")
self.assertRegex(function(source, "overlay_slot"),
r"if \(\*idx < 0\) \{ log_drop\(l\); return g_alloc_failed \? -1 : 0; \}")
self.assertIn("overlay_slot(", function(source, "sc_layer_present_overlay"))
for name in ("sc_layer_present", "sc_layer_present_overlay"):
with self.subTest(layer=name):
body = function(source, name)
self.assertRegex(body, r"if \(idx < 0\) \{ log_drop\(l\); return g_alloc_failed \? -1 : 0; \}")
def test_layer_blits_use_the_imported_output_row_pitch(self):
source = (SRC / "vk_present.c").read_text()
@@ -165,7 +156,7 @@ class VkLinearDmabufTest(unittest.TestCase):
self.assertLess(blit.index("VkBufferImageCopy copy = dst->linear_copy"), copy)
self.assertLess(blit.index("VK_ACCESS_TRANSFER_WRITE_BIT, 1"), copy)
self.assertGreater(blit.index("VK_ACCESS_TRANSFER_WRITE_BIT, 0"), copy)
for name in ("vkp_blit_images", "pass_finish"):
for name in ("vkp_blit_image", "pass_finish"):
self.assertIn("blit_to_layer(", function(source, name))
-3
View File
@@ -117,9 +117,6 @@ int __android_log_print(int, const char *, const char *, ...);
def test_blit_wait_error_same_size_pixel_upload(self):
self.run_scenario('pixel-wait-error')
def test_layer_copies_share_one_submit_and_wait(self):
self.run_scenario('blit-batched')
def test_lost_device_shm_upload_keeps_cpu_snapshot(self):
self.run_scenario('lost-shm-upload')
-146
View File
@@ -1,146 +0,0 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
from test_vk_pending_completion import function
ROOT = Path(__file__).resolve().parents[2]
SRC = ROOT / 'app/src/main/cpp/waylandcomp/src'
HARNESS = r'''
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#include <wayland-util.h>
struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); };
struct wl_event_source;
struct wl_client;
struct wl_resource;
struct surface { int unused; };
struct vkp_draw { int unused; };
struct dmabuf_buffer { int fd; void *slot; };
typedef struct AHardwareBuffer { int unused; } AHardwareBuffer;
DEFINES
STRUCT
static unsigned g_stat_zero_copy;
static int g_export_failed_logged;
static struct surface *g_announced;
static volatile int64_t g_last_zero_copy_ns;
static int export_ok, exports, presents, presented_acquire, logs, polls;
static int fake_ioctl(int fd, unsigned long req, void *arg) {
struct droiddeck_dma_buf_sync_file *f = arg;
(void)fd;
assert(req == DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE && f->flags == DROIDDECK_DMA_BUF_SYNC_READ);
++exports;
if (!export_ok) { errno = ENOTTY; return -1; }
f->fd = dup(0);
return 0;
}
#define ioctl fake_ioctl
static int fake_poll(struct pollfd *p, nfds_t n, int timeout) {
assert(n == 1 && p->events == POLLIN && timeout == 100);
++polls; p->revents = POLLIN; return 1;
}
#define poll fake_poll
static int64_t now_ns(void) { return 1; }
static void **droiddeck_dmabuf_ahb_slot(struct dmabuf_buffer *b) { return &b->slot; }
static int droiddeck_dmabuf_fd(struct dmabuf_buffer *b) { return b->fd; }
static const void *droiddeck_surface_color(struct surface *s) { (void)s; return NULL; }
static void droiddeck_surface_describe(struct surface *s, char *out, size_t n) { (void)s; snprintf(out, n, "game"); }
static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; ++logs; }
static int sc_layer_present_ahb(AHardwareBuffer *a, int w, int h, int acquire, void *token, int sw, int sh,
const struct vkp_draw *d, const void *color, uint32_t format) {
(void)a; (void)w; (void)h; (void)token; (void)sw; (void)sh; (void)d; (void)color; (void)format;
++presents; presented_acquire = acquire;
if (acquire >= 0) close(acquire);
return 0;
}
FUNCTIONS
static void run(int fd, int can_export, int copyable) {
struct dmabuf_buffer b = {.fd = fd};
struct vkp_draw d;
const struct vkp_draw *draw = copyable ? &d : NULL;
struct ahb_buf ab;
struct surface s;
memset(&ab, 0, sizeof(ab));
ab.id = 7; ab.w = 64; ab.h = 64; ab.fence_fd = -1;
b.slot = &ab;
export_ok = can_export;
int r = ahb_swapchain_present(&b, &s, 64, 64, draw);
if (fd >= 0 && can_export) {
assert(r == 0 && presents == 1 && presented_acquire >= 0 && ab.on_layer && g_stat_zero_copy == 1 && polls == 0);
} else if (copyable) {
assert(r == -1 && presents == 0 && !ab.on_layer && g_stat_zero_copy == 0 && polls == (fd >= 0));
r = ahb_swapchain_present(&b, &s, 64, 64, draw);
assert(r == -1 && presents == 0 && logs == 1);
} else {
assert(r == 0 && presents == 1 && presented_acquire == -1 && ab.on_layer && polls == (fd >= 0));
}
}
int main(int argc, char **argv) {
assert(argc == 4);
run(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]));
return 0;
}
'''
class ZeroCopyAcquireFenceTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cc = shutil.which(os.environ.get('CC', 'cc'))
if not cc:
raise AssertionError('C compiler required')
ahb = (SRC / 'ahb_swapchain.c').read_text()
defines = '\n'.join(re.findall(r'^(?:struct droiddeck_dma_buf_sync_file \{.*?\};|#define DROIDDECK_DMA_BUF_\w+ .*)$',
ahb, re.M))
struct = re.search(r'struct ahb_buf \{.*?\n\};', ahb, re.S).group()
source = HARNESS.replace('DEFINES', defines).replace('STRUCT', struct)
source = source.replace('FUNCTIONS', function(ahb, 'ahb_swapchain_present'))
cls.tmp = tempfile.TemporaryDirectory(prefix='droiddeck-acquire-fence-')
cls.addClassCleanup(cls.tmp.cleanup)
probe = Path(cls.tmp.name) / 'probe.c'
probe.write_text(source)
cls.binary = probe.with_suffix('')
built = subprocess.run([cc, '-std=c11', '-Wall', '-Wextra', '-Werror', '-Wno-unused-function', '-UNDEBUG',
'-include', 'stdio.h', '-I', str(SRC.parent / 'prebuilt/include'), str(probe),
'-o', str(cls.binary)],
capture_output=True, text=True)
if built.returncode:
raise AssertionError(built.stdout + built.stderr)
def scenario(self, fd, can_export, copyable=1):
result = subprocess.run([str(self.binary), str(fd), str(can_export), str(copyable)], capture_output=True, text=True,
timeout=10)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_exported_fence_goes_to_the_display(self):
self.scenario(5, 1)
def test_kernel_without_fence_export_falls_back_to_copy(self):
self.scenario(5, 0)
def test_buffer_without_dmabuf_fd_falls_back_to_copy(self):
self.scenario(-1, 1)
def test_uncopyable_buffer_waits_on_the_cpu_and_stays_on_the_layer(self):
self.scenario(5, 0, 0)
def test_uncopyable_buffer_without_dmabuf_fd_stays_on_the_layer(self):
self.scenario(-1, 1, 0)
if __name__ == '__main__':
unittest.main()
+4 -23
View File
@@ -202,11 +202,6 @@ static void setup(int extra) {
/* Probe the public GPU entry points after a terminal result. This includes an
* active off-screen pass and consumed release fds, not just the render guard. */
static int blit_one(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
const struct vkp_blit b = {.src = src, .dst = dst, .wait_fd = wait_fd};
return vkp_blit_images(&b, 1);
}
static void assert_stopped(void) {
assert(g_dev_state == -3 || (g_dev_state == -2 && g_recovery_attempted));
unsigned before = operations, before_destroys = destroys;
@@ -225,7 +220,7 @@ static void assert_stopped(void) {
assert(vkp_image_readback(&src, &pixel, 1) == -1);
assert(vkp_pass_begin(64, 64, NULL, 0, NULL, NULL) == -1);
int fd[2]; assert(pipe(fd) == 0);
assert(blit_one(&src, &dst, fd[0]) == -1);
assert(vkp_blit_image(&src, &dst, fd[0]) == -1);
errno = 0; assert(close(fd[0]) == -1 && errno == EBADF); close(fd[1]);
g_pass.active = 1;
assert(pipe(fd) == 0);
@@ -268,7 +263,7 @@ static void upload_wait_error(int single_pixel) {
memcpy(saved, bytes, sizeof(saved));
struct vkp_image dst = {.image = (VkImage)(uintptr_t)9, .blit_dst = 1, .w = img->w, .h = img->h};
fence_answer = VK_ERROR_OUT_OF_HOST_MEMORY;
assert(blit_one(img, &dst, -1) == -1);
assert(vkp_blit_image(img, &dst, -1) == -1);
assert(g_dev_state == -3 && submits == 1 && waits == 1);
memset(data, 0x7e, sizeof(data));
if (single_pixel) take_pixel(&s, data, &resource); else take_shm(&s, &b, &resource);
@@ -316,26 +311,12 @@ int main(int argc, char **argv) {
struct vkp_image src = {.image = (VkImage)(uintptr_t)7, .w = 1, .h = 1};
struct vkp_image dst = {.image = (VkImage)(uintptr_t)8, .w = 1, .h = 1, .blit_dst = 1};
fence_timeouts = 3;
assert(blit_one(&src, &dst, -1) == 0);
assert(vkp_blit_image(&src, &dst, -1) == 0);
assert(g_dev_state == 1 && submits == 1 && waits == 4 && destroys == 0);
assert(blit_one(&src, &dst, -1) == 0);
assert(vkp_blit_image(&src, &dst, -1) == 0);
assert(g_dev_state == 1 && submits == 2 && waits == 5 && destroys == 0);
free(g_images);
}
else if (!strcmp(name, "blit-batched")) {
setup(0);
struct vkp_image a = {.image = (VkImage)(uintptr_t)7, .w = 4, .h = 4};
struct vkp_image b = {.image = (VkImage)(uintptr_t)8, .w = 1, .h = 1};
struct vkp_image da = {.image = (VkImage)(uintptr_t)9, .w = 4, .h = 4, .blit_dst = 1};
struct vkp_image db = {.image = (VkImage)(uintptr_t)10, .w = 1, .h = 1, .blit_dst = 1};
const struct vkp_blit both[2] = {{.src = &a, .dst = &da, .wait_fd = -1}, {.src = &b, .dst = &db, .wait_fd = -1}};
assert(vkp_blit_images(both, 2) == 0);
assert(g_dev_state == 1 && submits == 1 && waits == 1 && destroys == 0);
const struct vkp_blit bad[2] = {{.src = &a, .dst = &da, .wait_fd = -1}, {.src = &b, .dst = &b, .wait_fd = -1}};
assert(vkp_blit_images(bad, 2) == -1);
assert(submits == 1 && waits == 1);
free(g_images);
}
else if (!strcmp(name, "normal") || !strcmp(name, "framegen")) {
int extra = !strcmp(name, "framegen"); setup(extra);
assert(vkp_render(64, 64, NULL, 0) == 0 && g_dev_state == 1);
@@ -79,9 +79,7 @@ elif ! command -v "$1" >/dev/null 2>&1; then
exit 1
fi
# An ordinary user of the native userland (droiddeck-user): the hook starts the command as root
[ "${DDNATV_USER:-}" = app ] && export DDNATV_BECOME=root
if [ "$(id -u)" = 0 ] || [ -n "${DDNATV_BECOME:-}" ]; then
if [ "$(id -u)" = 0 ]; then
[ "$background" = 1 ] && { "$@" & exit 0; }
exec "$@"
fi