diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 8fd6411fd6..8647862676 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -22,8 +22,10 @@ permissions:
pull-requests: write
concurrency:
- group: build-${{ github.event.pull_request.number || github.ref }}
- cancel-in-progress: true
+ # Replace older builds only for the same PR. Each push/dispatch gets its own group so one main
+ # build cannot cancel another before it signs and publishes.
+ group: build-${{ github.event.pull_request.number || github.run_id }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
PRELOAD_CACHE_VERSION: v2
@@ -307,8 +309,8 @@ jobs:
set -o pipefail
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
- - name: Game environment launch tests
- run: python3 -m unittest discover -s tools/tests -p test_game_environment.py
+ - name: Steam import and game environment tests
+ run: python3 -m unittest discover -s tools/tests -p 'test_*.py'
- name: Unit tests
run: ./gradlew testReleaseUnitTest --console=plain -PndkVersion="$NDK_VERSION"
@@ -489,10 +491,24 @@ jobs:
gh release delete "$tag" -R "$CI_REPO" --yes --cleanup-tag 2>/dev/null || true
gh release create "$tag" -R "$CI_REPO" --target main --prerelease \
--title "main ${GITHUB_SHA::7}" --notes "$notes" signed/*
- # Only the newest KEEP main builds stay; PR releases (pr-N) are left alone.
- gh release list -R "$CI_REPO" -L 200 --json tagName,createdAt \
- --jq '[.[] | select(.tagName | startswith("main-"))] | sort_by(.createdAt) | reverse | .['"$KEEP"':][] | .tagName' |
- while IFS= read -r old; do gh release delete "$old" -R "$CI_REPO" --yes --cleanup-tag; done
+ # Keep the newest main builds by publication time. GitHub App releases can share createdAt.
+ gh release list -R "$CI_REPO" -L 200 --json tagName,publishedAt \
+ --jq '[.[] | select(.tagName | startswith("main-"))] | sort_by(.publishedAt) | reverse | .['"$KEEP"':][] | .tagName' |
+ while IFS= read -r old; do
+ # Never remove this run's release, even if the API returns an unexpected ordering.
+ if [ "$old" = "$tag" ]; then
+ continue
+ fi
+ # Another main publish may have removed the same old release concurrently.
+ if ! gh release delete "$old" -R "$CI_REPO" --yes --cleanup-tag 2>/dev/null; then
+ if gh release view "$old" -R "$CI_REPO" >/dev/null 2>&1; then
+ echo "::error::Could not delete old release $old"
+ exit 1
+ fi
+ fi
+ done
+ published=$(gh release view "$tag" -R "$CI_REPO" --json tagName,assets)
+ jq -e --arg tag "$tag" '.tagName == $tag and (.assets | length) > 0' <<< "$published" >/dev/null
url="$GITHUB_SERVER_URL/$CI_REPO/releases/tag/$tag"
apk=$(cd signed && ls DroidDeck-*.apk | awk 'length(a) == 0 || length($0) < length(a) { a = $0 } END { print a }')
echo "release=$url" >> "$GITHUB_OUTPUT"
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index fba4727ba7..86a4f4617e 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -130,6 +130,9 @@
+
> 1);
+ gl_Position = vec4(mix(pc.dst.xy, pc.dst.zw, t), 0.0, 1.0);
+ uv = mix(pc.src.xy, pc.src.zw, t);
+}
diff --git a/app/src/main/cpp/waylandcomp/src/blend_frag.h b/app/src/main/cpp/waylandcomp/src/blend_frag.h
new file mode 100644
index 0000000000..9d2af54a38
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/blend_frag.h
@@ -0,0 +1,22 @@
+ // 1115.1.0
+ #pragma once
+const uint32_t blend_frag_code[] = {
+ 0x07230203,0x00010000,0x0008000b,0x00000014,0x00000000,0x00020011,0x00000001,0x0006000b,
+ 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
+ 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x00000011,0x00030010,
+ 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
+ 0x00000000,0x00050005,0x00000009,0x4374756f,0x726f6c6f,0x00000000,0x00040005,0x0000000d,
+ 0x66727553,0x00656361,0x00030005,0x00000011,0x00007675,0x00040047,0x00000009,0x0000001e,
+ 0x00000000,0x00040047,0x0000000d,0x00000021,0x00000000,0x00040047,0x0000000d,0x00000022,
+ 0x00000000,0x00040047,0x00000011,0x0000001e,0x00000000,0x00020013,0x00000002,0x00030021,
+ 0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,
+ 0x00000004,0x00040020,0x00000008,0x00000003,0x00000007,0x0004003b,0x00000008,0x00000009,
+ 0x00000003,0x00090019,0x0000000a,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,
+ 0x00000001,0x00000000,0x0003001b,0x0000000b,0x0000000a,0x00040020,0x0000000c,0x00000000,
+ 0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000000,0x00040017,0x0000000f,0x00000006,
+ 0x00000002,0x00040020,0x00000010,0x00000001,0x0000000f,0x0004003b,0x00000010,0x00000011,
+ 0x00000001,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,
+ 0x0004003d,0x0000000b,0x0000000e,0x0000000d,0x0004003d,0x0000000f,0x00000012,0x00000011,
+ 0x00050057,0x00000007,0x00000013,0x0000000e,0x00000012,0x0003003e,0x00000009,0x00000013,
+ 0x000100fd,0x00010038
+};
diff --git a/app/src/main/cpp/waylandcomp/src/blend_pass.c b/app/src/main/cpp/waylandcomp/src/blend_pass.c
new file mode 100644
index 0000000000..471eedc9ae
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/blend_pass.c
@@ -0,0 +1,315 @@
+/* Alpha composition: one surface drawn source-over onto the scene - see blend_pass.h. Compositor thread. */
+#define _POSIX_C_SOURCE 200809L
+#include "blend_pass.h"
+#include "vk_loader.h"
+#include "vk_present.h" /* banner_log, vkp_gpu_name */
+#include
+
+/* SPIR-V, pre-compiled (glslangValidator -V blend.vert --vn blend_vert_code, the same for blend.frag)
+ * and committed next to the GLSL: the NDK build compiles no shaders. */
+#include "blend_vert.h"
+#include "blend_frag.h"
+
+struct pc_blend { float dst[4]; float src[4]; };
+
+static VkDevice g_dev;
+static int g_ready; /* 0 = not built, 1 = ok, -1 = unavailable (said once) */
+static VkSampler g_sampler;
+static VkDescriptorSetLayout g_dsl;
+static VkPipelineLayout g_pl;
+static VkDescriptorPool g_dpool;
+static VkShaderModule g_vert, g_frag;
+static unsigned g_frame = 1;
+
+/* One render pass + pipeline per target format: the screen swapchain's, the scene image's, the HDR
+ * composition's. */
+#define NFMT 4
+static struct { VkFormat fmt; VkRenderPass rp; VkPipeline pipe; } g_out[NFMT];
+
+#define NSRC 32
+static struct { VkImage img; VkImageView view; VkDescriptorSet ds; unsigned frame; } g_src[NSRC];
+#define NDST 12
+static struct { VkImage img; VkFormat fmt; int w, h; VkImageView view; VkFramebuffer fb; unsigned frame; } g_dst[NDST];
+
+void blendp_bind_device(VkDevice dev) { g_dev = dev; }
+
+void blendp_begin_frame(void) { g_frame++; }
+
+static void src_release(int i) {
+ if (g_src[i].ds) g_vk.FreeDescriptorSets(g_dev, g_dpool, 1, &g_src[i].ds);
+ if (g_src[i].view) g_vk.DestroyImageView(g_dev, g_src[i].view, NULL);
+ memset(&g_src[i], 0, sizeof(g_src[i]));
+}
+
+static void dst_release(int i) {
+ if (g_dst[i].fb) g_vk.DestroyFramebuffer(g_dev, g_dst[i].fb, NULL);
+ if (g_dst[i].view) g_vk.DestroyImageView(g_dev, g_dst[i].view, NULL);
+ memset(&g_dst[i], 0, sizeof(g_dst[i]));
+}
+
+void blendp_forget_image(VkImage img) {
+ if (!g_dev || !img) return;
+ for (int i = 0; i < NSRC; i++) if (g_src[i].img == img) src_release(i);
+ for (int i = 0; i < NDST; i++) if (g_dst[i].img == img) dst_release(i);
+}
+
+static VkShaderModule shader(const uint32_t *code, size_t size) {
+ VkShaderModule m = VK_NULL_HANDLE;
+ VkShaderModuleCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = size, .pCode = code};
+ if (g_vk.CreateShaderModule(g_dev, &ci, NULL, &m) != VK_SUCCESS) return VK_NULL_HANDLE;
+ return m;
+}
+
+/* The target keeps what the blits put there (LOAD) and stays in TRANSFER_DST_OPTIMAL for the blits
+ * that follow. The dependencies order the pass between them. */
+static VkRenderPass make_rp(VkFormat fmt) {
+ VkAttachmentDescription att = {.format = fmt, .samples = VK_SAMPLE_COUNT_1_BIT,
+ .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
+ .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
+ .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
+ .initialLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
+ .finalLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL};
+ VkAttachmentReference ref = {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
+ VkSubpassDescription sub = {.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, .colorAttachmentCount = 1,
+ .pColorAttachments = &ref};
+ VkSubpassDependency deps[2] = {
+ {.srcSubpass = VK_SUBPASS_EXTERNAL, .dstSubpass = 0,
+ .srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
+ .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
+ .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
+ .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT},
+ {.srcSubpass = 0, .dstSubpass = VK_SUBPASS_EXTERNAL,
+ .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
+ .dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
+ .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
+ .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT |
+ VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT}};
+ VkRenderPassCreateInfo rci = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, .attachmentCount = 1,
+ .pAttachments = &att, .subpassCount = 1, .pSubpasses = &sub,
+ .dependencyCount = 2, .pDependencies = deps};
+ VkRenderPass rp = VK_NULL_HANDLE;
+ if (g_vk.CreateRenderPass(g_dev, &rci, NULL, &rp) != VK_SUCCESS) return VK_NULL_HANDLE;
+ return rp;
+}
+
+static VkPipeline make_pipe(VkRenderPass rp) {
+ VkPipelineShaderStageCreateInfo st[2] = {
+ {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT,
+ .module = g_vert, .pName = "main"},
+ {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT,
+ .module = g_frag, .pName = "main"}};
+ VkPipelineVertexInputStateCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
+ VkPipelineInputAssemblyStateCreateInfo ia = {.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
+ .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP};
+ VkDynamicState dyn[2] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
+ VkPipelineDynamicStateCreateInfo ds = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
+ .dynamicStateCount = 2, .pDynamicStates = dyn};
+ VkPipelineViewportStateCreateInfo vp = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
+ .viewportCount = 1, .scissorCount = 1};
+ VkPipelineRasterizationStateCreateInfo rs = {.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
+ .polygonMode = VK_POLYGON_MODE_FILL, .cullMode = VK_CULL_MODE_NONE,
+ .frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE, .lineWidth = 1.0f};
+ VkPipelineMultisampleStateCreateInfo ms = {.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
+ .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT};
+ /* The target's alpha is left alone: the screen is opaque whatever is drawn onto it. */
+ VkPipelineColorBlendAttachmentState ba = {
+ .blendEnable = VK_TRUE, .srcColorBlendFactor = VK_BLEND_FACTOR_ONE,
+ .dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, .colorBlendOp = VK_BLEND_OP_ADD,
+ .srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE, .dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
+ .alphaBlendOp = VK_BLEND_OP_ADD,
+ .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT};
+ VkPipelineColorBlendStateCreateInfo cb = {.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
+ .attachmentCount = 1, .pAttachments = &ba};
+ VkGraphicsPipelineCreateInfo pi = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 2,
+ .pStages = st, .pVertexInputState = &vi, .pInputAssemblyState = &ia,
+ .pViewportState = &vp, .pRasterizationState = &rs, .pMultisampleState = &ms,
+ .pColorBlendState = &cb, .pDynamicState = &ds, .layout = g_pl,
+ .renderPass = rp, .subpass = 0};
+ VkPipeline p = VK_NULL_HANDLE;
+ if (g_vk.CreateGraphicsPipelines(g_dev, VK_NULL_HANDLE, 1, &pi, NULL, &p) != VK_SUCCESS) return VK_NULL_HANDLE;
+ return p;
+}
+
+static void objects_destroy(void) {
+ if (g_vert) g_vk.DestroyShaderModule(g_dev, g_vert, NULL);
+ if (g_frag) g_vk.DestroyShaderModule(g_dev, g_frag, NULL);
+ if (g_dpool) g_vk.DestroyDescriptorPool(g_dev, g_dpool, NULL);
+ if (g_pl) g_vk.DestroyPipelineLayout(g_dev, g_pl, NULL);
+ if (g_dsl) g_vk.DestroyDescriptorSetLayout(g_dev, g_dsl, NULL);
+ if (g_sampler) g_vk.DestroySampler(g_dev, g_sampler, NULL);
+ g_vert = g_frag = VK_NULL_HANDLE; g_dpool = VK_NULL_HANDLE; g_pl = VK_NULL_HANDLE;
+ g_dsl = VK_NULL_HANDLE; g_sampler = VK_NULL_HANDLE;
+}
+
+static int objects_ensure(void) {
+ if (g_ready) return g_ready == 1 ? 0 : -1;
+ g_ready = -1;
+ if (!g_dev || !g_vk.CreateGraphicsPipelines) goto fail;
+ VkSamplerCreateInfo sci = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_LINEAR,
+ .minFilter = VK_FILTER_LINEAR, .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
+ .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
+ .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
+ .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE};
+ if (g_vk.CreateSampler(g_dev, &sci, NULL, &g_sampler) != VK_SUCCESS) goto fail;
+ VkDescriptorSetLayoutBinding b = {.binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
+ .descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT};
+ VkDescriptorSetLayoutCreateInfo dli = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
+ .bindingCount = 1, .pBindings = &b};
+ if (g_vk.CreateDescriptorSetLayout(g_dev, &dli, NULL, &g_dsl) != VK_SUCCESS) goto fail;
+ VkPushConstantRange pcr = {.stageFlags = VK_SHADER_STAGE_VERTEX_BIT, .offset = 0, .size = sizeof(struct pc_blend)};
+ VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1,
+ .pSetLayouts = &g_dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pcr};
+ if (g_vk.CreatePipelineLayout(g_dev, &pli, NULL, &g_pl) != VK_SUCCESS) goto fail;
+ VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, NSRC};
+ VkDescriptorPoolCreateInfo dpi = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
+ .flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, .maxSets = NSRC,
+ .poolSizeCount = 1, .pPoolSizes = &ps};
+ if (g_vk.CreateDescriptorPool(g_dev, &dpi, NULL, &g_dpool) != VK_SUCCESS) goto fail;
+ if (!(g_vert = shader(blend_vert_code, sizeof(blend_vert_code)))) goto fail;
+ if (!(g_frag = shader(blend_frag_code, sizeof(blend_frag_code)))) goto fail;
+ g_ready = 1;
+ banner_log("gpu", "alpha composition ready on %s: translucent surfaces are blended over what is under them",
+ vkp_gpu_name());
+ return 0;
+fail:
+ objects_destroy();
+ banner_log("error", "gpu: the alpha composition pass could not be built on this driver; translucent surfaces "
+ "are drawn opaque this session");
+ return -1;
+}
+
+static int out_slot(VkFormat fmt) {
+ int i;
+ for (i = 0; i < NFMT && g_out[i].pipe; i++) if (g_out[i].fmt == fmt) return i;
+ if (i == NFMT) return -1;
+ VkRenderPass rp = make_rp(fmt);
+ VkPipeline pipe = rp ? make_pipe(rp) : VK_NULL_HANDLE;
+ if (!pipe) {
+ if (rp) g_vk.DestroyRenderPass(g_dev, rp, NULL);
+ return -1;
+ }
+ g_out[i].fmt = fmt; g_out[i].rp = rp; g_out[i].pipe = pipe;
+ return i;
+}
+
+static VkImageView make_view(VkImage img, VkFormat fmt) {
+ VkImageView v = VK_NULL_HANDLE;
+ VkImageViewCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = img,
+ .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = fmt,
+ .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
+ if (g_vk.CreateImageView(g_dev, &ci, NULL, &v) != VK_SUCCESS) return VK_NULL_HANDLE;
+ return v;
+}
+
+/* The slot to recycle: a free one, else the one unused for longest - never one this command buffer
+ * already refers to. -1 = every slot is in this frame. */
+#define OLDEST(arr, n, out) do { \
+ unsigned age_ = 0; \
+ (out) = -1; \
+ for (int k_ = 0; k_ < (n); k_++) { \
+ if (!(arr)[k_].img) { (out) = k_; break; } \
+ if ((arr)[k_].frame != g_frame && g_frame - (arr)[k_].frame > age_) { age_ = g_frame - (arr)[k_].frame; (out) = k_; } \
+ } \
+ } while (0)
+
+static VkDescriptorSet src_ensure(VkImage img, VkFormat fmt, VkImageLayout layout) {
+ int i;
+ for (i = 0; i < NSRC; i++)
+ if (g_src[i].img == img) { g_src[i].frame = g_frame; return g_src[i].ds; }
+ OLDEST(g_src, NSRC, i);
+ if (i < 0) return VK_NULL_HANDLE;
+ src_release(i);
+ if (!(g_src[i].view = make_view(img, fmt))) return VK_NULL_HANDLE;
+ VkDescriptorSetAllocateInfo ai = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
+ .descriptorPool = g_dpool, .descriptorSetCount = 1, .pSetLayouts = &g_dsl};
+ if (g_vk.AllocateDescriptorSets(g_dev, &ai, &g_src[i].ds) != VK_SUCCESS) {
+ g_src[i].ds = VK_NULL_HANDLE;
+ src_release(i);
+ return VK_NULL_HANDLE;
+ }
+ VkDescriptorImageInfo ii = {.sampler = g_sampler, .imageView = g_src[i].view, .imageLayout = layout};
+ VkWriteDescriptorSet wr = {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g_src[i].ds, .dstBinding = 0,
+ .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
+ .pImageInfo = &ii};
+ g_vk.UpdateDescriptorSets(g_dev, 1, &wr, 0, NULL);
+ g_src[i].img = img; g_src[i].frame = g_frame;
+ return g_src[i].ds;
+}
+
+static VkFramebuffer dst_ensure(VkImage img, VkFormat fmt, int w, int h, VkRenderPass rp) {
+ int i;
+ for (i = 0; i < NDST; i++) {
+ if (g_dst[i].img != img) continue;
+ if (g_dst[i].fmt == fmt && g_dst[i].w == w && g_dst[i].h == h) { g_dst[i].frame = g_frame; return g_dst[i].fb; }
+ if (g_dst[i].frame == g_frame) return VK_NULL_HANDLE;
+ break;
+ }
+ if (i == NDST) OLDEST(g_dst, NDST, i);
+ if (i < 0) return VK_NULL_HANDLE;
+ dst_release(i);
+ if (!(g_dst[i].view = make_view(img, fmt))) return VK_NULL_HANDLE;
+ VkFramebufferCreateInfo fi = {.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, .renderPass = rp,
+ .attachmentCount = 1, .pAttachments = &g_dst[i].view, .width = (uint32_t)w,
+ .height = (uint32_t)h, .layers = 1};
+ if (g_vk.CreateFramebuffer(g_dev, &fi, NULL, &g_dst[i].fb) != VK_SUCCESS) {
+ g_dst[i].fb = VK_NULL_HANDLE;
+ dst_release(i);
+ return VK_NULL_HANDLE;
+ }
+ g_dst[i].img = img; g_dst[i].fmt = fmt; g_dst[i].w = w; g_dst[i].h = h; g_dst[i].frame = g_frame;
+ return g_dst[i].fb;
+}
+
+static void src_layout(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkImageLayout to) {
+ int sampling = to == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
+ VkImageMemoryBarrier b = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = from, .newLayout = to,
+ .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
+ .image = img, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
+ .srcAccessMask = sampling ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_SHADER_READ_BIT,
+ .dstAccessMask = sampling ? VK_ACCESS_SHADER_READ_BIT : VK_ACCESS_TRANSFER_READ_BIT};
+ g_vk.CmdPipelineBarrier(cmd, sampling ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
+ sampling ? VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT : VK_PIPELINE_STAGE_TRANSFER_BIT,
+ 0, 0, NULL, 0, NULL, 1, &b);
+}
+
+int blendp_draw(VkCommandBuffer cmd, VkImage src, VkFormat src_fmt, int src_w, int src_h, int src_general,
+ VkImage dst, VkFormat dst_fmt, int dst_w, int dst_h, const VkImageBlit *blit) {
+ if (!src || !dst || src_w <= 0 || src_h <= 0 || dst_w <= 0 || dst_h <= 0 || objects_ensure() != 0) return -1;
+ int slot = out_slot(dst_fmt);
+ if (slot < 0) return -1;
+ VkImageLayout sampled = src_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
+ VkDescriptorSet ds = src_ensure(src, src_fmt, sampled);
+ if (!ds) return -1;
+ VkFramebuffer fb = dst_ensure(dst, dst_fmt, dst_w, dst_h, g_out[slot].rp);
+ if (!fb) return -1;
+
+ const VkOffset3D *d = blit->dstOffsets, *s = blit->srcOffsets;
+ int x0 = d[0].x < d[1].x ? d[0].x : d[1].x, x1 = d[0].x < d[1].x ? d[1].x : d[0].x;
+ int y0 = d[0].y < d[1].y ? d[0].y : d[1].y, y1 = d[0].y < d[1].y ? d[1].y : d[0].y;
+ if (x0 < 0) x0 = 0;
+ if (y0 < 0) y0 = 0;
+ if (x1 > dst_w) x1 = dst_w;
+ if (y1 > dst_h) y1 = dst_h;
+ if (x1 <= x0 || y1 <= y0) return 0;
+
+ struct pc_blend pc = {
+ .dst = {2.0f * d[0].x / dst_w - 1.0f, 2.0f * d[0].y / dst_h - 1.0f,
+ 2.0f * d[1].x / dst_w - 1.0f, 2.0f * d[1].y / dst_h - 1.0f},
+ .src = {(float)s[0].x / src_w, (float)s[0].y / src_h, (float)s[1].x / src_w, (float)s[1].y / src_h}};
+
+ if (!src_general) src_layout(cmd, src, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, sampled);
+ VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_out[slot].rp,
+ .framebuffer = fb,
+ .renderArea = {{x0, y0}, {(uint32_t)(x1 - x0), (uint32_t)(y1 - y0)}}};
+ VkViewport vp = {0, 0, (float)dst_w, (float)dst_h, 0, 1};
+ g_vk.CmdBeginRenderPass(cmd, &rpi, VK_SUBPASS_CONTENTS_INLINE);
+ g_vk.CmdSetViewport(cmd, 0, 1, &vp);
+ g_vk.CmdSetScissor(cmd, 0, 1, &rpi.renderArea);
+ g_vk.CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_out[slot].pipe);
+ g_vk.CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pl, 0, 1, &ds, 0, NULL);
+ g_vk.CmdPushConstants(cmd, g_pl, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(pc), &pc);
+ g_vk.CmdDraw(cmd, 4, 1, 0, 0);
+ g_vk.CmdEndRenderPass(cmd);
+ if (!src_general) src_layout(cmd, src, sampled, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
+ return 0;
+}
diff --git a/app/src/main/cpp/waylandcomp/src/blend_pass.h b/app/src/main/cpp/waylandcomp/src/blend_pass.h
new file mode 100644
index 0000000000..2faade2521
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/blend_pass.h
@@ -0,0 +1,28 @@
+#ifndef BLEND_PASS_H
+#define BLEND_PASS_H
+/*
+ * Alpha composition. The scene is composed with blits, which replace what is under them; a surface
+ * with translucent pixels (gamescope's overlay and notification planes over a game, a toolkit's
+ * shadowed popup) is drawn through this pass instead, source-over with premultiplied alpha.
+ *
+ * Compositor thread. Objects are built on the first use; if the driver refuses them the pass is
+ * unavailable for the session (logged once) and the caller keeps blitting.
+ */
+#define VK_USE_PLATFORM_ANDROID_KHR
+#include
+
+/* Called from dev_init (device up). */
+void blendp_bind_device(VkDevice dev);
+/* A source or target image is about to be destroyed: drop what is cached for it. Frames are fenced,
+ * so nothing submitted still uses it. */
+void blendp_forget_image(VkImage img);
+/* A new command buffer is being recorded: what the previous one used may be recycled again. */
+void blendp_begin_frame(void);
+
+/* Record one surface over `dst`. `dst` is in TRANSFER_DST_OPTIMAL before and after. `src` was created
+ * with SAMPLED usage and is in GENERAL (src_general) or TRANSFER_SRC_OPTIMAL, and is left there.
+ * `blit` is the draw as the blit path maps it. 0 = recorded, -1 = unavailable (nothing recorded). */
+int blendp_draw(VkCommandBuffer cmd, VkImage src, VkFormat src_fmt, int src_w, int src_h, int src_general,
+ VkImage dst, VkFormat dst_fmt, int dst_w, int dst_h, const VkImageBlit *blit);
+
+#endif
diff --git a/app/src/main/cpp/waylandcomp/src/blend_vert.h b/app/src/main/cpp/waylandcomp/src/blend_vert.h
new file mode 100644
index 0000000000..f402c6a926
--- /dev/null
+++ b/app/src/main/cpp/waylandcomp/src/blend_vert.h
@@ -0,0 +1,55 @@
+ // 1115.1.0
+ #pragma once
+const uint32_t blend_vert_code[] = {
+ 0x07230203,0x00010000,0x0008000b,0x0000003a,0x00000000,0x00020011,0x00000001,0x0006000b,
+ 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
+ 0x0008000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000c,0x0000001b,0x00000031,
+ 0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,0x00000000,0x00030005,
+ 0x00000009,0x00000074,0x00060005,0x0000000c,0x565f6c67,0x65747265,0x646e4978,0x00007865,
+ 0x00060005,0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,
+ 0x00000000,0x505f6c67,0x7469736f,0x006e6f69,0x00070006,0x00000019,0x00000001,0x505f6c67,
+ 0x746e696f,0x657a6953,0x00000000,0x00070006,0x00000019,0x00000002,0x435f6c67,0x4470696c,
+ 0x61747369,0x0065636e,0x00070006,0x00000019,0x00000003,0x435f6c67,0x446c6c75,0x61747369,
+ 0x0065636e,0x00030005,0x0000001b,0x00000000,0x00030005,0x0000001d,0x00004350,0x00040006,
+ 0x0000001d,0x00000000,0x00747364,0x00040006,0x0000001d,0x00000001,0x00637273,0x00030005,
+ 0x0000001f,0x00006370,0x00030005,0x00000031,0x00007675,0x00040047,0x0000000c,0x0000000b,
+ 0x0000002a,0x00030047,0x00000019,0x00000002,0x00050048,0x00000019,0x00000000,0x0000000b,
+ 0x00000000,0x00050048,0x00000019,0x00000001,0x0000000b,0x00000001,0x00050048,0x00000019,
+ 0x00000002,0x0000000b,0x00000003,0x00050048,0x00000019,0x00000003,0x0000000b,0x00000004,
+ 0x00030047,0x0000001d,0x00000002,0x00050048,0x0000001d,0x00000000,0x00000023,0x00000000,
+ 0x00050048,0x0000001d,0x00000001,0x00000023,0x00000010,0x00040047,0x00000031,0x0000001e,
+ 0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,
+ 0x00000020,0x00040017,0x00000007,0x00000006,0x00000002,0x00040020,0x00000008,0x00000007,
+ 0x00000007,0x00040015,0x0000000a,0x00000020,0x00000001,0x00040020,0x0000000b,0x00000001,
+ 0x0000000a,0x0004003b,0x0000000b,0x0000000c,0x00000001,0x0004002b,0x0000000a,0x0000000e,
+ 0x00000001,0x00040017,0x00000015,0x00000006,0x00000004,0x00040015,0x00000016,0x00000020,
+ 0x00000000,0x0004002b,0x00000016,0x00000017,0x00000001,0x0004001c,0x00000018,0x00000006,
+ 0x00000017,0x0006001e,0x00000019,0x00000015,0x00000006,0x00000018,0x00000018,0x00040020,
+ 0x0000001a,0x00000003,0x00000019,0x0004003b,0x0000001a,0x0000001b,0x00000003,0x0004002b,
+ 0x0000000a,0x0000001c,0x00000000,0x0004001e,0x0000001d,0x00000015,0x00000015,0x00040020,
+ 0x0000001e,0x00000009,0x0000001d,0x0004003b,0x0000001e,0x0000001f,0x00000009,0x00040020,
+ 0x00000020,0x00000009,0x00000015,0x0004002b,0x00000006,0x00000029,0x00000000,0x0004002b,
+ 0x00000006,0x0000002a,0x3f800000,0x00040020,0x0000002e,0x00000003,0x00000015,0x00040020,
+ 0x00000030,0x00000003,0x00000007,0x0004003b,0x00000030,0x00000031,0x00000003,0x00050036,
+ 0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x0004003b,0x00000008,
+ 0x00000009,0x00000007,0x0004003d,0x0000000a,0x0000000d,0x0000000c,0x000500c7,0x0000000a,
+ 0x0000000f,0x0000000d,0x0000000e,0x0004006f,0x00000006,0x00000010,0x0000000f,0x0004003d,
+ 0x0000000a,0x00000011,0x0000000c,0x000500c3,0x0000000a,0x00000012,0x00000011,0x0000000e,
+ 0x0004006f,0x00000006,0x00000013,0x00000012,0x00050050,0x00000007,0x00000014,0x00000010,
+ 0x00000013,0x0003003e,0x00000009,0x00000014,0x00050041,0x00000020,0x00000021,0x0000001f,
+ 0x0000001c,0x0004003d,0x00000015,0x00000022,0x00000021,0x0007004f,0x00000007,0x00000023,
+ 0x00000022,0x00000022,0x00000000,0x00000001,0x00050041,0x00000020,0x00000024,0x0000001f,
+ 0x0000001c,0x0004003d,0x00000015,0x00000025,0x00000024,0x0007004f,0x00000007,0x00000026,
+ 0x00000025,0x00000025,0x00000002,0x00000003,0x0004003d,0x00000007,0x00000027,0x00000009,
+ 0x0008000c,0x00000007,0x00000028,0x00000001,0x0000002e,0x00000023,0x00000026,0x00000027,
+ 0x00050051,0x00000006,0x0000002b,0x00000028,0x00000000,0x00050051,0x00000006,0x0000002c,
+ 0x00000028,0x00000001,0x00070050,0x00000015,0x0000002d,0x0000002b,0x0000002c,0x00000029,
+ 0x0000002a,0x00050041,0x0000002e,0x0000002f,0x0000001b,0x0000001c,0x0003003e,0x0000002f,
+ 0x0000002d,0x00050041,0x00000020,0x00000032,0x0000001f,0x0000000e,0x0004003d,0x00000015,
+ 0x00000033,0x00000032,0x0007004f,0x00000007,0x00000034,0x00000033,0x00000033,0x00000000,
+ 0x00000001,0x00050041,0x00000020,0x00000035,0x0000001f,0x0000000e,0x0004003d,0x00000015,
+ 0x00000036,0x00000035,0x0007004f,0x00000007,0x00000037,0x00000036,0x00000036,0x00000002,
+ 0x00000003,0x0004003d,0x00000007,0x00000038,0x00000009,0x0008000c,0x00000007,0x00000039,
+ 0x00000001,0x0000002e,0x00000034,0x00000037,0x00000038,0x0003003e,0x00000031,0x00000039,
+ 0x000100fd,0x00010038
+};
diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c
index 7dd9b7c73c..d2f5f05956 100644
--- a/app/src/main/cpp/waylandcomp/src/compositor.c
+++ b/app/src/main/cpp/waylandcomp/src/compositor.c
@@ -238,6 +238,8 @@ struct surface {
struct dmabuf_buffer *dmabuf_buf; /* its imported image, kept until replaced or the surface goes */
struct wl_listener dmabuf_destroy;
int buf_w, buf_h, has_content;
+ int buf_alpha;
+ int opaque[4], pending_opaque[4], pending_opaque_set; /* x, y, w, h; w = 0: none */
int src_set, dst_set;
float src[4];
int dst[2];
@@ -466,6 +468,12 @@ static struct seat_pointer g_ptrs[MAX_PTRS];
static int g_nptrs;
static struct seat_keyboard g_kbs[MAX_PTRS];
static int g_nkbs;
+/* Modifier state in the keymap's real-modifier bits (Shift=0x1, Lock=0x2, Control=0x4, Mod1=0x8,
+ * Mod4=0x40). A client of the wayland backend - gamescope, labwc - takes modifiers only from
+ * wl_keyboard.modifiers and ignores what a Shift key event does to its xkb state, so without this
+ * every capital arrived lowercase. */
+static uint32_t g_mods_depressed, g_mods_locked;
+static uint32_t g_mod_keys_held; /* one bit per modifier key below, so a repeat press is harmless */
static struct seat_touch g_touches[MAX_PTRS];
static int g_ntouches;
@@ -716,6 +724,7 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
wl_buffer_send_release(buffer);
s->buf_w = w;
s->buf_h = h;
+ s->buf_alpha = wl_shm_buffer_get_format(shm) == WL_SHM_FORMAT_ARGB8888;
s->has_content = s->shm_img != NULL;
g_stat_shm++;
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
@@ -767,6 +776,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
}
s->buf_w = b->width;
s->buf_h = b->height;
+ s->buf_alpha = (b->format & 0xff) == 'A';
s->has_content = b->img != NULL;
g_stat_dmabuf++;
const int announced_now = !s->announced_vulkan;
@@ -938,8 +948,27 @@ static void surface_frame(struct wl_client *c, struct wl_resource *r, uint32_t c
wl_resource_set_implementation(callback, NULL, NULL, frame_callback_destroy);
wl_list_insert(s->pending_frames.prev, wl_resource_get_link(callback));
}
+/* The bounding box serves pointer confinement. The exact flag also tells opaque-region handling
+ * whether the bounding box itself is the whole region. */
+struct region { int set, exact; int x, y, w, h; };
+
+/* A wl_surface's opaque region is pending until its next commit. An exact region that covers
+ * the surface lets the blit path keep handling an otherwise alpha-capable buffer. */
static void surface_set_opaque(struct wl_client *c, struct wl_resource *r,
- struct wl_resource *region) {}
+ struct wl_resource *region) {
+ struct surface *s = wl_resource_get_user_data(r);
+ struct region *rg = region ? wl_resource_get_user_data(region) : NULL;
+ memset(s->pending_opaque, 0, sizeof(s->pending_opaque));
+ s->pending_opaque_set = 1;
+ if (rg && rg->set && rg->exact) {
+ s->pending_opaque[0] = rg->x;
+ s->pending_opaque[1] = rg->y;
+ s->pending_opaque[2] = rg->w;
+ s->pending_opaque[3] = rg->h;
+ }
+ struct client_info *ci = client_info_of(c);
+ if (ci) ci->declares_opaque = 1;
+}
static void surface_set_input(struct wl_client *c, struct wl_resource *r,
struct wl_resource *region) {}
@@ -1030,6 +1059,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
memcpy(s->dst, s->pending_dst, sizeof(s->dst));
s->pending_dst_set = 0;
}
+ if (s->pending_opaque_set) {
+ memcpy(s->opaque, s->pending_opaque, sizeof(s->opaque));
+ s->pending_opaque_set = 0;
+ }
if (s->pending_attach) {
struct wl_resource *buffer = s->pending_buffer;
@@ -1168,24 +1201,29 @@ static void surface_resource_destroy(struct wl_resource *r) {
/* ------------------------------------------------------------------ wl_region */
-/* A region is kept as the bounding box of its rectangles: enough for pointer confinement,
- * where winewayland sends one rectangle (the ClipCursor area). Subtractions are ignored. */
-struct region { int set; int x, y, w, h; };
-
static void region_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
static void region_add(struct wl_client *c, struct wl_resource *r,
int32_t x, int32_t y, int32_t w, int32_t h) {
struct region *rg = wl_resource_get_user_data(r);
if (!rg || w <= 0 || h <= 0) return;
- if (!rg->set) { rg->x = x; rg->y = y; rg->w = w; rg->h = h; rg->set = 1; return; }
- int x2 = rg->x + rg->w > x + w ? rg->x + rg->w : x + w;
- int y2 = rg->y + rg->h > y + h ? rg->y + rg->h : y + h;
+ if (!rg->set) { rg->x = x; rg->y = y; rg->w = w; rg->h = h; rg->set = rg->exact = 1; return; }
+ long long x2 = (long long)rg->x + rg->w, y2 = (long long)rg->y + rg->h;
+ long long nx2 = (long long)x + w, ny2 = (long long)y + h;
+ int inside = x >= rg->x && y >= rg->y && nx2 <= x2 && ny2 <= y2;
+ int around = x <= rg->x && y <= rg->y && nx2 >= x2 && ny2 >= y2;
+ if (!inside && !around) rg->exact = 0;
+ if (nx2 > x2) x2 = nx2;
+ if (ny2 > y2) y2 = ny2;
if (x < rg->x) rg->x = x;
if (y < rg->y) rg->y = y;
- rg->w = x2 - rg->x; rg->h = y2 - rg->y;
+ rg->w = (int)(x2 - rg->x > INT32_MAX ? INT32_MAX : x2 - rg->x);
+ rg->h = (int)(y2 - rg->y > INT32_MAX ? INT32_MAX : y2 - rg->y);
}
static void region_subtract(struct wl_client *c, struct wl_resource *r,
- int32_t x, int32_t y, int32_t w, int32_t h) {}
+ int32_t x, int32_t y, int32_t w, int32_t h) {
+ struct region *rg = wl_resource_get_user_data(r);
+ if (rg && w > 0 && h > 0) rg->exact = 0;
+}
static void region_resource_destroy(struct wl_resource *r) { free(wl_resource_get_user_data(r)); }
static const struct wl_region_interface region_impl = {
.destroy = region_destroy,
@@ -1659,6 +1697,17 @@ static void note_hdr_unimported(const struct draw_list *dl, struct surface *s, i
g_hdr_unimported_below = dl->n;
}
+/* A client that describes opaque regions can intentionally leave part of an alpha buffer see-through.
+ * Gamescope uses this for its full-size Steam notification and overlay planes. */
+static int surface_translucent(const struct surface *s, int w, int h) {
+ if (!s->buf_alpha) return 0;
+ const struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
+ if (!ci || !ci->declares_opaque) return 0;
+ const int *o = s->opaque;
+ return !(o[2] > 0 && o[0] <= 0 && o[1] <= 0 &&
+ (long long)o[0] + o[2] >= w && (long long)o[1] + o[3] >= h);
+}
+
static void add_surface(struct draw_list *dl, struct surface *s, int ox, int oy) {
struct vkp_image *img = surface_image(s);
float sx = 0, sy = 0, sw = (float)s->buf_w, sh = (float)s->buf_h;
@@ -1678,7 +1727,8 @@ static void add_surface(struct draw_list *dl, struct surface *s, int ox, int oy)
dl->d = d;
dl->cap = cap;
}
- dl->d[dl->n++] = (struct vkp_draw){img, sx, sy, sw, sh, ox, oy, dw, dh};
+ dl->d[dl->n++] = (struct vkp_draw){img, sx, sy, sw, sh, ox, oy, dw, dh,
+ surface_translucent(s, dw, dh)};
s->drawn = 1;
}
@@ -1749,6 +1799,7 @@ static int on_frame_timer(void *data) {
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) continue; /* the translucent plane must not replace the opaque game layer */
if (!vkp_image_is_dmabuf(d->img)) continue;
if (d->dx != 0 || d->dy != 0 || d->dw != scene_w || d->dh != scene_h) continue;
if (d->sx != 0 || d->sy != 0 || (int)d->sw != vkp_image_width(d->img) ||
@@ -2087,7 +2138,7 @@ static void render_scene(void) {
* its own layer, cropped and placed by the display. */
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) == 0 ? 1 : -1;
+ 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) { /* the overlay layer refused it: draw the whole scene the old way */
sc_layer_hide();
@@ -2370,8 +2421,8 @@ static void keyboard_focus(struct wl_resource *target) {
if (sk->focus == target) continue;
sk->focus = target;
wl_keyboard_send_enter(sk->kb, wl_display_next_serial(g_display), target, &keys);
- /* Baseline modifiers = none; Shift/Ctrl arrive as their own key events. */
- wl_keyboard_send_modifiers(sk->kb, wl_display_next_serial(g_display), 0, 0, 0, 0);
+ wl_keyboard_send_modifiers(sk->kb, wl_display_next_serial(g_display),
+ g_mods_depressed, 0, g_mods_locked, 0);
}
wl_array_release(&keys);
banner_clipboard_keyboard_focus(client); /* wl_data_device selection follows focus */
@@ -3068,7 +3119,34 @@ static void scroll_event(int steps) {
wl_display_flush_clients(g_display);
}
+/* Folds a key into the modifier state; returns whether the state changed. */
+static int update_modifiers(uint32_t evdev, int pressed) {
+ static const struct { uint32_t evdev, mask; } mod_keys[] = {
+ { 42, 0x1 }, { 54, 0x1 }, /* Shift L/R */
+ { 29, 0x4 }, { 97, 0x4 }, /* Control L/R */
+ { 56, 0x8 }, { 100, 0x8 }, /* Alt L/R, both Mod1 in this keymap */
+ { 125, 0x40 }, { 126, 0x40 }, /* Super L/R */
+ };
+ uint32_t depressed = g_mods_depressed, locked = g_mods_locked;
+ if (evdev == 58) { /* Caps Lock toggles on press */
+ if (pressed) locked ^= 0x2;
+ } else {
+ int i, n = (int)(sizeof(mod_keys) / sizeof(mod_keys[0]));
+ for (i = 0; i < n && mod_keys[i].evdev != evdev; i++) {}
+ if (i == n) return 0;
+ if (pressed) g_mod_keys_held |= 1u << i; else g_mod_keys_held &= ~(1u << i);
+ depressed = 0;
+ for (int j = 0; j < n; j++) if (g_mod_keys_held & (1u << j)) depressed |= mod_keys[j].mask;
+ }
+ if (depressed == g_mods_depressed && locked == g_mods_locked) return 0;
+ g_mods_depressed = depressed;
+ g_mods_locked = locked;
+ return 1;
+}
+
static void key_event(uint32_t evdev, int pressed) {
+ /* Tracked even with nothing to deliver to, so a Shift released unseen is not left held. */
+ int mods_changed = update_modifiers(evdev, pressed);
/* Keys go to the program window the user last clicked (else the topmost non-shell window),
* never to Wine's desktop surface: winewayland hands each key to the hwnd of the surface that
* holds keyboard focus, and a key handed to explorer's desktop hwnd is queued to explorer's
@@ -3088,9 +3166,13 @@ static void key_event(uint32_t evdev, int pressed) {
struct seat_keyboard *sk;
if (!keyboard_for(client)) return;
keyboard_focus(target->resource);
- for_each_keyboard_of(client, sk)
+ for_each_keyboard_of(client, sk) {
wl_keyboard_send_key(sk->kb, wl_display_next_serial(g_display), now_ms(), evdev,
pressed ? WL_KEYBOARD_KEY_STATE_PRESSED : WL_KEYBOARD_KEY_STATE_RELEASED);
+ if (mods_changed)
+ wl_keyboard_send_modifiers(sk->kb, wl_display_next_serial(g_display),
+ g_mods_depressed, 0, g_mods_locked, 0);
+ }
wl_display_flush_clients(g_display);
}
diff --git a/app/src/main/cpp/waylandcomp/src/compositor_internal.h b/app/src/main/cpp/waylandcomp/src/compositor_internal.h
index d6e07c5f5c..db739132af 100644
--- a/app/src/main/cpp/waylandcomp/src/compositor_internal.h
+++ b/app/src/main/cpp/waylandcomp/src/compositor_internal.h
@@ -60,6 +60,9 @@ struct client_info {
/* An OpenGL program whose EGL gave up on the GPU: it asked for dma-buf feedback (EGL's
* Wayland GPU path always does), never made a dma-buf buffer, and draws wl_shm frames. */
unsigned asked_feedback : 1, shm_gl_said : 1;
+ /* Clients that describe opaque regions can use alpha outside those regions. Wine windows
+ * never describe them, and their unused alpha channel must not make them translucent. */
+ unsigned declares_opaque : 1;
unsigned dmabuf_buffers, shm_frames;
struct client_info *next;
};
diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c
index cd60fd3515..1fcbf3357c 100644
--- a/app/src/main/cpp/waylandcomp/src/sc_layer.c
+++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c
@@ -85,6 +85,7 @@ static struct {
#define ASC_VISIBILITY_HIDE 0
#define ASC_VISIBILITY_SHOW 1
+#define ASC_TRANSPARENCY_TRANSLUCENT 1
#define ASC_TRANSPARENCY_OPAQUE 2
static int load_api(void) {
@@ -766,7 +767,8 @@ static ASurfaceControl *swap_sc_begin(struct layer *l) {
/* The transaction that puts pool slot `idx` of layer `l` on screen at `r`, as `color` (NULL = no
* description). 0 = applied. */
-static int present_slot(struct layer *l, int idx, const int r[8], const struct banner_color *color) {
+static int present_slot(struct layer *l, int idx, const int r[8], const struct banner_color *color,
+ int translucent) {
struct slot *s = &l->slots[idx];
ASurfaceTransaction *tx = api.txCreate();
if (!tx) return -1;
@@ -774,9 +776,8 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct b
if (old) api.setZOrder(tx, l->sc, l->z);
/* The blit was waited for on the CPU, so no acquire fence is needed (-1). */
api.setBuffer(tx, l->sc, s->ahb, -1);
- /* The compositor composes with blits, which overwrite: nothing is ever alpha-blended on the
- * copy path either, so every layer is opaque and the picture matches it pixel for pixel. */
- api.setBufferTransparency(tx, l->sc, ASC_TRANSPARENCY_OPAQUE);
+ api.setBufferTransparency(tx, l->sc,
+ translucent ? ASC_TRANSPARENCY_TRANSLUCENT : ASC_TRANSPARENCY_OPAQUE);
apply_geometry(tx, l, r);
apply_frame_rate(tx, l);
apply_colour(tx, l, color);
@@ -883,7 +884,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
if (idx < 0) { log_drop(l); return 0; }
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
- if (present_slot(l, idx, r, color) != 0) return -1;
+ if (present_slot(l, idx, r, color, 0) != 0) return -1;
if (color && color->dataspace) banner_color_frame_shown(color, BANNER_HDR_LAYER_COPY, AHB_RGBA8);
if (!l->first_logged) {
l->first_logged = 1;
@@ -908,7 +909,7 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int
int idx = take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd);
if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; }
if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1;
- if (present_slot(l, idx, r, NULL) != 0) return -1; /* the effects chain's result is 8-bit sRGB */
+ if (present_slot(l, idx, r, NULL, 0) != 0) return -1; /* the effects chain's result is 8-bit sRGB */
if (!l->first_logged) {
l->first_logged = 1;
banner_log("layer", "presenting %dx%d frames on their own SurfaceControl layer (%s pool, %d buffers); "
@@ -950,7 +951,7 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct
}
if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; }
if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1;
- if (present_slot(l, idx, r, tm ? NULL : color) != 0) return -1; /* tone-mapped = plain sRGB: no tag */
+ if (present_slot(l, idx, r, tm ? NULL : color, 0) != 0) return -1; /* tone-mapped = plain sRGB: no tag */
if (color && color->dataspace)
banner_color_frame_shown(color, tm ? BANNER_HDR_TONEMAPPED : BANNER_HDR_COMPOSED, tm ? AHB_RGBA8 : g_hdr_pool_fmt);
static int said = -1;
@@ -1031,7 +1032,7 @@ int sc_layer_overlay_affordable(void) {
return ok;
}
-int sc_layer_present_overlay(struct vkp_image *src, const int geo[8]) {
+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;
/* The caller decides with sc_layer_overlay_affordable() BEFORE it commits the game to a layer;
@@ -1046,7 +1047,7 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8]) {
/* The window is copied into the layer buffer 1:1; `geo` crops it and places it, so the layer
* is exactly the window's rectangle on screen and nothing else is blended anywhere. */
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
- if (present_slot(l, idx, geo, NULL) != 0) return -1;
+ if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
if (!l->first_logged) {
l->first_logged = 1;
log_layer_count();
diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.h b/app/src/main/cpp/waylandcomp/src/sc_layer.h
index 94a6f90653..f2f12a704f 100644
--- a/app/src/main/cpp/waylandcomp/src/sc_layer.h
+++ b/app/src/main/cpp/waylandcomp/src/sc_layer.h
@@ -150,8 +150,9 @@ int sc_layer_overlay_affordable(void);
/* OVERLAY layer: show `src` (one window's imported frame) above the game layer, at the placement
* `geo` = {src x0,y0,x1,y1 in image pixels, dst x0,y0,x1,y1 in output pixels} from vkp_map_draw.
+ * `translucent` preserves a client's alpha over the game for Steam notifications and overlays.
* 0 = shown or dropped, -1 = unavailable (the caller must fall back to the copy path). */
-int sc_layer_present_overlay(struct vkp_image *src, const int geo[8]);
+int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent);
/* The scene is not a single fullscreen window this frame: hide every layer that is up. */
void sc_layer_hide(void);
diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c
index 8c1d897fc1..7a2ecfd48b 100644
--- a/app/src/main/cpp/waylandcomp/src/vk_present.c
+++ b/app/src/main/cpp/waylandcomp/src/vk_present.c
@@ -7,6 +7,7 @@
#include "effects_chain.h"
#include "framegen_bridge.h"
#include "hdr_compose.h"
+#include "blend_pass.h"
#include "banner_color.h"
#include
#include
@@ -32,6 +33,8 @@ struct vkp_image {
void *map; /* shm images: persistently mapped linear memory */
VkDeviceSize offset, row_pitch;
int in_general; /* shm images: moved from PREINITIALIZED to GENERAL */
+ VkFormat fmt;
+ int sampled; /* created with SAMPLED usage: the alpha pass can read it */
};
static ANativeWindow *g_window; /* the window frames go to; compositor thread only */
@@ -230,6 +233,7 @@ static void destroy_swapchain(void) {
if (g_dev_state != 1) return;
g_vk.DeviceWaitIdle(g_dev);
reset_sync();
+ for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
g_swapchain = VK_NULL_HANDLE;
g_swap_md_identity = 0; /* a new swapchain gets the metadata again */
@@ -525,6 +529,7 @@ static int dev_init(void) {
vkp_effects_bind_device(g_dev, g_pd, &g_memprops);
hdrc_bind_device(g_dev, &g_memprops);
+ blendp_bind_device(g_dev);
g_dev_state = 1;
reset_sync();
init_black_image();
@@ -873,9 +878,8 @@ const char *vkp_modifier_name(uint64_t modifier) {
return other;
}
-/* Can the driver create the image vkp_image_import_dmabuf() creates for this format+modifier
- * (2D, DRM_FORMAT_MODIFIER tiling, TRANSFER_SRC, dma-buf memory) - and import it? */
-static int modifier_importable(VkFormat fmt, uint64_t modifier) {
+/* Can the driver create and import this format/modifier with the requested image usage? */
+static int modifier_importable(VkFormat fmt, uint64_t modifier, VkImageUsageFlags usage) {
if (!g_vk.GetPhysicalDeviceImageFormatProperties2) return 1; /* can't ask; the create will tell */
VkPhysicalDeviceExternalImageFormatInfo ext = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
@@ -886,7 +890,7 @@ static int modifier_importable(VkFormat fmt, uint64_t modifier) {
VkPhysicalDeviceImageFormatInfo2 info = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, .pNext = &mod,
.format = fmt, .type = VK_IMAGE_TYPE_2D, .tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT,
- .usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT};
+ .usage = usage};
VkExternalImageFormatProperties extp = {.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES};
VkImageFormatProperties2 props = {.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2, .pNext = &extp};
if (g_vk.GetPhysicalDeviceImageFormatProperties2(g_pd, &info, &props) != VK_SUCCESS) return 0;
@@ -914,7 +918,7 @@ int vkp_dmabuf_modifiers(uint32_t drm_format, uint64_t *out, int max) {
if (m != VKP_MOD_LINEAR && m != VKP_MOD_QCOM_COMPRESSED) why = "unknown layout";
else if (props[i].drmFormatModifierPlaneCount != 1) why = "not single-plane";
else if (!(props[i].drmFormatModifierTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) why = "no blit source";
- else if (!modifier_importable(fmt, m)) why = "not importable as a dma-buf";
+ else if (!modifier_importable(fmt, m, VK_IMAGE_USAGE_TRANSFER_SRC_BIT)) why = "not importable as a dma-buf";
if (why) {
LOGI("dmabuf: %c%c%c%c %s reported by the driver but not advertised: %s",
drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff,
@@ -942,6 +946,10 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0;
+ img->fmt = drm_to_vk(drm_format);
+ const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
+ img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
+ modifier_importable(img->fmt, modifier, sampled_usage);
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = {
@@ -952,10 +960,11 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
VkImageCreateInfo ici = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &extImg,
- .imageType = VK_IMAGE_TYPE_2D, .format = drm_to_vk(drm_format), .extent = {w, h, 1},
+ .imageType = VK_IMAGE_TYPE_2D, .format = img->fmt, .extent = {w, h, 1},
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT,
- .usage = as_blit_dst ? VK_IMAGE_USAGE_TRANSFER_DST_BIT : VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
+ .usage = as_blit_dst ? VK_IMAGE_USAGE_TRANSFER_DST_BIT
+ : img->sampled ? sampled_usage : VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
VkResult cr = g_vk.CreateImage(g_dev, &ici, NULL, &img->image);
if (cr != VK_SUCCESS) {
@@ -1008,18 +1017,35 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
return img;
}
+/* Linear wl_shm images can use the blend pass only if the driver samples them with a linear filter. */
+static int shm_sampled(void) {
+ static int known;
+ if (!known) {
+ const VkFormatFeatureFlags need = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
+ VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
+ VkFormatProperties2 fp = {.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2};
+ if (g_vk.GetPhysicalDeviceFormatProperties2)
+ g_vk.GetPhysicalDeviceFormatProperties2(g_pd, VK_FORMAT_B8G8R8A8_UNORM, &fp);
+ known = (fp.formatProperties.linearTilingFeatures & need) == need ? 1 : -1;
+ }
+ return known == 1;
+}
+
struct vkp_image *vkp_image_create_shm(int w, int h) {
if (w <= 0 || h <= 0 || dev_init() != 0) return NULL;
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = w; img->h = h;
+ img->fmt = VK_FORMAT_B8G8R8A8_UNORM;
+ img->sampled = shm_sampled();
VkImageCreateInfo ici = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D,
- .format = VK_FORMAT_B8G8R8A8_UNORM, .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = 1,
+ .format = img->fmt, .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_LINEAR,
- .usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
+ .usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
+ .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED};
if (g_vk.CreateImage(g_dev, &ici, NULL, &img->image) != VK_SUCCESS) { free(img); return NULL; }
@@ -1062,6 +1088,7 @@ int vkp_image_height(const struct vkp_image *img) { return img ? img->h : 0; }
void vkp_image_destroy(struct vkp_image *img) {
if (!img) return;
if (g_dev) {
+ blendp_forget_image(img->image);
if (img->map) g_vk.UnmapMemory(g_dev, img->mem);
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
@@ -1111,8 +1138,21 @@ static int draw_to_scene_blit(const struct vkp_draw *d, int scene_w, int scene_h
return map_draw(d, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, (float)scene_w, (float)scene_h, blit);
}
+/* A translucent draw needs source-over blending; every other draw keeps the existing blit path. */
+static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target,
+ VkFormat target_fmt, int target_w, int target_h, VkFilter filter) {
+ const struct vkp_image *im = d->img;
+ if (d->blend && im->sampled &&
+ blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !im->dmabuf, target, target_fmt, target_w, target_h,
+ blit) == 0)
+ return;
+ g_vk.CmdBlitImage(cmd, im->image, im->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
+ target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
+}
+
static void destroy_scene_image(void) {
if (g_scene.img) hdrc_forget_image(g_scene.img); /* the HDR pass may have drawn into it */
+ if (g_scene.img) blendp_forget_image(g_scene.img);
if (g_scene.img) g_vk.DestroyImage(g_dev, g_scene.img, NULL);
if (g_scene.mem) g_vk.FreeMemory(g_dev, g_scene.mem, NULL);
memset(&g_scene, 0, sizeof(g_scene));
@@ -1150,6 +1190,7 @@ static int ensure_scene_image(int w, int h) {
static int ensure_img(struct vkp_img_slot *s, int w, int h, VkFormat fmt, VkImageUsageFlags usage, const char *what) {
if (s->img && s->w == w && s->h == h && s->fmt == fmt) return 0;
if (s->img) hdrc_forget_image(s->img);
+ if (s->img) blendp_forget_image(s->img);
if (s->img) g_vk.DestroyImage(g_dev, s->img, NULL);
if (s->mem) g_vk.FreeMemory(g_dev, s->mem, NULL);
memset(s, 0, sizeof(*s));
@@ -1190,7 +1231,8 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n,
int scene_w, int scene_h, VkImage out, VkFormat out_fmt, enum hdrc_mode mode) {
if (!hf || !hf->is_hdr || n <= 0) return -1;
if (ensure_img(&g_mixed, scene_w, scene_h, HDR_FMT,
- VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
+ VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
+ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
"HDR composition (mixed)") != 0)
return -1;
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
@@ -1214,9 +1256,7 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n,
VkImageBlit blit;
if (!draws[i].img || !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit)) continue;
/* A blit converts UNORM to UNORM by value: 8-bit sRGB and 10-bit PQ both land unchanged. */
- g_vk.CmdBlitImage(cmd, draws[i].img->image,
- draws[i].img->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
- g_mixed.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR);
+ record_draw(cmd, &draws[i], &blit, g_mixed.img, HDR_FMT, scene_w, scene_h, VK_FILTER_LINEAR);
if (hf->is_hdr[i] && lowest_hdr < 0) lowest_hdr = i;
}
static int truncated_said;
@@ -1249,6 +1289,7 @@ static void device_lost(const char *where) {
vkp_framegen_device_lost();
banner_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
"restart the session", where);
+ for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
g_swapchain = VK_NULL_HANDLE;
if (g_surface) g_vk.DestroySurfaceKHR(g_inst, g_surface, NULL);
@@ -1547,6 +1588,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(cmd, &bi);
+ blendp_begin_frame();
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
/* Source images: take dmabufs from the client's queue family, move shm images to
@@ -1589,8 +1631,8 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
free(bars);
/* Clear the composition target to black (the letterbox on the direct path, the desktop's
- * background on the pass) before the draws land on it. A draw that covers the whole scene
- * overwrites every pixel of its rectangle (blits never blend), so then only what lies outside it
+ * background on the pass) before the draws land on it. An opaque draw that covers the whole scene
+ * overwrites every pixel of its rectangle, so then only what lies outside it
* needs black: the letterbox bars on the direct path, nothing at all on the pass (the scene image
* is exactly the scene). Anything else - no such draw, the HDR composition - clears the whole
* target as before. */
@@ -1600,7 +1642,8 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
if (!(hf && pass)) {
for (int i = n - 1; i >= 0 && !covered; i--) {
const struct vkp_draw *d = &draws[i];
- if (!d->img || d->dx > 0 || d->dy > 0 || d->dx + d->dw < scene_w || d->dy + d->dh < scene_h) continue;
+ if (!d->img || d->blend || d->dx > 0 || d->dy > 0 || d->dx + d->dw < scene_w ||
+ d->dy + d->dh < scene_h) continue;
covered = pass ? draw_to_scene_blit(d, scene_w, scene_h, &cover_blit) : draw_to_blit(d, &cover_blit);
}
}
@@ -1633,10 +1676,9 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
VkImageBlit blit;
if (!draws[i].img) continue;
if (pass ? !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit) : !draw_to_blit(&draws[i], &blit)) continue;
- g_vk.CmdBlitImage(cmd, draws[i].img->image,
- draws[i].img->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
- target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit,
- pass ? VK_FILTER_LINEAR : blit_filter);
+ record_draw(cmd, &draws[i], &blit, target, pass ? scene_fmt : g_swap_fmt,
+ pass ? scene_w : (int)g_extent.width, pass ? scene_h : (int)g_extent.height,
+ pass ? VK_FILTER_LINEAR : blit_filter);
drawn++;
}
@@ -2073,6 +2115,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(cmd, &bi);
+ blendp_begin_frame();
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
/* Same acquisition as vkp_render's compositor pass: the sources come from the client's queue
@@ -2132,9 +2175,8 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
for (int i = 0; i < n; i++) {
VkImageBlit blit;
if (!draws[i].img || !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit)) continue;
- g_vk.CmdBlitImage(cmd, draws[i].img->image,
- draws[i].img->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
- g_scene.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR);
+ record_draw(cmd, &draws[i], &blit, g_scene.img, SCENE_FMT, scene_w, scene_h,
+ VK_FILTER_LINEAR);
}
if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM);
}
diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.h b/app/src/main/cpp/waylandcomp/src/vk_present.h
index 8997365200..eef9c80cca 100644
--- a/app/src/main/cpp/waylandcomp/src/vk_present.h
+++ b/app/src/main/cpp/waylandcomp/src/vk_present.h
@@ -79,6 +79,7 @@ struct vkp_draw {
struct vkp_image *img;
float sx, sy, sw, sh;
int dx, dy, dw, dh;
+ int blend; /* translucent: composed over what is under it (blend_pass.h) */
};
// The GPU the renderer runs on ("Adreno (TM) 750"), empty before the device is up.
diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt
index 964df91bd2..df58f900bf 100644
--- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt
@@ -45,6 +45,7 @@ import com.droiddeck.launcher.core.CpuCores
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
import com.droiddeck.launcher.core.WirelessAdbFix
+import com.droiddeck.launcher.core.WirelessAdbPairingService
import com.droiddeck.launcher.ui.CoreRow
import com.droiddeck.launcher.ui.PerformancePage
import com.droiddeck.launcher.ui.ModeSettingsPage
@@ -88,6 +89,9 @@ class MainActivity : ComponentActivity() {
private var flood by mutableStateOf(null)
private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f)
private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent)
+ /** A session stopped behind a flood: its blue, drawn back into the button it started from (FloodReturn). */
+ private var returning by mutableStateOf(null)
+ private class ReturningFlood(val color: Int, val to: androidx.compose.ui.geometry.Rect?)
private var ready by mutableStateOf(false)
private var available by mutableStateOf(null)
private var busy by mutableStateOf(false)
@@ -432,6 +436,12 @@ class MainActivity : ComponentActivity() {
android.widget.Toast.makeText(this, "ADB command copied", android.widget.Toast.LENGTH_SHORT).show()
},
onDismissPhantomGate = { showPhantomGate = false },
+ onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
+ onOpenNotificationSettings = {
+ startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
+ .putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ },
controller = ControllerActions(
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
onTint = { t -> ControllerPrefs.setTint(this, t); refreshController() },
@@ -475,6 +485,13 @@ class MainActivity : ComponentActivity() {
)
if (showCredits) CreditsDialog { showCredits = false }
flood?.let { f -> com.droiddeck.launcher.ui.LaunchFlood(f.from, onProgress = { floodProgress = it }) { launchFlooded(f) } }
+ returning?.let { r ->
+ com.droiddeck.launcher.ui.FloodReturn(androidx.compose.ui.graphics.Color(r.color), r.to, onProgress = { floodProgress = it }) {
+ returning = null
+ floodProgress = 0f
+ com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
+ }
+ }
}
}
@@ -551,6 +568,10 @@ class MainActivity : ComponentActivity() {
override fun onResume() {
super.onResume()
com.droiddeck.launcher.ui.Motion.refresh(this)
+ // Back from a session stopped behind a flood: open on its blue, before the first frame.
+ com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
+ returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
+ }
refreshPhantomStatus()
// Swaps queued while a game ran on that Proton go in once nothing uses it (usually the
// session has just ended). Cheap when nothing is queued.
@@ -586,6 +607,7 @@ class MainActivity : ComponentActivity() {
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
// The session covers the page by now; coming back finds it as it was.
flood = null
+ returning = null
floodProgress = 0f
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
super.onStop()
@@ -785,6 +807,7 @@ class MainActivity : ComponentActivity() {
storageOptions = storageOptions,
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
+ steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
@@ -837,6 +860,11 @@ class MainActivity : ComponentActivity() {
},
onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id },
+ onSteamDeckMode = { on ->
+ SessionPrefs.setSteamDeckMode(this, on)
+ steamDeckMode = on
+ steamChannel = SessionPrefs.steamChannel(this)
+ },
onRunSteamAtStartup = { on ->
SessionPrefs.setRunSteamAtStartup(this, on)
runSteamAtStartup = on
@@ -867,14 +895,13 @@ class MainActivity : ComponentActivity() {
PerformancePage(
cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) },
clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores,
- tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, steamDeckMode = steamDeckMode, noXalia = noXalia,
+ tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia,
prootNoSeccomp = prootNoSeccomp, guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on },
onZinkLazy = { on -> SessionPrefs.setZinkLazy(this, on); zinkLazy = on },
onGlThread = { on -> SessionPrefs.setGlThread(this, on); glThread = on },
onNoGlError = { on -> SessionPrefs.setNoGlError(this, on); noGlError = on },
- onSteamDeckMode = { on -> SessionPrefs.setSteamDeckMode(this, on); steamDeckMode = on },
onNoXalia = { on -> SessionPrefs.setNoXalia(this, on); noXalia = on },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
@@ -995,14 +1022,14 @@ class MainActivity : ComponentActivity() {
val games = if (ready) Library.steamGames(this) + com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art ->
Library.SteamGame(
- g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId,
+ g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId,
hero = art.hero ?: art.header, gameFiles = g.folder,
- protonPrefix = Library.protonPrefix(this, g.appId),
+ protonPrefix = Library.protonPrefix(this, g.steamAppId?.toLong() ?: g.appId),
)
}
} else emptyList()
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
- ui.post { steamGames = games; emulatorList = emus }
+ ui.post { steamGames = games.distinctBy { it.gameId }; emulatorList = emus }
// Box art for the games that have none, fetched after the list is up; the list is
// rebuilt once if any was found.
if (!OfflineMode.enabled(this) && CoverArt.fetchMissing(this, emus.flatMap { it.games })) {
@@ -1044,15 +1071,18 @@ class MainActivity : ComponentActivity() {
}
private fun refreshPhantomStatus() {
- phantomProcessStatus = PhantomProcessLimit.read(contentResolver)
+ phantomProcessStatus = PhantomProcessLimit.read(this)
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
- "${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.ADB_COMMAND}"
+ "${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.adbCommand()}"
} else null
}
private fun openDeveloperOptions(displayId: Int?) {
+ val highlight = if (PhantomProcessLimit.hasDeveloperToggle() &&
+ WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) null else "toggle_adb_wireless"
val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ .apply { if (highlight != null) putExtra(":settings:fragment_args_key", highlight) }
try {
if (displayId == null) startActivity(intent)
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle())
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index ae6c63ec47..82d9f86e69 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -29,6 +29,8 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.gpu.FrameGen
@@ -144,6 +146,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// Compose reads these; the activity writes them.
private var drawerOpen by mutableStateOf(false)
+ /** A stop growing out of the dialog's Stop (overlay px); the session ends once it covers the screen. */
+ private var quitFrom by mutableStateOf(null)
+ /** Left behind that flood: the front end opens on its blue, so no sink of our own. */
+ private var quitFlooded = false
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */
private var drawerComponents by mutableStateOf(null)
private var drawerPage by mutableIntStateOf(0)
@@ -394,6 +400,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onBackground = { drawerOpen = false; moveTaskToBack(true) },
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
+ onStopFrom = { onScreen ->
+ drawerOpen = false
+ if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) {
+ if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() }
+ } else {
+ val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) }
+ quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat())
+ }
+ },
onClose = { drawerOpen = false },
components = drawerComponents,
onComponentsRefresh = { refreshDrawerComponents() },
@@ -403,6 +418,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
title = pausedTitle(),
onResume = { SessionService.resume(this@SessionActivity) },
)
+ quitFrom?.let { from ->
+ val error = androidx.compose.material3.MaterialTheme.colorScheme.error
+ com.droiddeck.launcher.ui.LaunchFlood(
+ from, onProgress = {},
+ fromColors = error to androidx.compose.ui.graphics.lerp(error, androidx.compose.ui.graphics.Color.Black, 0.12f),
+ cornerAtRest = 20.dp,
+ ) { finishFlooded() }
+ }
}
}
}
@@ -437,7 +460,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
performBackAction(double = false)
}
pendingBackAction = pending
- uiHandler.postDelayed(pending, BACK_DOUBLE_PRESS_TIMEOUT_MS)
+ // Android's own double-tap window (300 ms): the single action waits it out, so it is felt.
+ uiHandler.postDelayed(pending, android.view.ViewConfiguration.getDoubleTapTimeout().toLong())
}
private fun performBackAction(double: Boolean) {
@@ -1554,16 +1578,27 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.onDestroy()
}
+ /** The screen is all blue: the session stops and the front end opens on the same blue (FloodReturn). */
+ private fun finishFlooded() {
+ if (isFinishing) return
+ val signal = com.droiddeck.launcher.ui.Themes.byId(SessionPrefs.theme(this)).signal
+ com.droiddeck.launcher.ui.QuitFlood.mark(signal.toArgb())
+ window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(signal.toArgb()))
+ quitFlooded = true
+ SessionService.stop(this)
+ finish()
+ }
+
/** Leaving the session sinks its surface back down onto the front end. */
override fun finish() {
super.finish()
- overridePendingTransition(R.anim.session_hold, R.anim.session_sink)
+ if (quitFlooded) overridePendingTransition(0, 0)
+ else overridePendingTransition(R.anim.session_hold, R.anim.session_sink)
}
companion object {
private const val TAG = "SessionActivity"
private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION
- private const val BACK_DOUBLE_PRESS_TIMEOUT_MS = 500L
private const val CURSOR_PAD_HOLD_MS = 1200L
private const val DRAWER_HAT_THRESHOLD = 0.5f
private const val DRAWER_STICK_ENTER_THRESHOLD = 0.55f
diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
index 15868ccfec..a0d44b1725 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt
@@ -163,7 +163,7 @@ object DeviceReport {
})
h("Android process limits")
- k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context.contentResolver)))
+ k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context)))
h("Device switch files in Download")
for (name in listOf("droiddeck-env", "droiddeck-tu-debug", "droiddeck-driver",
diff --git a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt
index 103bf05563..4155a29dd0 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/PhantomProcessLimit.kt
@@ -1,6 +1,6 @@
package com.droiddeck.launcher.core
-import android.content.ContentResolver
+import android.content.Context
import android.os.Build
import android.provider.Settings
@@ -14,17 +14,53 @@ enum class PhantomProcessStatus {
}
object PhantomProcessLimit {
- const val ADB_COMMAND = "adb shell settings put global settings_enable_monitor_phantom_procs false"
- const val SHELL_COMMAND = "settings put global settings_enable_monitor_phantom_procs false"
private const val SETTING = "settings_enable_monitor_phantom_procs"
- fun adbCommand(enabled: Boolean): String =
- "adb shell settings put global $SETTING ${if (enabled) "true" else "false"}"
+ private const val MAX_PHANTOM = "2147483647"
+ private const val PREFS = "phantom-process-limit"
+ private const val PREF_ANDROID_12_OFF = "android12-off"
- fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
+ fun usesDeviceConfig(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk == Build.VERSION_CODES.S
+
+ fun shellCommands(enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): List = when {
+ usesDeviceConfig(sdk) && enabled -> listOf(
+ "device_config delete activity_manager max_phantom_processes",
+ "device_config set_sync_disabled_for_tests none",
+ )
+ usesDeviceConfig(sdk) -> listOf(
+ "device_config set_sync_disabled_for_tests persistent",
+ "device_config put activity_manager max_phantom_processes $MAX_PHANTOM",
+ )
+ else -> listOf("settings put global $SETTING ${if (enabled) "true" else "false"}")
+ }
+
+ fun verifyCommand(sdk: Int = Build.VERSION.SDK_INT): String =
+ if (usesDeviceConfig(sdk)) "device_config get activity_manager max_phantom_processes"
+ else "settings get global $SETTING"
+
+ fun verified(output: String, enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): Boolean {
+ val value = output.trim()
+ return if (usesDeviceConfig(sdk)) (value == MAX_PHANTOM) != enabled
+ else value == if (enabled) "true" else "false"
+ }
+
+ fun adbCommand(enabled: Boolean, sdk: Int = Build.VERSION.SDK_INT): String =
+ shellCommands(enabled, sdk).joinToString(" && ") { "adb shell $it" }
+
+ fun adbCommand(): String = adbCommand(false)
+
+ fun rememberAndroid12(context: Context, off: Boolean) {
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(PREF_ANDROID_12_OFF, off).apply()
+ }
+
+ fun read(context: Context, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
+ if (usesDeviceConfig(sdk)) {
+ val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
+ return if (off) PhantomProcessStatus.DISABLED else PhantomProcessStatus.UNREADABLE
+ }
val global = try {
- Settings.Global.getString(resolver, SETTING)
+ Settings.Global.getString(context.contentResolver, SETTING)
} catch (_: Exception) {
return PhantomProcessStatus.UNREADABLE
}
@@ -57,6 +93,8 @@ object PhantomProcessLimit {
null
}
+ fun hasDeveloperToggle(sdk: Int = Build.VERSION.SDK_INT): Boolean = sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
+
fun blocksSteam(status: PhantomProcessStatus): Boolean =
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
@@ -69,20 +107,20 @@ object PhantomProcessLimit {
}
fun instructions(status: PhantomProcessStatus): String = when (status) {
- PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
- PhantomProcessStatus.UNSET -> "This setting is unset, so the ROM default applies and may enforce the limit. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
- PhantomProcessStatus.UNREADABLE -> "DroidDeck could not read the setting. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
+ PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence() + " If that is not possible, connect this device to a computer with ADB and run the command below. Return here and check again."
PhantomProcessStatus.DISABLED -> "Steam sessions can start."
PhantomProcessStatus.NOT_APPLICABLE -> "This Android version does not use this limit."
}
fun gateInstructions(status: PhantomProcessStatus): String = when (status) {
- PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options."
- PhantomProcessStatus.UNSET -> "The ROM default may enforce this limit. Explicitly turn off “Restrict child processes” in Developer options."
- PhantomProcessStatus.UNREADABLE -> "DroidDeck could not check this setting. Turn off “Restrict child processes” in Developer options."
+ PhantomProcessStatus.ENABLED, PhantomProcessStatus.UNSET, PhantomProcessStatus.UNREADABLE -> fixSentence()
else -> instructions(status)
}
+ fun fixSentence(sdk: Int = Build.VERSION.SDK_INT): String =
+ if (hasDeveloperToggle(sdk)) "Turn on “Disable child process restrictions” in Developer options, and keep Developer options on afterwards."
+ else "This Android version has no switch for it. Use Wireless debugging to change it from this device."
+
fun reportValue(status: PhantomProcessStatus): String = when (status) {
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt
index 82b6e4d636..c97ba3a861 100644
--- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt
+++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt
@@ -6,7 +6,9 @@ import android.net.nsd.NsdServiceInfo
import com.flyfishxu.kadb.Kadb
import com.flyfishxu.kadb.cert.KadbCert
import java.io.File
+import java.net.Inet4Address
import java.net.InetAddress
+import java.net.NetworkInterface
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
@@ -19,6 +21,7 @@ object WirelessAdbFix {
private const val KEY_FILE = "wireless-adb-key.pem"
private const val HOST_FILE = "wireless-adb-host.txt"
private const val CONNECTION_FILE = "wireless-adb-connection.txt"
+ const val LOOPBACK = "127.0.0.1"
private data class SavedConnection(val host: String, val port: Int?)
@@ -76,9 +79,27 @@ object WirelessAdbFix {
}
/** Finds this paired device's separate TLS connection port from Android's ADB mDNS record. */
+ fun isLocalAddress(address: InetAddress): Boolean = runCatching {
+ if (address.isLoopbackAddress) return true
+ NetworkInterface.getNetworkInterfaces()?.toList().orEmpty().any { network ->
+ network.inetAddresses.toList().any { it.address.contentEquals(address.address) }
+ }
+ }.getOrDefault(address is Inet4Address)
+
+ fun localConnectPort(context: Context): Int? =
+ tlsPortProperty()
+ ?: findConnectPort(context, LOOPBACK)
+
+ private fun tlsPortProperty(): Int? = runCatching {
+ Class.forName("android.os.SystemProperties").getMethod("get", String::class.java)
+ .invoke(null, "service.adb.tls.port") as? String
+ }.getOrNull()?.trim()?.toIntOrNull()?.takeIf { it in 1..65535 }
+
fun findConnectPort(context: Context, pairedHost: String, timeoutSeconds: Long = 12): Int? {
val manager = context.applicationContext.getSystemService(Context.NSD_SERVICE) as NsdManager
- val expectedAddress = runCatching { InetAddress.getByName(pairedHost).address }.getOrNull() ?: return null
+ val paired = runCatching { InetAddress.getByName(pairedHost) }.getOrNull() ?: return null
+ val matches: (InetAddress) -> Boolean =
+ if (paired.isLoopbackAddress) ::isLocalAddress else { address -> address.address.contentEquals(paired.address) }
val resolvedPort = AtomicInteger(-1)
val finished = AtomicBoolean(false)
val latch = CountDownLatch(1)
@@ -101,8 +122,8 @@ object WirelessAdbFix {
}
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
- val address = serviceInfo.host?.address
- if (address != null && address.contentEquals(expectedAddress) && finished.compareAndSet(false, true)) {
+ val address = serviceInfo.host
+ if (address != null && matches(address) && finished.compareAndSet(false, true)) {
resolvedPort.set(serviceInfo.port)
latch.countDown()
} else {
@@ -148,14 +169,16 @@ object WirelessAdbFix {
fun setChildProcessLimit(context: Context, host: String, port: Int, enabled: Boolean) {
loadOrCreateIdentity(context.applicationContext)
Kadb.create(host, port).use { adb ->
- val value = if (enabled) "true" else "false"
- val change = adb.shell("settings put global settings_enable_monitor_phantom_procs $value")
- check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } }
- val result = adb.shell("settings get global settings_enable_monitor_phantom_procs")
- check(result.exitCode == 0 && result.output.trim() == value) {
+ PhantomProcessLimit.shellCommands(enabled).forEach { command ->
+ val change = adb.shell(command)
+ check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } }
+ }
+ val result = adb.shell(PhantomProcessLimit.verifyCommand())
+ check(result.exitCode == 0 && PhantomProcessLimit.verified(result.output, enabled)) {
"Android did not confirm the child-process limit was changed: ${result.allOutput.trim()}"
}
}
+ if (PhantomProcessLimit.usesDeviceConfig()) PhantomProcessLimit.rememberAndroid12(context, !enabled)
saveConnection(context, host, port)
}
diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt
new file mode 100644
index 0000000000..d4645962af
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbPairingService.kt
@@ -0,0 +1,270 @@
+package com.droiddeck.launcher.core
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.RemoteInput
+import android.app.Service
+import android.content.Context
+import android.content.Intent
+import android.net.nsd.NsdManager
+import android.net.nsd.NsdServiceInfo
+import android.os.Build
+import android.os.Handler
+import android.os.IBinder
+import android.os.Looper
+import com.droiddeck.launcher.MainActivity
+import com.droiddeck.launcher.R
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+
+class WirelessAdbPairingService : Service() {
+ sealed interface Stage {
+ data object Idle : Stage
+ data object Waiting : Stage
+ data class CodeNeeded(val error: String? = null) : Stage
+ data class Working(val step: String) : Stage
+ data object Done : Stage
+ data class Failed(val error: String) : Stage
+ }
+
+ private val main = Handler(Looper.getMainLooper())
+ private var nsd: NsdManager? = null
+ private var discovery: NsdManager.DiscoveryListener? = null
+ private var pairingHost: String? = null
+ private var pairingPort: Int? = null
+ @Volatile private var working = false
+ private val timeout = Runnable { finish(Stage.Failed("Timed out waiting for the pairing pop-up. Try again from DroidDeck.")) }
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ when (intent?.action) {
+ ACTION_CODE -> {
+ val code = RemoteInput.getResultsFromIntent(intent)?.getCharSequence(KEY_CODE)
+ ?.filter(Char::isDigit)?.toString().orEmpty()
+ onCode(code)
+ }
+ ACTION_CANCEL -> finish(Stage.Idle)
+ else -> begin()
+ }
+ return START_NOT_STICKY
+ }
+
+ private fun begin() {
+ pairingHost = null
+ pairingPort = null
+ working = false
+ publish(Stage.Waiting)
+ startForeground(NOTIFICATION_ID, notification(Stage.Waiting))
+ startDiscovery()
+ main.removeCallbacks(timeout)
+ main.postDelayed(timeout, TIMEOUT_MS)
+ }
+
+ private fun startDiscovery() {
+ stopDiscovery()
+ val manager = getSystemService(Context.NSD_SERVICE) as NsdManager
+ val listener = object : NsdManager.DiscoveryListener {
+ override fun onDiscoveryStarted(serviceType: String) = Unit
+ override fun onServiceFound(serviceInfo: NsdServiceInfo) {
+ if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return
+ runCatching { manager.resolveService(serviceInfo, resolveListener()) }
+ }
+ override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
+ override fun onDiscoveryStopped(serviceType: String) = Unit
+ override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
+ main.post { finish(Stage.Failed("Could not look for the pairing pop-up ($errorCode). Check that Wi-Fi is on.")) }
+ }
+ override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit
+ }
+ runCatching { manager.discoverServices("$PAIRING_TYPE.", NsdManager.PROTOCOL_DNS_SD, listener) }
+ .onSuccess { nsd = manager; discovery = listener }
+ .onFailure { finish(Stage.Failed("Could not look for the pairing pop-up: ${it.localizedMessage}")) }
+ }
+
+ private fun resolveListener() = object : NsdManager.ResolveListener {
+ override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit
+ override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
+ val address = serviceInfo.host ?: return
+ if (!WirelessAdbFix.isLocalAddress(address)) return
+ main.post {
+ if (working || current.value == Stage.Done) return@post
+ pairingHost = address.hostAddress
+ pairingPort = serviceInfo.port
+ if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded())
+ }
+ }
+ }
+
+ private fun onCode(code: String) {
+ val host = pairingHost
+ val port = pairingPort
+ if (working) return
+ if (host == null || port == null) {
+ show(Stage.Waiting)
+ return
+ }
+ if (code.length != 6) {
+ show(Stage.CodeNeeded("Enter all 6 digits of the code"))
+ return
+ }
+ working = true
+ show(Stage.Working("Pairing…"))
+ Thread({
+ val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } }
+ if (paired.isFailure) {
+ main.post {
+ working = false
+ pairingPort = null
+ show(Stage.CodeNeeded("That code didn't work. Open the pairing pop-up again and enter its new code."))
+ }
+ return@Thread
+ }
+ main.post {
+ stopDiscovery()
+ show(Stage.Working("Paired. Connecting…"))
+ }
+ val result = runCatching {
+ val connectPort = WirelessAdbFix.localConnectPort(this)
+ ?: error("Paired, but the Wireless debugging port was not found. Keep Wireless debugging on and try again.")
+ main.post { show(Stage.Working("Applying the setting…")) }
+ WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false)
+ }
+ main.post {
+ working = false
+ finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: "Wireless debugging command failed") } ?: Stage.Done)
+ }
+ }, "wireless-adb-pairing").start()
+ }
+
+ private fun show(stage: Stage) {
+ publish(stage)
+ getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, notification(stage))
+ }
+
+ private fun finish(stage: Stage) {
+ main.removeCallbacks(timeout)
+ stopDiscovery()
+ publish(stage)
+ val manager = getSystemService(NotificationManager::class.java)
+ if (stage is Stage.Done || stage is Stage.Failed) {
+ manager?.notify(NOTIFICATION_ID, notification(stage))
+ stopForeground(STOP_FOREGROUND_DETACH)
+ } else {
+ stopForeground(STOP_FOREGROUND_REMOVE)
+ manager?.cancel(NOTIFICATION_ID)
+ }
+ stopSelf()
+ }
+
+ private fun stopDiscovery() {
+ val listener = discovery ?: return
+ runCatching { nsd?.stopServiceDiscovery(listener) }
+ discovery = null
+ }
+
+ override fun onDestroy() {
+ main.removeCallbacks(timeout)
+ stopDiscovery()
+ if (current.value.let { it is Stage.Waiting || it is Stage.CodeNeeded || it is Stage.Working }) publish(Stage.Idle)
+ super.onDestroy()
+ }
+
+ private fun notification(stage: Stage): Notification {
+ val manager = getSystemService(NotificationManager::class.java)
+ manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "Wireless debugging setup",
+ NotificationManager.IMPORTANCE_HIGH).apply {
+ description = "Asks for the Wireless debugging pairing code while Settings is open"
+ setShowBadge(false)
+ setSound(null, null)
+ enableVibration(false)
+ })
+ val open = PendingIntent.getActivity(this, 0,
+ Intent(this, MainActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
+ PendingIntent.FLAG_IMMUTABLE)
+ val cancel = PendingIntent.getService(this, 1,
+ Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
+ val builder = Notification.Builder(this, CHANNEL_ID)
+ .setSmallIcon(R.drawable.ic_stat_session)
+ .setContentIntent(open)
+ .setShowWhen(false)
+ .setCategory(Notification.CATEGORY_STATUS)
+ when (stage) {
+ Stage.Waiting, Stage.Idle -> builder
+ .setContentTitle("Pair Wireless debugging")
+ .setContentText("Turn on Wireless debugging, then tap “Pair device with pairing code”.")
+ .setStyle(Notification.BigTextStyle().bigText(
+ "Turn on Wireless debugging, then tap “Pair device with pairing code”. Stay in Settings: the code goes in this notification."))
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .addAction(Notification.Action.Builder(null, "Cancel", cancel).build())
+ is Stage.CodeNeeded -> {
+ val reply = PendingIntent.getService(this, 2,
+ Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CODE),
+ if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ else PendingIntent.FLAG_UPDATE_CURRENT)
+ val input = RemoteInput.Builder(KEY_CODE).setLabel("6-digit pairing code").build()
+ val text = stage.error ?: "Tap Enter code and type the 6 digits shown in Settings."
+ builder
+ .setContentTitle(if (stage.error == null) "Enter the Wi-Fi pairing code" else "Try the code again")
+ .setContentText(text)
+ .setStyle(Notification.BigTextStyle().bigText(text))
+ .setOngoing(true)
+ .addAction(Notification.Action.Builder(null, "Enter code", reply).addRemoteInput(input).build())
+ .addAction(Notification.Action.Builder(null, "Cancel", cancel).build())
+ }
+ is Stage.Working -> builder
+ .setContentTitle("Setting up Steam")
+ .setContentText(stage.step)
+ .setProgress(0, 0, true)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ Stage.Done -> builder
+ .setContentTitle("Steam is ready")
+ .setContentText("Tap to go back to DroidDeck. You can turn Wireless debugging off now.")
+ .setStyle(Notification.BigTextStyle().bigText("Tap to go back to DroidDeck. You can turn Wireless debugging off now."))
+ .setAutoCancel(true)
+ is Stage.Failed -> builder
+ .setContentTitle("Wireless debugging setup stopped")
+ .setContentText(stage.error)
+ .setStyle(Notification.BigTextStyle().bigText(stage.error))
+ .setAutoCancel(true)
+ }
+ return builder.build()
+ }
+
+ companion object {
+ private const val CHANNEL_ID = "wireless-adb-pairing"
+ private const val NOTIFICATION_ID = 3
+ private const val PAIRING_TYPE = "_adb-tls-pairing._tcp"
+ private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
+ private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
+ private const val KEY_CODE = "code"
+ private const val TIMEOUT_MS = 5 * 60_000L
+
+ private val current = MutableStateFlow(Stage.Idle)
+ val stage: StateFlow = current
+
+ private fun publish(stage: Stage) { current.value = stage }
+
+ fun start(context: Context) {
+ context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
+ publish(Stage.Waiting)
+ val intent = Intent(context, WirelessAdbPairingService::class.java)
+ if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
+ }
+
+ fun cancel(context: Context) {
+ if (current.value.let { it is Stage.Done || it is Stage.Failed || it is Stage.Idle }) {
+ publish(Stage.Idle)
+ return
+ }
+ context.startService(Intent(context, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL))
+ }
+
+ fun notificationsEnabled(context: Context): Boolean =
+ context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt
index bd5a759832..6d833d9318 100644
--- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt
+++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt
@@ -1,24 +1,15 @@
package com.droiddeck.launcher.frontend
import android.content.Context
-import android.os.Environment
import android.util.Log
+import com.droiddeck.launcher.runtime.LinuxRuntime
+import org.json.JSONObject
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.util.zip.CRC32
-/**
- * The user's own Windows games, added to the Steam client's library.
- *
- * A Games folder is scanned one level deep: each subfolder is one game, and the program to launch
- * is the .exe in it that looks most like the game - the one named after the folder, else the
- * largest, never an installer, redistributable or crash reporter - unless the user picked one
- * for that game. Each game becomes a non-Steam shortcut in the client, under the ARM64 Proton,
- * with the appid the client itself would derive, so launching from the rail and from the
- * client's own library are the same thing. Any number of Games folders, from anywhere on the
- * device: each is bound into the session under /root/Games on its own.
- */
+/** Windows game folders shared with the Steam session. */
object AddedGames {
private const val TAG = "AddedGames"
@@ -29,6 +20,7 @@ object AddedGames {
/** What steam://rungameid/ takes for a shortcut. */
val gameId: Long,
val candidates: List,
+ val steamAppId: Int? = null,
) {
fun folderName(): String = folder.name
}
@@ -96,12 +88,15 @@ object AddedGames {
fun scan(context: Context): List {
val out = ArrayList()
- for (root in roots(context)) {
- val dir = root.host
+ val folders = roots(context).map { it.host } + listOfNotNull(
+ GameStorage.effective(context)?.let { File(it.path) },
+ GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
+ )
+ for (dir in folders.distinctBy { it.absolutePath }) {
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) scanGame(context, folder, out)
}
- return out
+ return out.distinctBy { it.folder.canonicalPath }
}
private fun scanGame(context: Context, folder: File, out: MutableList) {
@@ -115,10 +110,23 @@ object AddedGames {
val name = folder.name
val crc = CRC32().apply { update(("\"$guestExe\"" + name).toByteArray()) }.value
val appId = crc or 0x80000000L
- out.add(Game(folder, name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, candidates))
+ val steamRoot = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
+ val steamId = steamRoute(steamRoot, appId)
+ out.add(Game(folder, name, exe, guestExe, guestDir, appId,
+ steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId))
}
}
+ private fun steamRoute(root: File, appId: Long): Int? = runCatching {
+ val users = File(root, "config/loginusers.vdf").readText()
+ val blocks = Regex(""""(\d{5,})"\s*\{([^}]*)\}""")
+ val recent = blocks.findAll(users).firstOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) }
+ ?: return@runCatching null
+ val account = recent.groupValues[1].toLong() - 76561197960265728L
+ JSONObject(File(root, "userdata/$account/config/.droiddeck-routes.json").readText())
+ .optInt(appId.toString()).takeIf { it > 0 }
+ }.getOrNull()
+
/** The list the session hands the runtime's shortcuts writer; one file per session start. */
fun writeListing(context: Context, games: List): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
@@ -126,6 +134,7 @@ object AddedGames {
games.forEachIndexed { i, g ->
if (i > 0) json.append(',')
json.append("{\"name\":").append(quote(g.name)).append(",\"exe\":").append(quote(g.guestExe))
+ .append(",\"folder\":").append(quote(guestPath(context, g.folder) ?: g.guestDir))
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
// The art, as the session sees it: the app's cache is bound at its own path, a file in
// the game's folder at the folder's guest path.
@@ -145,5 +154,5 @@ object AddedGames {
return guestPath(context, file)
}
- private fun quote(s: String) = "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
+ private fun quote(s: String): String = JSONObject.quote(s)
}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
index 5189049733..890fde729f 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
+++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
@@ -26,9 +26,24 @@ public final class PadBridge {
/** Slot 0 is the one the session exports; extra slots would each show as another pad. */
private static final int SLOT = 0;
private static final float DEAD_ZONE = 0.12f;
- private static final long QAM_GUIDE_LEAD_MS = 80;
- private static final long QAM_A_HOLD_MS = 120;
- private static final long QAM_GUIDE_TAIL_MS = 40;
+ // The client takes A as part of the chord only once it has had Guide held for a while, and a
+ // client starved of CPU needs longer. Too short, and it acts on A as well, selecting whatever it
+ // had focused before opening QAM: with 80 ms of lead that was 3 times in 20 at rest, and 250 ms
+ // none in 20; with the session down to 1 fps a fixed 400 ms still let 3 in 15 through, where
+ // 1000 ms let none. The lead keeps 80 ms when frames are quick, for a QAM that feels immediate,
+ // and stretches to eight frames when they are slow.
+ private static final long QAM_GUIDE_LEAD_MIN_MS = 80;
+ private static final long QAM_GUIDE_LEAD_MAX_MS = 1500;
+ private static final int QAM_GUIDE_LEAD_FRAMES = 8;
+ private static final long QAM_A_HOLD_MS = 200;
+ private static final long QAM_GUIDE_TAIL_MS = 200;
+ // Off the main thread, so a busy UI cannot shorten or stretch the steps.
+ private static final Handler chordHandler;
+ static {
+ android.os.HandlerThread thread = new android.os.HandlerThread("qam-chord", android.os.Process.THREAD_PRIORITY_DISPLAY);
+ thread.start();
+ chordHandler = new Handler(thread.getLooper());
+ }
private final FakeInputWriter writer;
private final PadState state = new PadState();
@@ -212,21 +227,27 @@ public final class PadBridge {
qamChordActive = true;
int generation = ++qamChordGeneration;
publish();
- mainHandler.postDelayed(() -> pressQamA(generation), QAM_GUIDE_LEAD_MS);
+ chordHandler.postDelayed(() -> pressQamA(generation), qamGuideLeadMs());
+ }
+
+ static long qamGuideLeadMs() {
+ long frame = com.droiddeck.launcher.wayland.WaylandCompositor.recentFrameIntervalMs();
+ if (frame <= 0) return QAM_GUIDE_LEAD_MIN_MS;
+ return Math.max(QAM_GUIDE_LEAD_MIN_MS, Math.min(QAM_GUIDE_LEAD_MAX_MS, frame * QAM_GUIDE_LEAD_FRAMES));
}
private synchronized void pressQamA(int generation) {
if (generation != qamChordGeneration || !qamChordActive) return;
qamSyntheticAPressed = true;
publish();
- mainHandler.postDelayed(() -> releaseQamA(generation), QAM_A_HOLD_MS);
+ chordHandler.postDelayed(() -> releaseQamA(generation), QAM_A_HOLD_MS);
}
private synchronized void releaseQamA(int generation) {
if (generation != qamChordGeneration || !qamChordActive) return;
qamSyntheticAPressed = false;
publish();
- mainHandler.postDelayed(() -> releaseQamGuide(generation), QAM_GUIDE_TAIL_MS);
+ chordHandler.postDelayed(() -> releaseQamGuide(generation), QAM_GUIDE_TAIL_MS);
}
private synchronized void releaseQamGuide(int generation) {
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
index c8875dadef..19ffe85299 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
@@ -193,6 +193,8 @@ public final class LinuxRuntime {
}
}
bindGpuNode(context, cmd);
+ bindAdrenoStats(cmd);
+ bindCpuTemps(cmd, root);
if (extraBinds != null) {
for (String spec : extraBinds) bind(cmd, spec);
}
@@ -244,6 +246,82 @@ public final class LinuxRuntime {
bind(cmd, KGSL_DEVICE + ":/dev/dri/" + node);
}
+ /**
+ * Valve's mangoapp (Deck mode's performance overlay) reads an Adreno GPU's load, clock and
+ * temperatures from where they are on Valve's own hardware; every Adreno under Android keeps
+ * them in KGSL's sysfs, readable by the app, though which files a kernel has differs between
+ * Snapdragon generations - so each value takes the first source that exists, the order other
+ * Android PC emulators (GameNative, Winlator forks) read them in. A value found nowhere is left
+ * alone.
+ */
+ private static void bindAdrenoStats(List cmd) {
+ String kgsl = "/sys/class/kgsl/kgsl-3d0/";
+ String gpuTemp = firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu"));
+ String[][] stats = {
+ {firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load"), "/sys/kernel/debug/dri/0/perf_now"},
+ {firstReadable(kgsl + "devfreq/cur_freq", kgsl + "gpuclk"),
+ "/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"},
+ {gpuTemp, "/sys/class/thermal/thermal_zone28/temp"},
+ {gpuTemp, "/sys/class/thermal/thermal_zone26/temp"},
+ {thermalZone("ddr"), "/sys/class/thermal/thermal_zone22/temp"},
+ };
+ for (String[] stat : stats) {
+ if (stat[0] != null) bind(cmd, stat[0] + ":" + stat[1]);
+ }
+ }
+
+ /**
+ * mangoapp's CPU temperature is the mean of the thermal zones named cpuN-thermal or
+ * cpuN-top-thermal, as mainline kernels name them; Android kernels name the same sensors
+ * cpuss-0, cpu-1-0, cpu0-silver-usr, apc1-cpu0-usr and the like, so those zones are shown
+ * under the mainline name.
+ */
+ private static void bindCpuTemps(List cmd, File root) {
+ File name = new File(root, "etc/bannerlator/cpu-thermal-type");
+ try {
+ if (!name.isFile()) Files.write(name.toPath(), "cpu0-thermal\n".getBytes(StandardCharsets.US_ASCII));
+ } catch (IOException e) {
+ return;
+ }
+ for (java.util.Map.Entry zone : thermalZones().entrySet()) {
+ String type = zone.getKey();
+ if (type.contains("cpu") && !type.contains("gpu") && !type.matches("cpu\\d-(top-)?thermal")) {
+ bind(cmd, name.getPath() + ":" + new File(zone.getValue(), "type").getPath());
+ }
+ }
+ }
+
+ private static String firstReadable(String... paths) {
+ for (String path : paths) {
+ if (path != null && new File(path).canRead()) return path;
+ }
+ return null;
+ }
+
+ /** The temp file of the thermal zone for a sensor: the one named so, else the first whose name has it. */
+ private static String thermalZone(String sensor) {
+ java.util.Map zones = thermalZones();
+ File zone = zones.get(sensor);
+ for (java.util.Map.Entry e : new java.util.TreeMap<>(zones).entrySet()) {
+ if (zone == null && e.getKey().contains(sensor)) zone = e.getValue();
+ }
+ return zone != null ? new File(zone, "temp").getPath() : null;
+ }
+
+ /** The device's thermal zones by their sensor's name, in lower case. */
+ private static java.util.Map thermalZones() {
+ java.util.Map byType = new java.util.HashMap<>();
+ File[] zones = new File("/sys/class/thermal").listFiles((dir, n) -> n.startsWith("thermal_zone"));
+ if (zones == null) return byType;
+ for (File zone : zones) {
+ try (java.io.BufferedReader r = new java.io.BufferedReader(new java.io.FileReader(new File(zone, "type")))) {
+ byType.putIfAbsent(String.valueOf(r.readLine()).trim().toLowerCase(java.util.Locale.ROOT), zone);
+ } catch (IOException ignored) {
+ }
+ }
+ return byType;
+ }
+
private static void bind(List cmd, String spec) {
cmd.add("-b");
cmd.add(spec);
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
index be31867ac3..2bb2f1010e 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt
@@ -40,6 +40,7 @@ object SessionFiles {
"usr/local/bin/bannerlator-desktop-games" to "usr/local/bin/bannerlator-desktop-games",
"usr/local/bin/bannerlator-steam-shim" to "usr/local/bin/bannerlator-steam-shim",
"usr/local/bin/bannerlator-steam-shortcuts" to "usr/local/bin/bannerlator-steam-shortcuts",
+ "usr/local/bin/bannerlator-steam-games" to "usr/local/bin/bannerlator-steam-games",
"usr/local/bin/bannerlator-pad-defaults" to "usr/local/bin/bannerlator-pad-defaults",
// The SteamOS helpers the client calls in Deck mode: the two Armada found it needs, plus
// the three under /usr/bin, all no-ops that answer "nothing to do" (see each file).
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
index 0b3d3b2cd3..f82732517b 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt
@@ -254,7 +254,7 @@ object SessionPrefs {
fun noGlError(context: Context): Boolean = prefs(context).getBoolean("noGlError", true)
fun setNoGlError(context: Context, on: Boolean) { prefs(context).edit().putBoolean("noGlError", on).apply() }
- /** `steam -steamdeck -steamos3`: the client as SteamOS runs it. Expects Deck hardware; untested. */
+ /** Runs the SteamOS gamepad client with its Quick Access performance controls. */
fun steamDeckMode(context: Context): Boolean = prefs(context).getBoolean("steamDeckMode", false)
fun setSteamDeckMode(context: Context, on: Boolean) { prefs(context).edit().putBoolean("steamDeckMode", on).apply() }
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
index 888d37fa7c..d5de2804ea 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt
@@ -309,6 +309,7 @@ class SessionService : Service() {
val added = com.droiddeck.launcher.frontend.AddedGames.scan(this)
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added)
guest.add("BL_ADDED_GAMES=" + listing.path)
+ if (OfflineMode.enabled(this)) guest.add("BL_STEAM_OFFLINE=1")
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
}
// Where the guest leaves a request for another session (the desktop's Steam launchers).
@@ -736,6 +737,24 @@ class SessionService : Service() {
return try { Pair(fields[1].toInt(), fields[19].toLong()) } catch (e: NumberFormatException) { null }
}
+ private fun askSteamToExit(prootPid: Int) {
+ if (!File("/proc/$prootPid").exists()) return
+ val request = File(LinuxRuntime.sessionRoot(this), "steam-stop")
+ try {
+ request.writeText("")
+ } catch (e: Exception) {
+ Log.w(TAG, "could not ask the Steam client to exit", e)
+ return
+ }
+ val started = System.currentTimeMillis()
+ if (waitForExit(prootPid, STEAM_PICKUP_MS) || request.exists()) {
+ request.delete()
+ return
+ }
+ val exited = waitForExit(prootPid, STEAM_EXIT_MS)
+ Log.i(TAG, "Steam client ${if (exited) "exited" else "did not exit"} after ${System.currentTimeMillis() - started} ms")
+ }
+
private fun waitForExit(pid: Int, timeoutMs: Long): Boolean {
val deadline = System.currentTimeMillis() + timeoutMs
while (System.currentTimeMillis() < deadline) {
@@ -953,9 +972,11 @@ class SessionService : Service() {
}
components.clear()
FakeInputWriter.releaseAllRingSlots()
+ val steamClientMayRun = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
val finishAfterTeardown: () -> Unit = {
if (prootPid > 1 || auxiliary.isNotEmpty()) {
Thread({
+ if (prootPid > 1 && steamClientMayRun) askSteamToExit(prootPid)
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
if (prootPid > 1) teardown(prootPid)
killGuestLeftovers()
@@ -1114,6 +1135,8 @@ class SessionService : Service() {
"steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so")
/** How long proot gets to run its own cleanup before it is killed outright. */
private const val GRACE_MS = 1200L
+ private const val STEAM_PICKUP_MS = 1500L
+ private const val STEAM_EXIT_MS = 10_000L
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
private const val PAD_LOG_SWITCH = "Download/droiddeck-pad-log"
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt
index ee5153f0d9..d245f03467 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt
@@ -157,6 +157,8 @@ class FrontEndActions(
val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit = { _, done -> done("Wireless debugging is unavailable") },
val onCopyPhantomCommand: (Boolean) -> Unit = {},
val onDismissPhantomGate: () -> Unit = {},
+ val onStartWirelessAdbPairing: () -> Unit = {},
+ val onOpenNotificationSettings: () -> Unit = {},
val controller: ControllerActions? = null,
)
@@ -469,7 +471,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
status = s.phantomProcessStatus,
onDismiss = a.onDismissPhantomGate,
onOpenDeveloperOptions = requestDeveloperOptions,
- onSetUpWirelessAdb = { requestWirelessAdbFix(false) },
+ onFixWithWirelessDebugging = {
+ a.onStartWirelessAdbPairing()
+ requestDeveloperOptions()
+ },
+ onEnterAddressManually = { requestWirelessAdbFix(false) },
+ onCopyCommand = { a.onCopyPhantomCommand(false) },
+ onOpenNotificationSettings = a.onOpenNotificationSettings,
)
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LaunchFlood.kt b/app/src/main/java/com/droiddeck/launcher/ui/LaunchFlood.kt
index ad43b536b3..59d257273d 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/LaunchFlood.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/LaunchFlood.kt
@@ -36,9 +36,18 @@ import kotlinx.coroutines.coroutineScope
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.runtime.snapshotFlow
import androidx.compose.animation.core.spring
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.layout.LayoutCoordinates
+import androidx.compose.ui.layout.boundsInRoot
+import androidx.compose.ui.unit.Dp
+import java.lang.ref.WeakReference
+import kotlin.math.PI
+import kotlin.math.sin
// Starting a session from a blue button: the button grows until the page is its blue, and the
// loading screen opens on that blue and gathers it into the ball of the throbber.
+// Stopping one from the drawer runs it the other way: Stop grows until the page is blue, and the
+// front end opens on that blue and draws it back down into the button the session came from.
/** Carries the flood's colour to the session, which opens on it. */
const val EXTRA_FLOOD = "com.droiddeck.launcher.FLOOD"
@@ -48,6 +57,8 @@ internal object LaunchOrigin {
private var bounds: Rect? = null
private var button: Any? = null
private var at = 0L
+ /** The last button a session was started from, for a stop to return into. */
+ private var last: WeakReference? = null
/** The button a flood is growing out of: it steps aside so only the flood shows. */
var flooding by mutableStateOf(null)
@@ -55,9 +66,22 @@ internal object LaunchOrigin {
fun mark(r: Rect, key: Any) {
bounds = r
button = key
+ last = WeakReference(key)
at = SystemClock.uptimeMillis()
}
+ /**
+ * Where the button the running session was started from sits now, if it is still on screen;
+ * it hides for the return, as for the flood.
+ */
+ fun takeReturn(): Rect? {
+ val key = last?.get() as? Array<*> ?: return null
+ val c = key.getOrNull(0) as? LayoutCoordinates ?: return null
+ if (!c.isAttached) return null
+ flooding = key
+ return c.boundsInRoot()
+ }
+
/** The button behind a launch starting now, if one was pressed just before; it hides for the flood. */
fun take(): Rect? {
val b = bounds?.takeIf { SystemClock.uptimeMillis() - at < 1_500 }
@@ -68,6 +92,23 @@ internal object LaunchOrigin {
}
}
+/** A session stopped behind a flood: the blue the front end opens on, for a few seconds. */
+internal object QuitFlood {
+ private var color: Int? = null
+ private var at = 0L
+
+ fun mark(argb: Int) {
+ color = argb
+ at = SystemClock.uptimeMillis()
+ }
+
+ fun take(): Int? {
+ val c = color?.takeIf { SystemClock.uptimeMillis() - at < 3_000 }
+ color = null
+ return c
+ }
+}
+
/** The page a flood grows over, sinking back a touch as it is covered; [progress] is the flood's. */
@Composable
internal fun FloodBehind(progress: () -> Float, content: @Composable () -> Unit) {
@@ -87,9 +128,17 @@ private val Gather = CubicBezierEasing(0.6f, 0f, 0.15f, 1f)
* Swallows touches while it runs.
*/
@Composable
-internal fun LaunchFlood(from: Rect, onProgress: (Float) -> Unit, onCovered: () -> Unit) {
+internal fun LaunchFlood(
+ from: Rect,
+ onProgress: (Float) -> Unit,
+ /** The button's own colours, where it is not the page's blue one (a red Stop). */
+ fromColors: Pair? = null,
+ cornerAtRest: Dp = 12.dp,
+ onCovered: () -> Unit,
+) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
+ val start = fromColors ?: (colors.primary to pal.primary2)
// Left, top, right, bottom: 0 on the button, 1 on the page's edge. Springs overshoot past the
// edge, off the page, so the wobble is felt in the pull and never seen as a shrink.
val edges = remember { List(4) { Animatable(0f) } }
@@ -117,30 +166,83 @@ internal fun LaunchFlood(from: Rect, onProgress: (Float) -> Unit, onCovered: ()
}
}
Canvas(Modifier.fillMaxSize().onSizeChanged { page = Size(it.width.toFloat(), it.height.toFloat()) }.pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) {
- val (l, t, r, b) = edges.map { it.value }
- val mean = edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f
- // The button sinks with the page behind (FloodBehind), so the flood leaves from where it is now.
- val k = sinkScale(mean)
- val cx = size.width / 2f
- val cy = size.height / 2f
- val left = lerp(cx + (from.left - cx) * k, 0f, l)
- val top = lerp(cy + (from.top - cy) * k, 0f, t)
- val right = lerp(cx + (from.right - cx) * k, size.width, r)
- val bottom = lerp(cy + (from.bottom - cy) * k, size.height, b)
- val w = (right - left).coerceAtLeast(0f)
- val h = (bottom - top).coerceAtLeast(0f)
- // A button's corners at rest, a blob in flight, square once it fills the page.
- val blob = kotlin.math.sin(Math.PI * mean).toFloat().coerceAtLeast(0f)
- val corner = lerp(12.dp.toPx() * (1f - mean), minOf(w, h) * 0.42f, blob)
- // The button's gradient gives way to the ball's flat blue in the first half.
- val mix = (mean * 2f).coerceAtMost(1f)
- drawRoundRect(
- Brush.linearGradient(
- listOf(lerp(colors.primary, pal.signal, mix), lerp(pal.primary2, pal.signal, mix)),
- start = Offset(left, top), end = Offset(right, bottom),
- ),
- topLeft = Offset(left, top), size = Size(w, h), cornerRadius = CornerRadius(corner),
- )
+ drawFlood(from, edges.map { it.value }, start, pal.signal, cornerAtRest.toPx())
+ }
+}
+
+/**
+ * The flood from a button at [from] with its edges [v] of the way to the page's (left, top, right,
+ * bottom): the button sinking with the page behind, blobby in flight, its colours [start] giving
+ * way to the flat [signal] in the first half.
+ */
+private fun DrawScope.drawFlood(from: Rect, v: List, start: Pair, signal: Color, cornerAtRest: Float) {
+ val (l, t, r, b) = v
+ val mean = v.sumOf { it.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f
+ // The button sinks with the page behind (FloodBehind), so the flood leaves from where it is now.
+ val k = sinkScale(mean)
+ val cx = size.width / 2f
+ val cy = size.height / 2f
+ val left = lerp(cx + (from.left - cx) * k, 0f, l)
+ val top = lerp(cy + (from.top - cy) * k, 0f, t)
+ val right = lerp(cx + (from.right - cx) * k, size.width, r)
+ val bottom = lerp(cy + (from.bottom - cy) * k, size.height, b)
+ val w = (right - left).coerceAtLeast(0f)
+ val h = (bottom - top).coerceAtLeast(0f)
+ // A button's corners at rest, a blob in flight, square once it fills the page.
+ val blob = sin(PI * mean).toFloat().coerceAtLeast(0f)
+ val corner = lerp(cornerAtRest * (1f - mean), minOf(w, h) * 0.42f, blob)
+ // The button's gradient gives way to the ball's flat blue in the first half.
+ val mix = (mean * 2f).coerceAtMost(1f)
+ val brush = Brush.linearGradient(
+ listOf(lerp(start.first, signal, mix), lerp(start.second, signal, mix)),
+ start = Offset(left, top), end = Offset(right, bottom),
+ )
+ drawRoundRect(brush, topLeft = Offset(left, top), size = Size(w, h), cornerRadius = CornerRadius(corner))
+}
+
+/**
+ * The front end's first frames after a stop: the page in [flood] after a beat, drawn back down
+ * into the button at [to] (root px, measured before the page sank) on critically damped springs,
+ * the far edges first, so it sets down on the button without a bounce. [onProgress] (1 to 0) lets
+ * the page behind rise back. No button to return to: the blue fades. Calls [onLanded] at the end.
+ */
+@Composable
+internal fun FloodReturn(flood: Color, to: Rect?, onProgress: (Float) -> Unit, onLanded: () -> Unit) {
+ val colors = MaterialTheme.colorScheme
+ val pal = LocalPalette.current
+ val edges = remember { List(4) { Animatable(1f) } }
+ val fade = remember { Animatable(1f) }
+ val landed by rememberUpdatedState(onLanded)
+ val progress by rememberUpdatedState(onProgress)
+ var page by remember { mutableStateOf(Size.Zero) }
+ LaunchedEffect(page != Size.Zero) {
+ if (page == Size.Zero) return@LaunchedEffect
+ progress(1f)
+ // A beat of plain blue first, so the change of screen does not read as a cut.
+ delay(Motion.ms(220).toLong())
+ if (to == null || Motion.scale == 0f) {
+ fade.animateTo(0f, tween(Motion.ms(240).coerceAtLeast(1)))
+ } else {
+ val travel = listOf(to.left, to.top, page.width - to.right, page.height - to.bottom).map { it.coerceAtLeast(0f) }
+ val far = travel.max().coerceAtLeast(1f)
+ coroutineScope {
+ edges.mapIndexed { i, edge ->
+ val lead = travel[i] / far
+ launch {
+ delay(Motion.ms((180 * (1f - lead)).toInt()).toLong())
+ edge.animateTo(0f, spring(dampingRatio = 1f, stiffness = lerp(110f, 190f, lead))) {
+ progress(edges.sumOf { it.value.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f)
+ }
+ }
+ }.forEach { it.join() }
+ }
+ }
+ progress(0f)
+ landed()
+ }
+ Canvas(Modifier.fillMaxSize().onSizeChanged { page = Size(it.width.toFloat(), it.height.toFloat()) }.pointerInput(Unit) { awaitEachGesture { while (true) awaitPointerEvent().changes.forEach { it.consume() } } }) {
+ if (to == null) drawRect(flood, alpha = fade.value)
+ else drawFlood(to, edges.map { it.value }, colors.primary to pal.primary2, flood, 12.dp.toPx())
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt
index 66d0c5f525..cbdf0cc788 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt
@@ -16,12 +16,12 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
+import androidx.compose.ui.res.stringResource
+import com.droiddeck.launcher.R
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
-import androidx.compose.ui.res.stringResource
-import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FexPreset
import com.droiddeck.launcher.runtime.DeckyManager
import com.droiddeck.launcher.session.SessionPrefs
@@ -69,6 +69,8 @@ class ModeSettings(
val stretch16x9: Boolean? = null,
/** Steam only: the client branch forced on the command line. */
val steamChannel: String? = null,
+ /** Steam only: enable the SteamOS client interface and its performance controls. */
+ val steamDeckMode: Boolean = false,
/** Steam only: start a Steam session when DroidDeck opens. */
val runSteamAtStartup: Boolean = false,
/** Steam only: the user's chosen Games folders; null outside Steam. */
@@ -125,6 +127,7 @@ class ModeSettingsActions(
val onForceFullscreen: (Boolean) -> Unit = {},
val onStretch16x9: (Boolean) -> Unit = {},
val onSteamChannel: (String) -> Unit = {},
+ val onSteamDeckMode: (Boolean) -> Unit = {},
val onRunSteamAtStartup: (Boolean) -> Unit = {},
val onPickAddedGamesDir: () -> Unit = {},
val onForgetAddedGamesDir: (path: String) -> Unit = {},
@@ -340,6 +343,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
}
}
if (steam && s.steamChannel != null) SettingsGroup("Client") {
+ ToggleRow(
+ host, "steamdeck", "Steam Deck mode",
+ "Enables Steam's Deck interface and Quick Access performance overlay controls. Applies next session.",
+ s.steamDeckMode, onChange = a.onSteamDeckMode,
+ )
ChoiceRow(
host, "channel", "Client branch", "The Steam client build the session forces. Applies at the next session start; the client may update itself once.",
listOf("publicbeta" to "Public beta", "steamdeck_publicbeta" to "Steam Deck public beta"), s.steamChannel,
@@ -351,13 +359,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
for (dir in s.addedGamesDirs) {
val n = s.addedGames.count { it.folderPath.startsWith("$dir/") }
ActionRow(
- dir.substringAfterLast('/').ifEmpty { dir }, dir + " · " + (if (n == 0) "no game folders with a .exe found" else "$n game${if (n == 1) "" else "s"}") + ". Forget: the games leave the client's library at the next session start; nothing on disk is touched.",
+ dir.substringAfterLast('/').ifEmpty { dir }, dir + " · " + (if (n == 0) "no game folders with a .exe found" else "$n game${if (n == 1) "" else "s"}") + ". " + stringResource(R.string.added_games_forget_hint),
"Forget", onClick = { a.onForgetAddedGamesDir(dir) },
)
}
ActionRow(
if (s.addedGamesDirs.isEmpty()) "Games folder" else "Another games folder",
- "Your own Windows games, one subfolder each, anywhere: internal storage, the SD card, a USB drive. As many folders as you like. Each game goes into the client's library as a non-Steam game under the ARM64 Proton, at the next session start.",
+ stringResource(R.string.added_games_import_hint),
"Add…", onClick = a.onPickAddedGamesDir,
)
ToggleRow(
@@ -410,7 +418,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
val open = host.open == "storage"
SettingsRow(
"Second library",
- "Adds a library location in Steam. Applies next session.",
+ stringResource(R.string.second_library_import_hint),
highlighted = open,
) {
androidx.compose.foundation.layout.Box {
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt
index 41b425092a..7756cd72f2 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt
@@ -36,7 +36,6 @@ fun PerformancePage(
zinkLazy: Boolean,
glThread: Boolean,
noGlError: Boolean,
- steamDeckMode: Boolean,
noXalia: Boolean,
prootNoSeccomp: Boolean,
guestHostname: String,
@@ -46,7 +45,6 @@ fun PerformancePage(
onZinkLazy: (Boolean) -> Unit,
onGlThread: (Boolean) -> Unit,
onNoGlError: (Boolean) -> Unit,
- onSteamDeckMode: (Boolean) -> Unit,
onNoXalia: (Boolean) -> Unit,
onProotNoSeccomp: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
@@ -96,11 +94,6 @@ fun PerformancePage(
"Disables per-call GL validation.",
noGlError, onChange = onNoGlError,
)
- ToggleRow(
- host, "deck", "Steam Deck mode",
- "Runs the client with -droiddeck. SteamOS helpers and battery info are provided.",
- steamDeckMode, onChange = onSteamDeckMode,
- )
}
SettingsGroup("Session fixes") {
ToggleRow(
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt
index 36d8803655..cae45fa485 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt
@@ -1,64 +1,96 @@
package com.droiddeck.launcher.ui
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities
+import android.os.Build
import androidx.activity.compose.BackHandler
+import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
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.padding
+import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
-import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.produceState
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.core.PhantomProcessLimit
import com.droiddeck.launcher.core.PhantomProcessStatus
+import com.droiddeck.launcher.core.WirelessAdbPairingService
+import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
@Composable
fun PhantomProcessGatePage(
status: PhantomProcessStatus,
onDismiss: () -> Unit,
onOpenDeveloperOptions: () -> Unit,
- onSetUpWirelessAdb: () -> Unit,
+ onFixWithWirelessDebugging: () -> Unit,
+ onEnterAddressManually: () -> Unit,
+ onCopyCommand: () -> Unit,
+ onOpenNotificationSettings: () -> Unit,
) {
BackHandler(onBack = onDismiss)
+ val context = LocalContext.current
+ val stage by WirelessAdbPairingService.stage.collectAsState()
+ val environment by produceState(GateEnvironment.read(context)) {
+ while (true) {
+ value = GateEnvironment.read(context)
+ kotlinx.coroutines.delay(2_000)
+ }
+ }
+ val hasToggle = PhantomProcessLimit.hasDeveloperToggle()
BoxWithConstraints(Modifier.fillMaxWidth()) {
val compact = maxWidth < 620.dp && maxHeight < 500.dp
SettingsPage(
host = rememberMenuHost(),
- title = if (compact) "Steam paused" else "Steam cannot start yet",
+ title = "One Android setting to change",
eyebrow = "Steam",
- lede = if (compact) compactStatus(status) else "${PhantomProcessLimit.title(status)} · checking again every two seconds",
+ lede = if (compact) null else "Android stops apps that start lots of background processes, and Steam starts dozens. " +
+ "Until this is changed, games close with no error.",
onBack = onDismiss,
- // Scrolls, so the larger text never pushes the ADB command off a short screen.
scrollContent = true,
compactLayout = compact,
) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 620.dp
- Column(
- modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
- verticalArrangement = Arrangement.spacedBy(2.dp),
- ) {
- when {
- compact -> CompactGateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
- wide -> Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxWidth()) {
- Column(Modifier.weight(1f)) {
- GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
- }
- Column(Modifier.weight(1f)) { AdbFallback() }
- }
- else -> {
- GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
- AdbFallback()
- }
+ val fix: @Composable ColumnScope.() -> Unit = {
+ FixGroup(hasToggle, stage, environment, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging,
+ onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) })
+ }
+ val side: @Composable ColumnScope.() -> Unit = {
+ StatusGroup(status, compact)
+ OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onEnterAddressManually, onCopyCommand)
+ }
+ if (wide) {
+ Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth()) {
+ Column(Modifier.weight(1.2f), content = fix)
+ Column(Modifier.weight(1f), content = side)
+ }
+ } else {
+ Column(Modifier.widthIn(max = 600.dp).fillMaxWidth()) {
+ fix()
+ side()
}
}
}
@@ -66,97 +98,168 @@ fun PhantomProcessGatePage(
}
}
-private fun compactStatus(status: PhantomProcessStatus): String {
- val state = when (status) {
- PhantomProcessStatus.ENABLED -> "Child-process limit is on"
- PhantomProcessStatus.UNSET -> "Child-process limit is unset"
- PhantomProcessStatus.UNREADABLE -> "Child-process limit is unreadable"
- else -> PhantomProcessLimit.title(status)
+private data class GateEnvironment(val onWifi: Boolean, val notifications: Boolean) {
+ companion object {
+ fun read(context: Context): GateEnvironment {
+ val connectivity = context.getSystemService(ConnectivityManager::class.java)
+ val wifi = runCatching {
+ connectivity?.getNetworkCapabilities(connectivity.activeNetwork)
+ ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true
+ }.getOrDefault(true)
+ return GateEnvironment(wifi, WirelessAdbPairingService.notificationsEnabled(context))
+ }
}
- return "$state · retrying every 2 sec"
}
@Composable
-private fun CompactGateInstructions(
- status: PhantomProcessStatus,
+private fun FixGroup(
+ hasToggle: Boolean,
+ stage: Stage,
+ environment: GateEnvironment,
+ compact: Boolean,
onOpenDeveloperOptions: () -> Unit,
- onSetUpWirelessAdb: () -> Unit,
+ onFixWithWirelessDebugging: () -> Unit,
+ onOpenNotificationSettings: () -> Unit,
+ onCancel: () -> Unit,
) {
- SettingsGroup("1 · Developer options", compact = true) {
+ val pairing = stage is Stage.Waiting || stage is Stage.CodeNeeded || stage is Stage.Working
+ SettingsGroup(if (hasToggle) "Developer options" else "Fix it for me", compact = compact) {
Column(
- modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 7.dp),
- verticalArrangement = Arrangement.spacedBy(5.dp),
+ modifier = Modifier.fillMaxWidth().padding(if (compact) 10.dp else 14.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp),
) {
- Text(
- PhantomProcessLimit.gateInstructions(status),
- style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp),
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- )
- Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
- PrimaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions)
- SecondaryButton("Use Wireless debugging", compact = true, onClick = onSetUpWirelessAdb)
+ when {
+ pairing -> PairingProgress(stage, onCancel)
+ hasToggle -> {
+ Body("Turn on “Disable child process restrictions”, then come back. Keep Developer options on afterwards: turning them off turns the switch back off.")
+ PrimaryButton("Open Developer options", compact = compact, onClick = onOpenDeveloperOptions)
+ }
+ else -> {
+ Body("This Android version has no switch for it, so DroidDeck changes it over Wireless debugging on this device. About a minute, no computer needed.")
+ (stage as? Stage.Failed)?.let { Body(it.error, error = true) }
+ PrimaryButton(
+ if (stage is Stage.Failed) "Try again" else "Fix it for me",
+ compact = compact,
+ enabled = environment.onWifi && environment.notifications,
+ onClick = onFixWithWirelessDebugging,
+ )
+ }
+ }
+ if (!hasToggle && !pairing) {
+ if (!environment.onWifi) {
+ Body("Wireless debugging needs Wi-Fi. Connect to any network first; it doesn't need internet.", warn = true)
+ }
+ if (!environment.notifications) {
+ Body("The pairing code is entered in a notification. Allow notifications for DroidDeck, or use Other ways.", warn = true)
+ SecondaryButton("Allow notifications", compact = compact, onClick = onOpenNotificationSettings)
+ }
}
}
}
- SettingsGroup("3 · Computer ADB last resort", compact = true) {
- Column(
- modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp),
- verticalArrangement = Arrangement.spacedBy(3.dp),
- ) {
- Text(
- "If the setting is missing and Wireless debugging is unavailable, run this from a computer:",
- style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp),
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- )
- Text(
- PhantomProcessLimit.ADB_COMMAND,
- style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp),
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- )
+}
+
+@Composable
+private fun PairingProgress(stage: Stage, onCancel: () -> Unit) {
+ val steps = listOf(
+ "Open Settings → Developer options → Wireless debugging and turn it on",
+ "Tap “Pair device with pairing code”",
+ "Type the code into the DroidDeck notification",
+ )
+ val active = when (stage) {
+ Stage.Waiting -> 1
+ is Stage.CodeNeeded -> 2
+ else -> 3
+ }
+ steps.forEachIndexed { index, step ->
+ val done = index < active
+ val current = index == active
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(if (done) "✓" else "${index + 1}", fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
+ color = if (done) LocalPalette.current.good else MaterialTheme.colorScheme.onSurfaceVariant)
+ Text(step, style = MaterialTheme.typography.bodySmall,
+ color = if (current) MaterialTheme.colorScheme.onBackground else MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ }
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
+ Text(
+ when (stage) {
+ Stage.Waiting -> "Waiting for the pairing pop-up…"
+ is Stage.CodeNeeded -> stage.error ?: "Pop-up found. Enter its code in the notification."
+ is Stage.Working -> stage.step
+ else -> ""
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = if (stage is Stage.CodeNeeded && stage.error != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.weight(1f),
+ )
+ SecondaryButton("Cancel", compact = true, onClick = onCancel)
+ }
+}
+
+@Composable
+private fun StatusGroup(status: PhantomProcessStatus, compact: Boolean) {
+ SettingsGroup("Status", compact = compact) {
+ Column(Modifier.fillMaxWidth().padding(if (compact) 10.dp else 14.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(PhantomProcessLimit.title(status), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onBackground)
+ Body("Checking every 2 seconds. This page closes when it's off.")
}
}
}
@Composable
-private fun GateInstructions(
- status: PhantomProcessStatus,
+private fun OtherWays(
+ hasToggle: Boolean,
+ compact: Boolean,
onOpenDeveloperOptions: () -> Unit,
- onSetUpWirelessAdb: () -> Unit,
+ onFixWithWirelessDebugging: () -> Unit,
+ onEnterAddressManually: () -> Unit,
+ onCopyCommand: () -> Unit,
) {
- SettingsGroup("1 · Developer options first") {
- Column(
- modifier = Modifier.fillMaxWidth().padding(14.dp),
+ var open by rememberSaveable { mutableStateOf(false) }
+ SettingsGroup("Other ways", compact = compact) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().clickable { open = !open }.padding(horizontal = 14.dp, vertical = 10.dp),
+ ) {
+ Body(if (hasToggle) "Wireless debugging, manual address, computer ADB" else "Manual address, computer ADB, Developer options", modifier = Modifier.weight(1f))
+ Text(if (open) "▴" else "▾", fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ if (open) Column(
+ modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 14.dp, bottom = 14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
+ if (hasToggle) {
+ SecondaryButton("Use Wireless debugging instead", compact = true, onClick = onFixWithWirelessDebugging)
+ } else {
+ Body("Some ROMs add the switch anyway. Look for “child process” in Developer options.")
+ SecondaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions)
+ }
+ Body("If the notification doesn't work, enter the pop-up's address and code yourself.")
+ SecondaryButton("Enter address manually", compact = true, onClick = onEnterAddressManually)
+ Body("From a computer with ADB:")
Text(
- PhantomProcessLimit.gateInstructions(status),
+ PhantomProcessLimit.adbCommand(),
+ style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
- PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions)
- SecondaryButton("Use Wireless debugging", onClick = onSetUpWirelessAdb)
+ SecondaryButton("Copy command", compact = true, onClick = onCopyCommand)
}
}
}
@Composable
-private fun AdbFallback() {
- SettingsGroup("3 · Computer ADB last resort") {
- Column(
- modifier = Modifier.fillMaxWidth().padding(14.dp),
- verticalArrangement = Arrangement.spacedBy(8.dp),
- ) {
- Text(
- "Use this only if Developer options has no setting and Wireless debugging is unavailable. Connect this device to a computer with ADB and run:",
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- style = MaterialTheme.typography.bodySmall,
- )
- Text(
- PhantomProcessLimit.ADB_COMMAND,
- style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- )
- }
- }
+private fun Body(text: String, modifier: Modifier = Modifier, error: Boolean = false, warn: Boolean = false) {
+ Text(
+ text,
+ modifier = modifier,
+ style = MaterialTheme.typography.bodySmall,
+ color = when {
+ error -> MaterialTheme.colorScheme.error
+ warn -> androidx.compose.ui.graphics.Color(0xFFFFB86B)
+ else -> MaterialTheme.colorScheme.onSurfaceVariant
+ },
+ )
}
@Composable
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt
index 70581f5b03..d853906a82 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt
@@ -85,6 +85,9 @@ import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.InputMode
import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.LocalFocusManager
+import androidx.compose.ui.platform.LocalView
+import androidx.compose.ui.layout.boundsInWindow
+import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
@@ -172,6 +175,8 @@ class DrawerActions(
val onBackground: () -> Unit,
val onShareLogs: () -> Unit,
val onStop: () -> Unit,
+ /** Stop with the dialog's button's bounds on screen, for the flood to grow out of; null falls back to [onStop]. */
+ val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null,
val onClose: () -> Unit,
/** Components tab: every Proton with what it uses; null until first read. */
val components: ComponentsManager.Snapshot? = null,
@@ -453,7 +458,14 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
if (confirmStop) {
val cancelFocus = remember { FocusRequester() }
val cancel = { confirmStop = false }
- val stop = { confirmStop = false; a.onStop() }
+ // Where Stop sits on screen: the dialog is a window of its own, so its bounds are taken
+ // against the screen and the session's overlay converts them back.
+ var stopOnScreen by remember { mutableStateOf(null) }
+ val stop = {
+ confirmStop = false
+ val from = a.onStopFrom
+ if (from != null) from(stopOnScreen) else a.onStop()
+ }
LaunchedEffect(controllerActive) {
if (controllerActive) {
androidx.compose.runtime.withFrameNanos { }
@@ -465,9 +477,13 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha
modifier = Modifier.controllerBack(onBack = cancel),
title = { Text("Stop session?") },
confirmButton = {
+ val dialogView = LocalView.current
TextButton(
onClick = stop,
- modifier = Modifier.controllerConfirm(onClick = stop),
+ modifier = Modifier.controllerConfirm(onClick = stop).onGloballyPositioned { c ->
+ val at = IntArray(2).also { dialogView.rootView.getLocationOnScreen(it) }
+ stopOnScreen = c.boundsInWindow().translate(at[0].toFloat(), at[1].toFloat())
+ },
colors = ButtonDefaults.textButtonColors(contentColor = colors.error),
) { Text("Stop") }
},
diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java
index 7b77178697..dd29b6ad11 100644
--- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java
+++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java
@@ -67,9 +67,30 @@ public final class WaylandCompositor {
if (l != null) l.onGameSurface(window, gpuName);
}
+ private static volatile long lastFrameNanos;
+ private static volatile long frameIntervalNanos;
+
+ /**
+ * How long frames are taking to arrive right now, in ms, or -1 before the first: the smoothed
+ * interval, or the time since the last frame when that is longer (a session that has stalled).
+ */
+ public static long recentFrameIntervalMs() {
+ long last = lastFrameNanos;
+ if (last == 0) return -1;
+ return Math.max(frameIntervalNanos, System.nanoTime() - last) / 1_000_000;
+ }
+
/** Invoked from native (banner_on_game_frame) for every frame of the HUD's window. */
@SuppressWarnings("unused")
static void onGameFrame() {
+ long now = System.nanoTime();
+ long previous = lastFrameNanos;
+ lastFrameNanos = now;
+ if (previous != 0) {
+ long interval = now - previous;
+ long smoothed = frameIntervalNanos;
+ frameIntervalNanos = smoothed == 0 ? interval : (smoothed * 3 + interval) / 4;
+ }
com.droiddeck.launcher.session.PerfHints.onFrame();
GameListener l = gameListener;
if (l != null) l.onGameFrame();
diff --git a/app/src/main/res/drawable/ic_stat_session.xml b/app/src/main/res/drawable/ic_stat_session.xml
index 3b3415de2b..0efa80f6cf 100644
--- a/app/src/main/res/drawable/ic_stat_session.xml
+++ b/app/src/main/res/drawable/ic_stat_session.xml
@@ -1,11 +1,8 @@
-
-
+ android:viewportWidth="239.92" android:viewportHeight="239.92">
+
+
+
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index a0519dce57..10cf334af2 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -19,6 +19,9 @@
Resume
Stop session
Frame generation
+ Choose Windows games with one subfolder per game. Steam checks ownership while signed in. Confirmed games use their Steam library entries after restarting Steam; other games stay as non-Steam shortcuts. Steam may verify or download files for imported games.
+ Adds a Steam library and scans Windows game folders here and in steamapps/common. After the ownership check and a Steam restart, owned games use Steam entries; other games use non-Steam shortcuts.
+ Forget removes non-Steam shortcuts next session. Manage Steam installations in Steam. Files stay on disk.
Game environment
Shared defaults and per-game overrides for games using Proton. Applies on the next game launch.
Edit variables
diff --git a/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt b/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt
index a7cfc80a92..e930f85e51 100644
--- a/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/core/PhantomProcessLimitTest.kt
@@ -1,6 +1,8 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
import org.junit.Test
class PhantomProcessLimitTest {
@@ -26,4 +28,33 @@ class PhantomProcessLimitTest {
assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status(null, null))
assertEquals(PhantomProcessStatus.UNSET, PhantomProcessLimit.status("", ""))
}
+
+ @Test
+ fun android12UsesDeviceConfig() {
+ assertEquals(
+ listOf(
+ "device_config set_sync_disabled_for_tests persistent",
+ "device_config put activity_manager max_phantom_processes 2147483647",
+ ),
+ PhantomProcessLimit.shellCommands(enabled = false, sdk = 31),
+ )
+ assertTrue(PhantomProcessLimit.verified("2147483647\n", enabled = false, sdk = 31))
+ assertFalse(PhantomProcessLimit.verified("null", enabled = false, sdk = 31))
+ }
+
+ @Test
+ fun android12LAndLaterUseTheFlag() {
+ assertEquals(
+ listOf("settings put global settings_enable_monitor_phantom_procs false"),
+ PhantomProcessLimit.shellCommands(enabled = false, sdk = 33),
+ )
+ assertTrue(PhantomProcessLimit.verified("false", enabled = false, sdk = 34))
+ assertFalse(PhantomProcessLimit.verified("null", enabled = false, sdk = 33))
+ }
+
+ @Test
+ fun developerToggleStartsAtAndroid14() {
+ assertFalse(PhantomProcessLimit.hasDeveloperToggle(33))
+ assertTrue(PhantomProcessLimit.hasDeveloperToggle(34))
+ }
}
diff --git a/docs/development/steam-game-imports.md b/docs/development/steam-game-imports.md
new file mode 100644
index 0000000000..4639afa5bd
--- /dev/null
+++ b/docs/development/steam-game-imports.md
@@ -0,0 +1,62 @@
+# Steam game imports
+
+Second Library still registers the selected Steam library. It now also scans Windows
+executables in its immediate game subfolders and `steamapps/common`, using the same
+importer as Added Games. Existing Steam manifests are preserved.
+
+`bannerlator-steam-games watch` runs beside the client. It identifies a game by an
+existing manifest's install directory, a `steam_appid.txt` beside the game or selected
+executable, or a unique normalized title from Steam's store search with an explicit
+country. Matching also accepts the terminal Windows Edition and INTERGRADE suffixes;
+multiple matches still remain unresolved. Artwork's fuzzy matching is deliberately not
+used for identity. Ambiguous or unresolved titles remain non-Steam games.
+
+Ownership comes from the running native ARM64 client's `BIsSubscribedApp`, through
+versioned SteamClient020 / SteamUser021 / STEAMAPPS_INTERFACE_VERSION008 interfaces. The
+helper gets the account from that connection, not from a public profile. No API key,
+password, profile visibility change, or CEF debugging port is needed. Each probe runs in
+a bounded subprocess so library failures cannot crash the importer or client.
+
+The resulting snapshot is stored under that account's `userdata//config` and
+refreshed every 30 seconds while logged in. Title lookups retry every five minutes and
+when the source changes, so an early network failure does not end the watcher. Changed
+status and probe failures are written to the session log. Startup and post-exit import
+use the last successful snapshot for the selected account. A newly identified title
+therefore starts as a shortcut and becomes a Steam entry after Steam exits and starts
+again. An unavailable client or offline first launch falls back to shortcuts; existing
+snapshots remain usable offline. Steam still enforces the current license at launch.
+
+For a confirmed game without a manifest, the importer links the source folder into the
+internal Steam library and writes an installed manifest with `Universe=1` and
+`StateFlags=4`. Steam ignores manifests without the universe field. This registers
+existing files; it does not assert a verified build ID or depot manifest. Steam can
+still require verification, updates or redistributables. Steam updates and uninstall
+operate on the linked game files, so imported folders must be writable. Existing Steam
+manifests and directories are preserved. Only the exact minimal manifests generated by
+the earlier importer are migrated, with the matching source symlink still present. If
+registration fails, the game remains a shortcut. Once Steam takes over an install,
+manage it in Steam; forgetting an Added Games folder only removes its shortcuts.
+
+The account's `.droiddeck-routes.json` maps shortcut IDs to real Steam app IDs so the
+Android launcher uses the same title and Proton prefix as Steam. Other accounts do not
+inherit those routes. Managed shortcuts are replaced; user-created shortcuts and
+unreadable shortcut files are preserved. Both routes use the existing ARM64 Proton
+registration.
+
+## Validation
+
+Run `python3 -m unittest discover -s tools/tests -p 'test_*.py'` and Android unit tests.
+Tests cover identity and edition matching, network recovery, account isolation,
+owned/unowned/unknown routing, legacy manifest migration, manifest preservation,
+filesystem collisions, shortcut preservation, and the versioned IPC call/cleanup
+contract. On 2026-09-28, the ARM64 Steam client (1790545198) confirmed ownership and
+installed status through ISteamApps for Final Fantasy VII Rebirth (2909400), Final
+Fantasy VII Remake Intergrade (1462040), and Final Fantasy XV (637650), with all three
+install paths resolving to the original second-library folders. The old managed
+shortcuts were removed. This verifies library registration, not complete game launches.
+Unowned fallback and account isolation are covered by automated tests.
+
+References: [Steam Apps
+API](https://partner.steamgames.com/doc/api/ISteamApps#BIsSubscribedApp), [Valve's
+versioned interfaces](https://github.com/ValveSoftware/Proton/tree/proton_11.0/lsteamcli
+ent/steamworks_sdk_154).
diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session
index ab1f6f5684..d50029b0ef 100755
--- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session
+++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session
@@ -510,20 +510,19 @@ BUSCONF
# desktop's launchers ask for; gamescope shows one window at a time and the game takes over.
_bl_ui=(-gamepadui)
[ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=()
- # Deck mode (BL_STEAMDECK=1, the Performance page): -steamdeck is the flag that puts the Quick
- # Access Menu, the performance overlay and the Deck settings pages on screen. Only -steamdeck,
- # never -steamos3: that one makes the client manage itself as SteamOS does - it calls
- # steamos-select-branch and opts the install into the steamdeck_stable client branch, writes
- # that to package/beta, and from then on the branch on disk loses to the -clientbeta below on
- # every launch; the updater finds "installed version 0", marks an update pending and exits 42
- # to apply it, which never happens, so the client restarts for ever - under a running game,
- # taking Steam Input with it each time. (Bannerlator 38996ea1, on device.) The SteamOS helpers
- # the client calls in this mode are staged as no-op stubs under /usr/bin.
+ # Deck mode (BL_STEAMDECK=1, the Steam page's Client settings): -steamdeck is the flag that puts
+ # the Quick Access Menu and the Deck settings pages on screen; the QAM's performance overlay
+ # controls stay greyed out without -steamos3, as SteamOS and Armada launch it. -steamos3 makes
+ # the client manage itself as SteamOS does - it calls steamos-select-branch and writes
+ # steamdeck_stable to package/beta, and a branch on disk that loses to the -clientbeta below
+ # is an update that never installs: exit 42, a restart, for ever (Bannerlator 38996ea1). The
+ # loop below puts package/beta back before every start. The SteamOS helpers the client calls
+ # in this mode are staged as no-op stubs under /usr/bin.
if [ "${BL_STEAMDECK:-0}" = 1 ] && [ "${BL_STEAM_UI:-}" != desktop ]; then
- _bl_ui+=(-steamdeck)
+ _bl_ui+=(-steamdeck -steamos3)
# The QAM's Scaling Filter lists NVIDIA Image Scaling only when told gamescope has it (it does).
export STEAM_GAMESCOPE_NIS_SUPPORTED=1
- echo "== steam: Deck mode on (-steamdeck)"
+ echo "== steam: Deck mode on (-steamdeck -steamos3)"
fi
# What a killed session leaves behind. Android ends sessions without warning (backgrounding, the
# low-memory killer), and the client then finds .crash - opening its update UI on the spinner -
@@ -548,10 +547,31 @@ BUSCONF
# again on the branch it just wrote.
steam_channel=${BL_STEAM_CHANNEL:-publicbeta}
steam_beta=$steam_root/package/beta
+ if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
+ bannerlator-steam-games watch "$steam_root" "$BL_ADDED_GAMES" &
+ games_watcher=$!
+ fi
echo "== steam args: ${_bl_ui[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan $*"
# An update that cannot install asks for a restart (rc=42) every time; the count is capped so a
# session can never again loop in silence, which reads as a menu opening and closing by itself.
steam_updates=0
+ rm -f "$HOME/.bl-stop-requested"
+ if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -d "$BL_LAUNCH_DIR" ]; then
+ rm -f "$BL_LAUNCH_DIR/steam-stop"
+ (
+ while :; do
+ if [ -e "$BL_LAUNCH_DIR/steam-stop" ]; then
+ rm -f "$BL_LAUNCH_DIR/steam-stop"
+ : > "$HOME/.bl-stop-requested"
+ echo "== steam: the app asked for a clean exit"
+ "$steam_root/steamrtarm64/steam" -shutdown >/dev/null 2>&1 || true
+ exit 0
+ fi
+ sleep 0.5
+ done
+ ) &
+ stop_watcher=$!
+ fi
while :; do
rm -f "$HOME/.bl-restart-once"
if [ -f "$steam_beta" ] && [ "$(cat "$steam_beta" 2>/dev/null)" != "$steam_channel" ]; then
@@ -565,6 +585,13 @@ BUSCONF
rc=$?
echo "== steam exited rc=$rc"
collect_steam_logs
+ if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
+ bannerlator-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
+ fi
+ if [ -f "$HOME/.bl-stop-requested" ]; then
+ rm -f "$HOME/.bl-stop-requested" "$HOME/.bl-restart-once"
+ break
+ fi
# The session asked for this exit (the ARM64 Proton landed): start again, without the URL
# arguments, which were acted on. Not counted against the update cap.
if [ -f "$HOME/.bl-restart-once" ]; then
@@ -581,6 +608,14 @@ BUSCONF
# The URL arguments were acted on the first time; a restart must not repeat them.
set --
done
+ if [ -n "${stop_watcher:-}" ]; then
+ kill "$stop_watcher" 2>/dev/null || true
+ wait "$stop_watcher" 2>/dev/null || true
+ fi
+ if [ -n "${games_watcher:-}" ]; then
+ kill "$games_watcher" 2>/dev/null || true
+ wait "$games_watcher" 2>/dev/null || true
+ fi
if [ -n "${BL_DESKTOP:-}" ]; then
# Started from the desktop (bannerlator-steam-launch): the desktop's own programs share this
# script's parent, so reap_orphans - right under gamescope, where everything is the client's -
diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-games b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-games
new file mode 100755
index 0000000000..1e6f2a1fd5
--- /dev/null
+++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-games
@@ -0,0 +1,254 @@
+#!/usr/bin/env python3
+"""Resolve added games against the signed-in Steam client's licenses."""
+import ctypes as C
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import time
+import unicodedata
+import urllib.parse
+import urllib.request
+
+STATE = ".droiddeck-games.json"
+BASE_ID = 76561197960265728
+
+
+def read_json(path, default):
+ try:
+ return json.loads(Path(path).read_text())
+ except (OSError, ValueError):
+ return default
+
+
+def save_json(path, value):
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temp = path.with_suffix(".tmp")
+ temp.write_text(json.dumps(value))
+ os.replace(temp, path)
+
+
+def title_key(name):
+ return "".join(c for c in unicodedata.normalize("NFKC", name.replace("™", "").replace("®", "")).casefold() if c.isalnum())
+
+
+def edition_key(name):
+ name = re.sub(r"(?i)\s+(?:windows edition|intergrade)\s*$", "", name)
+ return title_key(name)
+
+
+def source_stamp(game):
+ try:
+ exe = Path(game["exe"])
+ stat = exe.stat()
+ hints = []
+ for parent in sorted({Path(game["folder"]), exe.parent}):
+ hint = parent / "steam_appid.txt"
+ hints.append(hint.read_text().strip() if hint.is_file() else "")
+ return [game["name"], str(exe), stat.st_size, stat.st_mtime_ns, hints]
+ except (OSError, ValueError):
+ return None
+
+
+def identify(game):
+ folder = Path(game["folder"])
+ steamapps = folder.parent.parent
+ if folder.parent.name == "common" and steamapps.name == "steamapps":
+ matches = []
+ for manifest in steamapps.glob("appmanifest_*.acf"):
+ try:
+ text = manifest.read_text()
+ install = re.search(r'"installdir"\s*"([^"\\]*)"', text, re.I)
+ if install and install[1] == folder.name:
+ matches.append(int(manifest.stem.removeprefix("appmanifest_")))
+ except (OSError, ValueError):
+ pass
+ if matches:
+ return matches[0] if len(matches) == 1 else None
+ ids = set()
+ for parent in {folder, Path(game["exe"]).parent}:
+ try:
+ appid = int((parent / "steam_appid.txt").read_text().strip())
+ if 0 < appid < 0x80000000:
+ ids.add(appid)
+ except (OSError, ValueError):
+ pass
+ if ids:
+ return next(iter(ids)) if len(ids) == 1 else None
+ url = "https://store.steampowered.com/api/storesearch/?l=english&cc=US&term=" + urllib.parse.quote(game["name"])
+ try:
+ with urllib.request.urlopen(url, timeout=5) as response:
+ items = json.loads(response.read(1024 * 1024)).get("items", [])
+ for key in (title_key, edition_key):
+ ids = {int(item["id"]) for item in items
+ if key(item.get("name", "")) == key(game["name"]) and key(game["name"])}
+ if ids:
+ return next(iter(ids)) if len(ids) == 1 else None
+ return None
+ except (OSError, ValueError, KeyError):
+ return None
+
+
+def method(obj, slot, result, *args):
+ if not obj:
+ raise RuntimeError("Steam interface unavailable")
+ table = C.cast(obj, C.POINTER(C.POINTER(C.c_void_p))).contents
+ return C.CFUNCTYPE(result, C.c_void_p, *args)(table[slot])
+
+
+def probe(steam_root, ids):
+ # Slots belong to Valve's SteamClient020, SteamUser021 and STEAMAPPS_INTERFACE_VERSION008.
+ library = C.CDLL(str(Path(steam_root) / "steamrtarm64/steamclient.so"))
+ library.CreateInterface.argtypes = [C.c_char_p, C.c_void_p]
+ library.CreateInterface.restype = C.c_void_p
+ client = library.CreateInterface(b"SteamClient020", None)
+ pipe = method(client, 0, C.c_int)(client)
+ if not pipe:
+ raise RuntimeError("Steam pipe unavailable")
+ user = 0
+ try:
+ user = method(client, 2, C.c_int, C.c_int)(client, pipe)
+ if not user:
+ raise RuntimeError("No signed-in Steam user")
+ get_interface = lambda slot, version: method(client, slot, C.c_void_p, C.c_int, C.c_int, C.c_char_p)(client, user, pipe, version)
+ account = get_interface(5, b"SteamUser021")
+ if not method(account, 1, C.c_bool)(account):
+ raise RuntimeError("Steam is offline")
+ steamid = method(account, 2, C.c_uint64)(account)
+ apps = get_interface(15, b"STEAMAPPS_INTERFACE_VERSION008")
+ subscribed = method(apps, 6, C.c_bool, C.c_uint32)
+ return {"account": str(steamid - BASE_ID), "checked": time.time(),
+ "owned": {str(appid): bool(subscribed(apps, appid)) for appid in ids}}
+ finally:
+ if user:
+ method(client, 4, None, C.c_int, C.c_int)(client, pipe, user)
+ method(client, 1, C.c_bool, C.c_int)(client, pipe)
+
+
+def watch(steam_root, listing):
+ games = read_json(listing, [])
+ if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games:
+ return
+ candidates, sources = {}, {}
+ next_lookup = 0
+ last_status = None
+ while True:
+ now = time.monotonic()
+ for game in games:
+ folder = game["folder"]
+ stamp = source_stamp(game)
+ if now >= next_lookup or stamp != sources.get(folder):
+ sources[folder] = stamp
+ appid = identify(game)
+ if appid:
+ candidates[folder] = appid
+ else:
+ candidates.pop(folder, None)
+ if now >= next_lookup:
+ next_lookup = now + 300
+ status = "waiting for a matching Steam title"
+ if candidates:
+ try:
+ result = subprocess.run([sys.executable, __file__, "probe", steam_root,
+ *map(str, sorted(set(candidates.values())))],
+ capture_output=True, text=True, timeout=15)
+ if result.returncode != 0:
+ status = "ownership probe failed: " + (result.stderr.strip()[-300:] or str(result.returncode))
+ else:
+ line = next(line for line in result.stdout.splitlines() if line.startswith("DROIDDECK_OWNERSHIP="))
+ snapshot = json.loads(line.removeprefix("DROIDDECK_OWNERSHIP="))
+ if not snapshot["account"].isdigit() or int(snapshot["account"]) <= 0:
+ raise ValueError("invalid Steam account")
+ snapshot["candidates"] = candidates
+ snapshot["sources"] = sources
+ save_json(Path(steam_root) / "userdata" / snapshot["account"] / "config" / STATE, snapshot)
+ status = "matched %d/%d games; %d owned" % (len(candidates), len(games), sum(snapshot["owned"].values()))
+ except (OSError, ValueError, KeyError, StopIteration, subprocess.TimeoutExpired) as error:
+ status = "ownership check unavailable: " + str(error)
+ if status != last_status:
+ print("bannerlator-steam-games: " + status, flush=True)
+ last_status = status
+ time.sleep(30)
+
+
+def seed_install(steam_root, game, appid):
+ steamapps = Path(steam_root) / "steamapps"
+ common = steamapps / "common"
+ name = f"DroidDeck-{appid}"
+ target = common / name
+ source = Path(game["folder"])
+ title = game["name"].replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ")
+ content = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n'
+ + f' "StateFlags" "4"\n "installdir" "{name}"\n' + '}\n')
+ legacy = content.replace(' "Universe" "1"\n', '')
+ manifest = steamapps / f"appmanifest_{appid}.acf"
+ for root in [Path(steam_root), Path("/mnt/bannerlator-sd")]:
+ existing = root / "steamapps" / manifest.name
+ if existing.is_file():
+ if (existing == manifest and source.is_dir() and target.is_symlink()
+ and os.readlink(target) == str(source)
+ and existing.read_text() in (legacy, legacy.replace('"StateFlags" "4"', '"StateFlags" "2"'))):
+ temp = manifest.with_suffix(".droiddeck")
+ temp.write_text(content)
+ os.replace(temp, manifest)
+ return True
+ if not source.is_dir():
+ return False
+ common.mkdir(parents=True, exist_ok=True)
+ if os.path.lexists(target):
+ if not target.is_symlink() or os.readlink(target) != str(source):
+ return False
+ else:
+ target.symlink_to(source, target_is_directory=True)
+ try:
+ with manifest.open("x") as output:
+ output.write(content)
+ except FileExistsError:
+ pass
+ return True
+
+
+def route(steam_root, acct, games):
+ snapshot = read_json(Path(acct) / "config" / STATE, {})
+ if not isinstance(snapshot, dict):
+ snapshot = {}
+ owned = snapshot.get("owned", {}) if snapshot.get("account") == Path(acct).name else {}
+ candidates = snapshot.get("candidates", {})
+ sources = snapshot.get("sources", {})
+ if not all(isinstance(value, dict) for value in (owned, candidates, sources)):
+ owned, candidates, sources = {}, {}, {}
+ shortcuts, routes = [], {}
+ for game in games:
+ appid = candidates.get(game.get("folder"))
+ stamp = source_stamp(game)
+ confirmed = (isinstance(appid, int) and 0 < appid < 0x80000000
+ and owned.get(str(appid)) is True and stamp is not None
+ and sources.get(game.get("folder")) == stamp)
+ if confirmed:
+ try:
+ if seed_install(steam_root, game, appid):
+ routes[str(game["appid"])] = appid
+ continue
+ except OSError as error:
+ print(f"bannerlator-steam-games: import unavailable ({error})")
+ shortcuts.append(game)
+ save_json(Path(acct) / "config/.droiddeck-routes.json", routes)
+ return shortcuts, routes
+
+
+if __name__ == "__main__":
+ if len(sys.argv) < 4:
+ sys.exit(2)
+ try:
+ if sys.argv[1] == "probe":
+ print("DROIDDECK_OWNERSHIP=" + json.dumps(probe(sys.argv[2], [int(value) for value in sys.argv[3:]])), flush=True)
+ elif sys.argv[1] == "watch":
+ watch(sys.argv[2], sys.argv[3])
+ else:
+ sys.exit(2)
+ except (OSError, RuntimeError, ValueError) as error:
+ print(str(error), file=sys.stderr)
+ sys.exit(1)
diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts
index 7f76069120..c3fcd4ae33 100755
--- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts
+++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts
@@ -1,15 +1,7 @@
#!/usr/bin/env python3
-"""Puts the app's added games (Windows games in the user's own folders) into the Steam client's
-library as non-Steam shortcuts, each mapped to the ARM64 Proton, before the client starts.
+"""Import added games while Steam is closed, preserving user-created shortcuts.
- bannerlator-steam-shortcuts
-
-The JSON is a list the app writes each session: {"name", "exe", "dir", "appid"} with guest paths.
-The client keeps non-Steam games in userdata//config/shortcuts.vdf, a binary VDF it
-reads at start-up and rewrites at exit, so this runs while it is down. Entries the app wrote
-carry the tag "droiddeck-app" and are replaced wholesale; anything the user added inside the
-client is kept as it is. The appid is the one the client itself derives (crc32 of exe+name with
-the top bit set), so the launch URL the app uses matches what the client shows.
+Usage: bannerlator-steam-shortcuts
"""
import importlib.machinery
import importlib.util
@@ -207,8 +199,15 @@ def main():
try:
with open(path, "rb") as f:
existing = parse(f.read()).get("shortcuts", {})
- except (ValueError, IndexError) as e:
- print("bannerlator-steam-shortcuts: could not read the existing file (%s); starting over" % e)
+ except (ValueError, IndexError, struct.error) as e:
+ print("bannerlator-steam-shortcuts: could not read the existing file (%s); keeping it unchanged" % e)
+ return 1
+ helper = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bannerlator-steam-games")
+ loader = importlib.machinery.SourceFileLoader("steam_games", helper)
+ spec = importlib.util.spec_from_loader(loader.name, loader)
+ routing = importlib.util.module_from_spec(spec)
+ loader.exec_module(routing)
+ games, routes = routing.route(steam_root, acct, games)
kept = [v for v in existing.values() if isinstance(v, dict) and TAG not in (v.get("tags") or {}).values()]
ours = [shortcut(g) for g in games if g.get("exe") and g.get("name")]
entries = {str(i): v for i, v in enumerate(kept + ours)}
@@ -226,8 +225,8 @@ def main():
compat = importlib.util.module_from_spec(spec)
spec.loader.exec_module(compat)
cfg = os.path.join(steam_root, "config", "config.vdf")
- if os.path.isfile(cfg) and ours:
- compat.register_default(cfg, apps=[str(int(g["appid"]) & 0xFFFFFFFF) for g in games if g.get("exe")])
+ if os.path.isfile(cfg) and (ours or routes):
+ compat.register_default(cfg, apps=[str(int(g["appid"]) & 0xFFFFFFFF) for g in games if g.get("exe")] + [str(appid) for appid in set(routes.values())])
print("bannerlator-steam-shortcuts: mapped them to %s" % compat.TOOL)
except Exception as e: # noqa: BLE001 - the games still show; the client falls back to the default tool
print("bannerlator-steam-shortcuts: compat mapping skipped (%s)" % e)
diff --git a/tools/linuxfs/preload/inputudev.c b/tools/linuxfs/preload/inputudev.c
index b3dffd1f31..5600538ea7 100644
--- a/tools/linuxfs/preload/inputudev.c
+++ b/tools/linuxfs/preload/inputudev.c
@@ -131,6 +131,9 @@ static struct pad *pad_for_syslink(const char *path) {
static void *next_symbol(const char *name) { return dlsym(RTLD_NEXT, name); }
+char *bl_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *))
+ __attribute__((visibility("hidden")));
+
/* Wine reaches libudev from its HID bus driver, which is the only caller these pads are for. */
static int caller_is_winebus(void *caller) {
Dl_info info;
@@ -152,7 +155,7 @@ char *realpath(const char *path, char *resolved) {
}
if (real_realpath == NULL) real_realpath = next_symbol("realpath");
if (real_realpath == NULL) return NULL;
- return real_realpath(path, resolved);
+ return bl_cached_realpath(path, resolved, real_realpath);
}
void *udev_device_new_from_syspath(void *udev, const char *syspath) {
diff --git a/tools/linuxfs/preload/pathcache.c b/tools/linuxfs/preload/pathcache.c
new file mode 100644
index 0000000000..2f2cfd3d40
--- /dev/null
+++ b/tools/linuxfs/preload/pathcache.c
@@ -0,0 +1,189 @@
+/*
+ * Path lookups the Steam client repeats, answered from a short-lived cache.
+ *
+ * While it registers its compatibility tools after logon, the client resolves the same few
+ * directories - its local tools under compatibilitytools.d and its own platform directory - with
+ * realpath() and access() thousands of times a second. Each realpath() is one readlinkat() per
+ * path component, and under proot every one of those is a trapped syscall with a round trip
+ * through the tracer. Measured on an AYN Thor, that loop was 23 of the client's 31 seconds of
+ * startup, with proot busy for 16 of them.
+ *
+ * Only the client itself uses the cache, never a game or a helper. Only successful answers are
+ * kept, and only for a moment: a path that stops existing is noticed within PATH_CACHE_TTL_NS, and
+ * one that starts existing is never hidden, since failures always go to the filesystem.
+ * BL_NO_PATH_CACHE=1 turns it off.
+ */
+#define _GNU_SOURCE
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define PATH_CACHE_SLOTS 256
+#define PATH_CACHE_KEY_MAX 512
+#define PATH_CACHE_TTL_NS 2000000000LL
+
+enum { KIND_REALPATH, KIND_ACCESS };
+
+struct entry {
+ long long stamp;
+ unsigned hash;
+ int kind;
+ int mode;
+ int flags;
+ char key[PATH_CACHE_KEY_MAX];
+ char *value;
+};
+
+static struct entry table[PATH_CACHE_SLOTS];
+static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
+
+static long long now_ns(void) {
+ struct timespec t;
+
+ clock_gettime(CLOCK_MONOTONIC_COARSE, &t);
+ return (long long)t.tv_sec * 1000000000LL + t.tv_nsec;
+}
+
+static int enabled(void) {
+ static int cached = -1;
+ const char *off;
+
+ if (cached >= 0) return cached;
+ off = getenv("BL_NO_PATH_CACHE");
+ cached = strcmp(program_invocation_short_name, "steam") == 0 &&
+ strstr(program_invocation_name, "steamrtarm64") != NULL &&
+ !(off != NULL && off[0] == '1');
+ return cached;
+}
+
+static unsigned hash_of(const char *s, int kind, int mode, int flags) {
+ unsigned h = 2166136261u ^ (unsigned)(kind * 31 + mode * 7 + flags);
+
+ while (*s) h = (h ^ (unsigned char)*s++) * 16777619u;
+ return h;
+}
+
+static int cacheable(const char *path) {
+ return path != NULL && path[0] == '/' && strlen(path) < PATH_CACHE_KEY_MAX && enabled();
+}
+
+static struct entry *find(const char *path, int kind, int mode, int flags, unsigned h) {
+ struct entry *e = &table[h % PATH_CACHE_SLOTS];
+
+ if (e->stamp == 0 || e->hash != h || e->kind != kind || e->mode != mode || e->flags != flags) return NULL;
+ if (now_ns() - e->stamp > PATH_CACHE_TTL_NS || strcmp(e->key, path) != 0) return NULL;
+ return e;
+}
+
+static void store(const char *path, int kind, int mode, int flags, unsigned h, const char *value) {
+ struct entry *e = &table[h % PATH_CACHE_SLOTS];
+ char *copy = value != NULL ? strdup(value) : NULL;
+
+ if (value != NULL && copy == NULL) return;
+ free(e->value);
+ e->value = copy;
+ e->hash = h;
+ e->kind = kind;
+ e->mode = mode;
+ e->flags = flags;
+ memcpy(e->key, path, strlen(path) + 1);
+ e->stamp = now_ns();
+}
+
+__attribute__((visibility("hidden")))
+char *bl_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *)) {
+ char out[PATH_MAX];
+ unsigned h;
+ struct entry *e;
+
+ if (!cacheable(path)) return real(path, resolved);
+ h = hash_of(path, KIND_REALPATH, 0, 0);
+ pthread_mutex_lock(&lock);
+ e = find(path, KIND_REALPATH, 0, 0, h);
+ if (e != NULL && e->value != NULL) {
+ size_t n = strlen(e->value) + 1;
+ char *result = resolved != NULL ? resolved : malloc(n);
+ if (result != NULL) memcpy(result, e->value, n);
+ pthread_mutex_unlock(&lock);
+ return result;
+ }
+ pthread_mutex_unlock(&lock);
+ if (real(path, out) == NULL) return NULL;
+ pthread_mutex_lock(&lock);
+ store(path, KIND_REALPATH, 0, 0, h, out);
+ pthread_mutex_unlock(&lock);
+ if (resolved != NULL) {
+ memcpy(resolved, out, strlen(out) + 1);
+ return resolved;
+ }
+ return strdup(out);
+}
+
+static int cached_access(const char *path, int mode, int flags, int (*check)(const char *, int, int)) {
+ unsigned h;
+ int hit;
+ int result;
+
+ if (!cacheable(path)) return check(path, mode, flags);
+ h = hash_of(path, KIND_ACCESS, mode, flags);
+ pthread_mutex_lock(&lock);
+ hit = find(path, KIND_ACCESS, mode, flags, h) != NULL;
+ pthread_mutex_unlock(&lock);
+ if (hit) return 0;
+ result = check(path, mode, flags);
+ if (result == 0) {
+ pthread_mutex_lock(&lock);
+ store(path, KIND_ACCESS, mode, flags, h, NULL);
+ pthread_mutex_unlock(&lock);
+ }
+ return result;
+}
+
+static int (*next_faccessat(void))(int, const char *, int, int) {
+ static int (*real)(int, const char *, int, int);
+
+ if (real == NULL) real = (int (*)(int, const char *, int, int))dlsym(RTLD_NEXT, "faccessat");
+ return real;
+}
+
+static int check_cwd(const char *path, int mode, int flags) {
+ int (*real)(int, const char *, int, int) = next_faccessat();
+
+ if (real == NULL) {
+ errno = ENOSYS;
+ return -1;
+ }
+ return real(AT_FDCWD, path, mode, flags);
+}
+
+int access(const char *path, int mode) {
+ return cached_access(path, mode, 0, check_cwd);
+}
+
+int euidaccess(const char *path, int mode) {
+ return cached_access(path, mode, AT_EACCESS, check_cwd);
+}
+
+int eaccess(const char *path, int mode) {
+ return cached_access(path, mode, AT_EACCESS, check_cwd);
+}
+
+int faccessat(int dirfd, const char *path, int mode, int flags) {
+ int (*real)(int, const char *, int, int);
+
+ if (dirfd == AT_FDCWD) {
+ return cached_access(path, mode, flags, check_cwd);
+ }
+ real = next_faccessat();
+ if (real == NULL) {
+ errno = ENOSYS;
+ return -1;
+ }
+ return real(dirfd, path, mode, flags);
+}
diff --git a/tools/linuxfs/preload/sysv.c b/tools/linuxfs/preload/sysv.c
index 6b9a21dc8a..36d7bdd70e 100644
--- a/tools/linuxfs/preload/sysv.c
+++ b/tools/linuxfs/preload/sysv.c
@@ -7,7 +7,8 @@
* segment is a plain file that shmat maps. Objects are found by the inode of their file, which is
* what the id is. semop applies its operations one by one (no all-or-nothing across a set) and
* SEM_UNDO is accepted but not performed - enough for the client, which uses single-counter sets.
- * Message queues stay unsupported. */
+ * A message queue is a table of slots in its file: gamescope hands mangoapp (Deck mode's performance
+ * overlay) each frame's timings through one. */
#define _GNU_SOURCE
#include
#include
@@ -15,6 +16,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -23,6 +25,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -396,6 +399,126 @@ int shmctl(int shmid, int cmd, struct shmid_ds *buf) {
}
}
+/* ------------------------------------------------------------------ message queues */
+
+/* Only what gamescope and mangoapp use: msgtyp 0 or > 0, IPC_NOWAIT and IPC_RMID. */
+#define MSG_MAGIC 0x574e4d51u /* "WNMQ" */
+#define MSG_SLOTS 32
+
+struct msg_queue {
+ uint32_t magic;
+ _Atomic int32_t lock; /* 0 free, else the holder's pid */
+ _Atomic int32_t changed; /* bumped on every send and receive; waiters sleep on it */
+ uint64_t next_seq;
+ struct { uint64_t seq; long mtype; size_t len; char data[2048]; } slot[MSG_SLOTS]; /* seq 0: free */
+};
+
+static struct msg_queue *msg_map(int id) {
+ int fd = open_by_id("msg", id);
+ if (fd < 0) return NULL;
+ struct msg_queue *q = mmap(NULL, sizeof(*q), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ close(fd);
+ if (q == MAP_FAILED) return NULL;
+ if (q->magic == MSG_MAGIC) return q;
+ munmap(q, sizeof(*q));
+ errno = EINVAL;
+ return NULL;
+}
+
+/* A process killed while holding the lock (Android ends sessions without warning) loses it. */
+static void msg_lock(struct msg_queue *q) {
+ for (int32_t owner = 0; !atomic_compare_exchange_strong(&q->lock, &owner, getpid()); owner = 0) {
+ if (kill(owner, 0) != 0 && errno == ESRCH) atomic_compare_exchange_strong(&q->lock, &owner, 0);
+ else futex(&q->lock, FUTEX_WAIT, owner, &(struct timespec){0, 20000000});
+ }
+}
+
+static void msg_unlock(struct msg_queue *q, int changed) {
+ atomic_store(&q->lock, 0);
+ futex(&q->lock, FUTEX_WAKE, 1, NULL);
+ if (changed) {
+ atomic_fetch_add(&q->changed, 1);
+ futex(&q->changed, FUTEX_WAKE, INT_MAX, NULL);
+ }
+}
+
+int msgget(key_t key, int msgflg) {
+ int created;
+ int fd = open_object("msg", key, msgflg, &created);
+ if (fd < 0) return -1;
+ uint32_t magic = MSG_MAGIC;
+ if (created && (ftruncate(fd, sizeof(struct msg_queue)) != 0 || pwrite(fd, &magic, sizeof(magic), 0) != sizeof(magic))) {
+ close(fd);
+ return -1;
+ }
+ int id = object_id(fd);
+ close(fd);
+ return id;
+}
+
+int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) {
+ struct msg_queue *q = msg_map(msqid);
+ if (!q) return -1;
+ if (msgsz > sizeof(q->slot[0].data) || *(const long *)msgp < 1) { munmap(q, sizeof(*q)); errno = EINVAL; return -1; }
+ for (;;) {
+ msg_lock(q);
+ int32_t seen = atomic_load(&q->changed);
+ for (int i = 0; i < MSG_SLOTS; i++) {
+ if (q->slot[i].seq) continue;
+ q->slot[i].mtype = *(const long *)msgp;
+ q->slot[i].len = msgsz;
+ memcpy(q->slot[i].data, (const long *)msgp + 1, msgsz);
+ q->slot[i].seq = ++q->next_seq;
+ msg_unlock(q, 1);
+ munmap(q, sizeof(*q));
+ return 0;
+ }
+ msg_unlock(q, 0);
+ if ((msgflg & IPC_NOWAIT) || (futex(&q->changed, FUTEX_WAIT, seen, NULL) != 0 && errno == EINTR)) {
+ munmap(q, sizeof(*q));
+ if (msgflg & IPC_NOWAIT) errno = EAGAIN;
+ return -1;
+ }
+ }
+}
+
+ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) {
+ if (msgtyp < 0) { errno = EINVAL; return -1; }
+ struct msg_queue *q = msg_map(msqid);
+ if (!q) return -1;
+ for (;;) {
+ msg_lock(q);
+ int32_t seen = atomic_load(&q->changed);
+ int best = -1;
+ for (int i = 0; i < MSG_SLOTS; i++)
+ if (q->slot[i].seq && (!msgtyp || q->slot[i].mtype == msgtyp) && (best < 0 || q->slot[i].seq < q->slot[best].seq))
+ best = i;
+ if (best >= 0) {
+ size_t n = q->slot[best].len < msgsz ? q->slot[best].len : msgsz;
+ *(long *)msgp = q->slot[best].mtype;
+ memcpy((long *)msgp + 1, q->slot[best].data, n);
+ q->slot[best].seq = 0;
+ msg_unlock(q, 1);
+ munmap(q, sizeof(*q));
+ return (ssize_t)n;
+ }
+ msg_unlock(q, 0);
+ if ((msgflg & IPC_NOWAIT) || (futex(&q->changed, FUTEX_WAIT, seen, NULL) != 0 && errno == EINTR)) {
+ munmap(q, sizeof(*q));
+ if (msgflg & IPC_NOWAIT) errno = ENOMSG;
+ return -1;
+ }
+ }
+}
+
+int msgctl(int msqid, int cmd, struct msqid_ds *buf) {
+ if (cmd != IPC_RMID) { errno = EINVAL; return -1; }
+ pthread_mutex_lock(&g_lock);
+ int rc = unlink_by_id("msg", msqid);
+ pthread_mutex_unlock(&g_lock);
+ return rc;
+}
+
/*
* fork() carries over only the calling thread, so a lock another thread was holding at that
* instant stays held in the child by a thread that is not there to release it. Taking it before
diff --git a/tools/linuxfs/preload/tracefs.c b/tools/linuxfs/preload/tracefs.c
new file mode 100644
index 0000000000..17d45a01a5
--- /dev/null
+++ b/tools/linuxfs/preload/tracefs.c
@@ -0,0 +1,101 @@
+/*
+ * A trace instance for mangoapp where the kernel's tracefs is closed to the app.
+ *
+ * Valve's mangoapp (Deck mode's performance overlay) reads the GPU memory total on a Qualcomm
+ * display driver (msm_dpu / msm_drm) from the gpu_mem_total event, through a tracefs instance of
+ * its own - and aborts when tracefs_instance_create() fails, taking the whole overlay with it.
+ * Android mounts tracefs for root and the readtracefs group only, so it always fails here.
+ *
+ * The real calls run first. Only when they fail is the instance placed in an empty directory of
+ * the session's own, and reading its events answers with one gpu_mem_total record carrying the
+ * total KGSL - the GPU driver of every Adreno under Android - reports to the app.
+ */
+#define _GNU_SOURCE
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define STANDIN_DIR "/tmp/droiddeck-tracefs"
+#define KGSL_TOTAL "/sys/class/kgsl/kgsl/page_alloc"
+
+struct tracefs_instance;
+struct tep_handle;
+struct tep_event;
+
+/* The head of libtraceevent 1.8's struct tep_record (the version tools/mangoapp/packages.txt pins). */
+struct tep_record {
+ unsigned long long ts, offset;
+ long long missed_events;
+ int record_size, size;
+ void *data;
+ int cpu, ref_count, locked;
+ void *priv;
+};
+
+/* The event as Android kernels declare it (trace/events/gpu_mem.h). */
+static const char gpu_mem_total_format[] =
+ "name: gpu_mem_total\n"
+ "ID: 1\n"
+ "format:\n"
+ "\tfield:unsigned short common_type;\toffset:0;\tsize:2;\tsigned:0;\n"
+ "\tfield:unsigned char common_flags;\toffset:2;\tsize:1;\tsigned:0;\n"
+ "\tfield:unsigned char common_preempt_count;\toffset:3;\tsize:1;\tsigned:0;\n"
+ "\tfield:int common_pid;\toffset:4;\tsize:4;\tsigned:1;\n"
+ "\n"
+ "\tfield:uint32_t gpu_id;\toffset:8;\tsize:4;\tsigned:0;\n"
+ "\tfield:uint32_t pid;\toffset:12;\tsize:4;\tsigned:0;\n"
+ "\tfield:uint64_t size;\toffset:16;\tsize:8;\tsigned:0;\n"
+ "\n"
+ "print fmt: \"gpu_id=%u pid=%u size=%llu\", REC->gpu_id, REC->pid, REC->size\n";
+
+static struct tracefs_instance *standin;
+
+struct tracefs_instance *tracefs_instance_create(const char *name) {
+ struct tracefs_instance *(*real)(const char *) = dlsym(RTLD_NEXT, "tracefs_instance_create");
+ struct tracefs_instance *instance = real ? real(name) : NULL;
+ if (instance || !name) return instance;
+ struct tracefs_instance *(*alloc)(const char *, const char *) = dlsym(RTLD_NEXT, "tracefs_instance_alloc");
+ if (!alloc) return NULL;
+ char path[PATH_MAX];
+ mkdir(STANDIN_DIR, 0700);
+ mkdir(STANDIN_DIR "/instances", 0700);
+ snprintf(path, sizeof(path), STANDIN_DIR "/instances/%s", name);
+ mkdir(path, 0700);
+ return standin = alloc(STANDIN_DIR, name);
+}
+
+struct tep_handle *tracefs_local_events(const char *tracing_dir) {
+ if (!tracing_dir || strncmp(tracing_dir, STANDIN_DIR "/", sizeof(STANDIN_DIR))) {
+ struct tep_handle *(*real)(const char *) = dlsym(RTLD_NEXT, "tracefs_local_events");
+ return real ? real(tracing_dir) : NULL;
+ }
+ struct tep_handle *(*tep_alloc)(void) = dlsym(RTLD_DEFAULT, "tep_alloc");
+ int (*parse)(struct tep_handle *, const char *, unsigned long, const char *) = dlsym(RTLD_DEFAULT, "tep_parse_event");
+ struct tep_handle *tep = tep_alloc ? tep_alloc() : NULL;
+ if (tep && parse) parse(tep, gpu_mem_total_format, sizeof(gpu_mem_total_format) - 1, "gpu_mem");
+ return tep;
+}
+
+int tracefs_iterate_raw_events(struct tep_handle *tep, struct tracefs_instance *instance, void *cpus, int cpu_size,
+ int (*callback)(struct tep_event *, struct tep_record *, int, void *), void *context) {
+ if (!standin || instance != standin) {
+ int (*real)(struct tep_handle *, struct tracefs_instance *, void *, int,
+ int (*)(struct tep_event *, struct tep_record *, int, void *), void *) =
+ dlsym(RTLD_NEXT, "tracefs_iterate_raw_events");
+ return real ? real(tep, instance, cpus, cpu_size, callback, context) : -1;
+ }
+ struct tep_event *(*find)(struct tep_handle *, int) = dlsym(RTLD_DEFAULT, "tep_find_event");
+ struct tep_event *event = find && tep ? find(tep, 1) : NULL;
+ unsigned long long total;
+ FILE *f = fopen(KGSL_TOTAL, "r");
+ int have = f && fscanf(f, "%llu", &total) == 1;
+ if (f) fclose(f);
+ if (!event || !have || !callback) return -1;
+ struct { uint16_t type; uint8_t flags, preempt; int32_t common_pid; uint32_t gpu_id, pid; uint64_t size; } data = {
+ .type = 1, .size = total};
+ struct tep_record record = {.record_size = sizeof(data), .size = sizeof(data), .data = &data};
+ return callback(event, &record, 0, context);
+}
diff --git a/tools/mangoapp/mangoapp b/tools/mangoapp/mangoapp
index 6557ed559d..4d541f73e2 100644
--- a/tools/mangoapp/mangoapp
+++ b/tools/mangoapp/mangoapp
@@ -1,4 +1,8 @@
#!/bin/sh
# gamescope --mangoapp runs `mangoapp` from PATH; this puts Valve's build beside the libraries the
# runtime lacks (fmt 10, spdlog 1.13, glfw, libtracefs, libtraceevent), staged by the app.
+# mangoapp reads its window through GLFW's X11 API. GLFW 3.4 takes XDG_SESSION_TYPE=wayland with a
+# WAYLAND_DISPLAY as Wayland-only, and unset, libwayland falls back to wayland-0 - DroidDeck's own
+# compositor, which shares XDG_RUNTIME_DIR - so both fail; x11 makes GLFW use gamescope's X server.
+export XDG_SESSION_TYPE=x11
LD_LIBRARY_PATH=/usr/local/lib/mangoapp${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} exec /usr/local/lib/mangoapp/mangoapp "$@"
diff --git a/tools/tests/test_steam_games.py b/tools/tests/test_steam_games.py
new file mode 100644
index 0000000000..26220319d9
--- /dev/null
+++ b/tools/tests/test_steam_games.py
@@ -0,0 +1,231 @@
+import importlib.machinery
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
+
+
+def load(name):
+ loader = importlib.machinery.SourceFileLoader(name, str(BIN / name))
+ spec = importlib.util.spec_from_loader(name, loader)
+ module = importlib.util.module_from_spec(spec)
+ loader.exec_module(module)
+ return module
+
+
+imports = load('bannerlator-steam-games')
+shortcuts = load('bannerlator-steam-shortcuts')
+
+
+class ImportsTest(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.steam = self.root / 'Steam'
+ self.acct = self.steam / 'userdata/123'
+ self.folder = self.root / 'Games/Example'
+ self.folder.mkdir(parents=True)
+ self.exe = self.folder / 'Example.exe'
+ self.exe.write_bytes(b'game')
+ self.game = dict(name='Example', exe=str(self.exe), folder=str(self.folder),
+ dir=str(self.folder), appid=0x87654321)
+
+ def snapshot(self, owned=True, account='123'):
+ imports.save_json(self.acct / 'config' / imports.STATE,
+ dict(account=account, owned={'42': owned},
+ candidates={str(self.folder): 42},
+ sources={str(self.folder): imports.source_stamp(self.game)}))
+
+ def test_owned_uses_real_id_and_registers_installed_files(self):
+ self.snapshot()
+ games, routes = imports.route(self.steam, self.acct, [self.game])
+ self.assertEqual([], games)
+ self.assertEqual({str(self.game['appid']): 42}, routes)
+ manifest = self.steam / 'steamapps/appmanifest_42.acf'
+ self.assertIn('"StateFlags" "4"', manifest.read_text())
+ self.assertIn('"Universe" "1"', manifest.read_text())
+ self.assertEqual(self.folder, (self.steam / 'steamapps/common/DroidDeck-42').resolve())
+ self.assertEqual(b'game', self.exe.read_bytes())
+
+ def test_migrates_only_unchanged_legacy_import_manifests(self):
+ self.snapshot()
+ imports.route(self.steam, self.acct, [self.game])
+ path = self.steam / 'steamapps/appmanifest_42.acf'
+ current = path.read_text()
+ legacy = current.replace(' "Universe" "1"\n', '').replace('"StateFlags" "4"', '"StateFlags" "2"')
+ path.write_text(legacy)
+ imports.route(self.steam, self.acct, [self.game])
+ self.assertEqual(current, path.read_text())
+ changed = legacy.replace('"StateFlags" "2"', '"StateFlags" "6"')
+ path.write_text(changed)
+ imports.route(self.steam, self.acct, [self.game])
+ self.assertEqual(changed, path.read_text())
+
+ def test_unresolved_titles_are_retried_after_network_recovers(self):
+ listing = self.root / 'games.json'
+ listing.write_text(json.dumps([self.game]))
+ from unittest.mock import Mock
+ result = Mock(returncode=0, stdout='DROIDDECK_OWNERSHIP=' + json.dumps(dict(account='123', owned={'42': True})))
+ with patch.object(imports, 'identify', side_effect=[None, 42]) as identify, \
+ patch.object(imports.time, 'monotonic', side_effect=[0, 301]), \
+ patch.object(imports.time, 'sleep', side_effect=[None, RuntimeError('stop')]), \
+ patch.object(imports.subprocess, 'run', return_value=result), \
+ patch('builtins.print'):
+ with self.assertRaisesRegex(RuntimeError, 'stop'):
+ imports.watch(self.steam, listing)
+ self.assertEqual(2, identify.call_count)
+ snapshot = imports.read_json(self.acct / 'config' / imports.STATE, {})
+ self.assertTrue(snapshot['owned']['42'])
+
+ def test_unowned_unknown_and_different_account_stay_shortcuts(self):
+ for owned, account in [(False, '123'), (True, '456')]:
+ self.snapshot(owned, account)
+ self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game]))
+ (self.acct / 'config' / imports.STATE).unlink()
+ self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game]))
+ self.assertFalse((self.steam / 'steamapps').exists())
+
+ def test_existing_manifest_is_never_overwritten(self):
+ manifest = self.steam / 'steamapps/appmanifest_42.acf'
+ manifest.parent.mkdir(parents=True)
+ manifest.write_text('Steam owns this file')
+ self.snapshot()
+ imports.route(self.steam, self.acct, [self.game])
+ self.assertEqual('Steam owns this file', manifest.read_text())
+
+ def test_import_collision_falls_back_without_touching_files(self):
+ occupied = self.steam / 'steamapps/common/DroidDeck-42'
+ occupied.mkdir(parents=True)
+ self.snapshot()
+ self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game]))
+ self.assertTrue(occupied.is_dir())
+ self.assertFalse(occupied.is_symlink())
+
+ def test_removed_folder_does_not_import(self):
+ self.snapshot()
+ self.exe.unlink()
+ self.folder.rmdir()
+ self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game]))
+
+ def test_replaced_game_does_not_inherit_cached_ownership(self):
+ self.snapshot()
+ self.exe.write_bytes(b'a different game')
+ self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game]))
+
+ def test_duplicate_owned_folders_share_one_steam_entry(self):
+ self.snapshot()
+ games, routes = imports.route(self.steam, self.acct, [self.game, self.game])
+ self.assertEqual([], games)
+ self.assertEqual(1, len(routes))
+ self.assertEqual(1, len(list((self.steam / 'steamapps').glob('*.acf'))))
+
+ def test_explicit_appid_does_not_need_network(self):
+ (self.folder / 'steam_appid.txt').write_text('42\n')
+ with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError):
+ self.assertEqual(42, imports.identify(self.game))
+
+ def test_manifest_identity_uses_install_directory(self):
+ folder = self.root / 'second/steamapps/common/Custom Name'
+ folder.mkdir(parents=True)
+ (folder.parent.parent / 'appmanifest_42.acf').write_text('"AppState" { "installdir" "Custom Name" }')
+ game = dict(self.game, folder=str(folder), exe=str(folder / 'game.exe'))
+ with patch.object(imports.urllib.request, 'urlopen', side_effect=AssertionError):
+ self.assertEqual(42, imports.identify(game))
+
+ def test_store_requires_unique_exact_title(self):
+ cases = [([{'id': 42, 'name': 'Example Deluxe'}], None),
+ ([{'id': 42, 'name': 'Example'}, {'id': 43, 'name': 'Example'}], None),
+ ([{'id': 42, 'name': 'EXAMPLE'}], 42)]
+ for items, expected in cases:
+ with patch.object(imports.urllib.request, 'urlopen') as request:
+ request.return_value.__enter__.return_value.read.return_value = json.dumps({'items': items}).encode()
+ self.assertEqual(expected, imports.identify(self.game))
+
+ def test_store_country_and_edition_suffixes(self):
+ for folder, store in [('FINAL FANTASY VII REMAKE', 'FINAL FANTASY VII REMAKE INTERGRADE'),
+ ('FINAL FANTASY XV', 'FINAL FANTASY XV WINDOWS EDITION')]:
+ with patch.object(imports.urllib.request, 'urlopen') as request:
+ request.return_value.__enter__.return_value.read.return_value = json.dumps({'items': [{'id': 42, 'name': store}]}).encode()
+ self.assertEqual(42, imports.identify(dict(self.game, name=folder)))
+ self.assertIn('cc=US&', request.call_args.args[0])
+
+ def test_edition_matching_rejects_ambiguous_titles_and_soundtracks(self):
+ with patch.object(imports.urllib.request, 'urlopen') as request:
+ request.return_value.__enter__.return_value.read.return_value = json.dumps({'items': [
+ {'id': 42, 'name': 'Example WINDOWS EDITION'},
+ {'id': 43, 'name': 'Example INTERGRADE'},
+ {'id': 44, 'name': 'Example Soundtrack'},
+ ]}).encode()
+ self.assertIsNone(imports.identify(self.game))
+
+ def test_corrupt_shortcuts_are_preserved(self):
+ path = self.acct / 'config/shortcuts.vdf'
+ path.parent.mkdir(parents=True)
+ original = b'corrupt'
+ path.write_bytes(original)
+ listing = self.root / 'games.json'
+ listing.write_text(json.dumps([self.game]))
+ run = subprocess.run(['python3', str(BIN / 'bannerlator-steam-shortcuts'), str(self.steam), str(listing)], capture_output=True)
+ self.assertEqual(1, run.returncode)
+ self.assertEqual(original, path.read_bytes())
+
+ def test_user_shortcuts_survive_owned_promotion(self):
+ self.snapshot()
+ path = self.acct / 'config/shortcuts.vdf'
+ manual = dict(shortcuts.shortcut(self.game), tags={'0': 'Personal'}, AppName='Manual')
+ path.write_bytes(shortcuts.write({'shortcuts': {'0': manual, '1': shortcuts.shortcut(self.game)}}))
+ listing = self.root / 'games.json'
+ listing.write_text(json.dumps([self.game]))
+ subprocess.run(['python3', str(BIN / 'bannerlator-steam-shortcuts'), str(self.steam), str(listing)], check=True, capture_output=True)
+ result = shortcuts.parse(path.read_bytes())['shortcuts']
+ self.assertEqual([manual], list(result.values()))
+ self.assertEqual({str(self.game['appid']): 42}, json.loads((path.parent / '.droiddeck-routes.json').read_text()))
+
+
+class SteamProbeTest(unittest.TestCase):
+ def test_probe_reads_account_and_licenses_and_releases_handles(self):
+ import ctypes as C
+ from unittest.mock import Mock
+ objects, callbacks, calls = [], [], []
+
+ def interface(slots):
+ table = (C.c_void_p * 24)()
+ for slot, result, args, callback in slots:
+ fn = C.CFUNCTYPE(result, C.c_void_p, *args)(callback)
+ callbacks.append(fn)
+ table[slot] = C.cast(fn, C.c_void_p).value
+ obj = C.pointer(C.cast(table, C.POINTER(C.c_void_p)))
+ objects.extend([table, obj])
+ return C.cast(obj, C.c_void_p).value
+
+ user = interface([
+ (1, C.c_bool, [], lambda _: True),
+ (2, C.c_uint64, [], lambda _: imports.BASE_ID + 123),
+ ])
+ apps = interface([(6, C.c_bool, [C.c_uint32], lambda _, appid: appid == 42)])
+ client = interface([
+ (0, C.c_int, [], lambda _: 7),
+ (1, C.c_bool, [C.c_int], lambda _, pipe: calls.append(('pipe', pipe)) or True),
+ (2, C.c_int, [C.c_int], lambda _, pipe: 9),
+ (4, None, [C.c_int, C.c_int], lambda _, pipe, handle: calls.append(('user', pipe, handle))),
+ (5, C.c_void_p, [C.c_int, C.c_int, C.c_char_p], lambda _, handle, pipe, version: user if version == b'SteamUser021' else 0),
+ (15, C.c_void_p, [C.c_int, C.c_int, C.c_char_p], lambda _, handle, pipe, version: apps if version == b'STEAMAPPS_INTERFACE_VERSION008' else 0),
+ ])
+ library = Mock()
+ library.CreateInterface.return_value = client
+ with patch.object(imports.C, 'CDLL', return_value=library):
+ result = imports.probe('/Steam', [42, 43])
+ self.assertEqual('123', result['account'])
+ self.assertEqual({'42': True, '43': False}, result['owned'])
+ self.assertEqual([('user', 7, 9), ('pipe', 7)], calls)
+ library.CreateInterface.assert_called_once_with(b'SteamClient020', None)
+
+
+if __name__ == '__main__':
+ unittest.main()