diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a5965ffe22..b2377bf6d3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,4 +1,5 @@ name: Build APK +run-name: ${{ github.event_name == 'pull_request' && format('building pr {0} on {1}', github.event.pull_request.number, github.event.pull_request.head.sha) || format('building {0} on {1}', github.ref_name, github.sha) }} # One job: the two glibc preload libraries the session needs, then the app around them. # Nothing is built on a developer machine - this workflow is the only thing that produces an apk. @@ -21,10 +22,15 @@ on: # A pull request against main builds by itself: the contributor's branch, as it would be once # merged onto main, comes back as an apk on the run without anyone here pressing a button. # Every push to the pull request rebuilds it and cancels the build it replaces; a draft waits - # until it is marked ready. pull_request_target rather than pull_request: GitHub does not run - # the latter at all while a pull request conflicts with main, and saying what conflicts is the - # point. The workflow file is always main's; the pull request's own code is checked out below. - pull_request_target: + # until it is marked ready. + # + # pull_request, NOT pull_request_target. The _target form runs a pull request's code with main's + # context: its caches are main's caches, so a hostile pull request could leave a poisoned + # Gradle/CMake cache that main's next build - which is signed with DroidDeck's key - picks up. + # Under pull_request a fork's run has a read-only token, no secrets, and caches of its own that + # main never reads. The price: GitHub does not run pull_request while a pull request conflicts + # with main, so a conflicting one gets no build (the pull request page still shows the conflict). + pull_request: branches: [ main ] types: [ opened, synchronize, reopened, ready_for_review ] paths-ignore: @@ -49,7 +55,7 @@ env: jobs: build: - if: ${{ github.event_name != 'pull_request_target' || !github.event.pull_request.draft }} + if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} runs-on: ubuntu-24.04 timeout-minutes: 45 steps: @@ -58,15 +64,27 @@ jobs: # the next step is to say so and show where. - uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || github.sha }} + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} # Full history: the merge below needs it (a shallow clone refuses to merge at all). fetch-depth: 0 # The pull request as it would be once merged onto main is what gets built. When it cannot # be merged, the conflicting files and the conflicting hunks go into the run summary and the # pull-request comment, and the job stops here: there is nothing coherent to build. + # DroidDeck's signing key lives only in GitHub environment secrets (see sign.yml). A key file + # committed by mistake would be in the history for good: stop at the first one. The AOSP + # testkey is public and meant to be here. + - name: No private key in the tree + run: | + set -euo pipefail + keys=$(git ls-files | grep -iE '\.(jks|keystore|p12|pfx|pk8|pem|key)$' | grep -vx 'keystore/testkey.p12' || true) + if [ -n "$keys" ]; then + echo "::error::a private key is committed - remove it from the history and make a new one: $keys" + exit 1 + fi + - name: Merge onto main, or say what conflicts - if: github.event_name == 'pull_request_target' + if: github.event_name == 'pull_request' run: | set -uo pipefail git config user.name "ci" @@ -140,6 +158,28 @@ jobs: echo "NDK $VERSION at $NDK" echo "NDK_VERSION=$VERSION" >> "$GITHUB_ENV" + - name: Set the APK build label + id: build-label + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + BUILD_REF: ${{ github.ref_name }} + BUILD_SHA: ${{ github.sha }} + run: | + if [[ -n "$(git status --porcelain)" ]]; then + tree_state=dirty + else + tree_state=clean + fi + echo "DROIDDECK_BUILD_TREE_STATE=$tree_state" >> "$GITHUB_ENV" + if [[ -n "$PR_NUMBER" ]]; then + label="pr${PR_NUMBER} at ${PR_HEAD_SHA:0:7}" + else + label="${BUILD_REF} at ${BUILD_SHA:0:7}" + fi + echo "label=$label" >> "$GITHUB_OUTPUT" + echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY" + # ── The session's preloads ─────────────────────────────────────────────────────────── # Both are glibc aarch64 libraries that live inside the rootfs, so they are cross-compiled # here rather than by the NDK. They ship in assets (not in the runtime tarball) so a fix in @@ -306,6 +346,8 @@ jobs: # The whole log is kept so a failed build's errors can be quoted back on a pull request. - name: Build id: build + env: + DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }} run: | set -o pipefail ./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log @@ -390,7 +432,7 @@ jobs: # build failed, the compiler's own errors with paths made short. Fork pull requests carry a # read-only token and cannot comment; the same text is in the run summary either way. - name: Report on the pull request - if: always() && github.event_name == 'pull_request_target' + if: always() && github.event_name == 'pull_request' continue-on-error: true env: GH_TOKEN: ${{ github.token }} @@ -410,7 +452,7 @@ jobs: success) echo "### Build passed" echo - echo "The apk is the \`droiddeck-apk\` artifact on [this run]($RUN_URL) (signed with the same test key as every build, so it installs over any other)." + echo "The apk is the \`droiddeck-apk\` artifact on [this run]($RUN_URL) A pull request's build is signed only with the public test key: it installs on a phone without an official DroidDeck. To install it over one, sign it with DroidDeck's key or ask for a test build of the branch." ;; failure) echo "### ERROR: Build failed" @@ -455,3 +497,21 @@ jobs: retention-days: 30 # An apk is a zip already; compressing it again buys nothing and costs seconds. compression-level: 0 + + # The apk signed with DroidDeck's own key (tools/release), so a test build installs over a release + # and keeps its data. Main's builds sign straight away (signing-main); any other branch's wait for + # the owner's approval (signing-branch). A pull request's never: its code is not ours to sign, and + # the job that would hold the key never runs for it. The testkey apk above is unaffected. + sign: + needs: build + if: github.event_name != 'pull_request' + # What sign.yml asks for; a called workflow never gets more than its caller gives it. + permissions: + contents: read + actions: read + uses: ./.github/workflows/sign.yml + with: + environment: ${{ github.ref == 'refs/heads/main' && 'signing-main' || 'signing-branch' }} + variants: '["standard"]' + # The key is an environment secret; a called workflow sees secrets only when they are passed on. + secrets: inherit diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000000..2106659c84 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,68 @@ +name: Release APKs +run-name: release ${{ inputs.version }} from main ${{ github.sha }} + +# Every package of a release, signed with DroidDeck's own key: the standard app and the named ones +# in tools/release/variants.txt, one matrix job each. Nothing is rebuilt - the apk is the one the +# Build APK run of this exact main commit made (with its caches) and that was tested, so the +# release is those bytes. Waits for the owner's approval (the release environment); publishing the +# GitHub release stays a separate, manual step. + +on: + workflow_dispatch: + inputs: + version: + description: Version for the file names, e.g. 0.1.7 + required: true + +permissions: + contents: read + actions: read + +concurrency: + group: release + cancel-in-progress: false + +jobs: + find: + name: find the main build + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + outputs: + run_id: ${{ steps.find.outputs.run_id }} + variants: ${{ steps.find.outputs.variants }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - id: find + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + [[ $VERSION =~ ^[0-9A-Za-z._-]+$ ]] || { echo "::error::version '$VERSION': letters, digits, . _ - only"; exit 1; } + # This commit's Build APK run - a push or a dispatch on main, never a pull request's. + runs=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml --branch main --commit "$GITHUB_SHA" \ + --status success --json databaseId,event,headSha -L 20) + id=$(jq -r --arg sha "$GITHUB_SHA" \ + '[.[] | select(.headSha == $sha and (.event == "push" or .event == "workflow_dispatch"))][0].databaseId // empty' <<<"$runs") + if [ -z "$id" ]; then + echo "::error::main ${GITHUB_SHA::7} has no successful Build APK run yet: wait for it, then release" + exit 1 + fi + variants=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .) + echo "run_id=$id" >> "$GITHUB_OUTPUT" + echo "variants=$variants" >> "$GITHUB_OUTPUT" + echo "Signing Build APK run $id (main ${GITHUB_SHA::7}) as $VERSION: $variants" >> "$GITHUB_STEP_SUMMARY" + + sign: + needs: find + uses: ./.github/workflows/sign.yml + with: + environment: release + variants: ${{ needs.find.outputs.variants }} + run_id: ${{ needs.find.outputs.run_id }} + label: ${{ inputs.version }} + artifact: droiddeck-release + # The key is an environment secret; a called workflow sees secrets only when they are passed on. + secrets: inherit diff --git a/.github/workflows/sign.yml b/.github/workflows/sign.yml new file mode 100644 index 0000000000..e1e6498695 --- /dev/null +++ b/.github/workflows/sign.yml @@ -0,0 +1,105 @@ +name: Sign APKs + +# Called, never run by itself: turns a "Build APK" apk into packages signed with DroidDeck's own key, +# one matrix job per package in tools/release/variants.txt (tools/release/sign-apk.sh does the work +# and checks it). The key lives only in the GitHub environment named by the caller: +# signing-main builds of main +# signing-branch builds of any other branch - waits for the owner's approval +# release release.yml - main only, waits for the owner's approval +# Pull requests never get here (build.yml skips this for pull_request), so code from a pull +# request can never be signed with the key or come near it. + +on: + workflow_call: + inputs: + environment: + type: string + required: true + variants: + description: JSON array of names from tools/release/variants.txt + type: string + required: true + run_id: + description: The Build APK run whose apk to sign; empty for the calling run's own + type: string + default: '' + label: + description: Goes in the file names (a version); empty for - + type: string + default: '' + artifact: + type: string + default: droiddeck-signed + +permissions: + contents: read + actions: read + +jobs: + sign: + name: sign ${{ matrix.variant }} + runs-on: ubuntu-24.04 + timeout-minutes: 15 + environment: ${{ inputs.environment }} + strategy: + fail-fast: false + matrix: + variant: ${{ fromJSON(inputs.variants) }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: The apk (this run's build) + if: inputs.run_id == '' + uses: actions/download-artifact@v4 + with: + name: droiddeck-apk + path: in + + - name: The apk (a main build) + if: inputs.run_id != '' + env: + GH_TOKEN: ${{ github.token }} + RUN: ${{ inputs.run_id }} + run: gh run download "$RUN" -R "$GITHUB_REPOSITORY" -n droiddeck-apk -D in + + - name: Sign + env: + RELEASE_KEYSTORE_B64: ${{ secrets.RELEASE_KEYSTORE_B64 }} + RELEASE_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }} + # The alias is not a secret (and as one, GitHub would mask 'droiddeck' all over the logs). + RELEASE_KEY_ALIAS: droiddeck + ENVIRONMENT: ${{ inputs.environment }} + VARIANT: ${{ matrix.variant }} + LABEL: ${{ inputs.label }} + run: | + set -euo pipefail + if [ -z "$RELEASE_KEYSTORE_B64" ]; then + echo "::error::environment '$ENVIRONMENT' has no signing key: run tools/release/make-release-key.sh once" + exit 1 + fi + export RELEASE_KEYSTORE="$RUNNER_TEMP/release.p12" + ( umask 077; base64 -d <<<"$RELEASE_KEYSTORE_B64" > "$RELEASE_KEYSTORE" ) + BUILD_TOOLS=$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -n1) + export BUILD_TOOLS + [ -n "$LABEL" ] || LABEL="${GITHUB_REF_NAME//\//-}-${GITHUB_SHA::7}" + suffix=$(awk -v v="$VARIANT" '!/^#/ && $1 == v { print $3 }' tools/release/variants.txt) + [ "$suffix" = - ] && suffix= + apks=(in/*.apk) + [ ${#apks[@]} = 1 ] && [ -f "${apks[0]}" ] || { echo "::error::expected one apk in the build"; exit 1; } + mkdir -p out + out="out/DroidDeck-$LABEL$suffix.apk" + tools/release/sign-apk.sh "${apks[0]}" "$VARIANT" "$out" + ( cd out && sha256sum -- *.apk > "SHA256SUMS-$VARIANT.txt" && cat "SHA256SUMS-$VARIANT.txt" ) + echo "- \`$(basename "$out")\` - $(cut -c1-16 "out/SHA256SUMS-$VARIANT.txt")…" >> "$GITHUB_STEP_SUMMARY" + + - name: Forget the key + if: always() + run: rm -f "$RUNNER_TEMP/release.p12" + + - uses: actions/upload-artifact@v4 + with: + name: ${{ inputs.artifact }}-${{ matrix.variant }} + path: out/* + if-no-files-found: error diff --git a/.gitignore b/.gitignore index 97ca1e4c80..1fa2e10c15 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,15 @@ app/src/main/assets/linuxfs/ # Kotlin compiler session files (build-tool state, never source). .kotlin/ + +# Signing keys never enter the repo (DroidDeck's lives in GitHub environment secrets; see +# tools/release/make-release-key.sh). keystore/testkey.p12 is the public AOSP testkey. +*.jks +*.keystore +*.p12 +*.pfx +*.pk8 +*.pem +!keystore/testkey.p12 +droiddeck-release-key/ +password.txt diff --git a/app/build.gradle b/app/build.gradle index 413b4e2238..7fa1adc1bc 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -4,6 +4,51 @@ plugins { apply plugin: 'kotlin-android' apply plugin: 'org.jetbrains.kotlin.plugin.compose' +def gitValue = { List arguments -> + try { + def output = providers.exec { + commandLine(['git'] + arguments) + workingDir rootProject.projectDir + ignoreExitValue = true + } + output.result.get().exitValue == 0 ? output.standardOutput.asText.get().trim() : null + } catch (Exception ignored) { + null + } +} + +def buildLabel = providers.environmentVariable('DROIDDECK_BUILD_LABEL').getOrNull() +if (buildLabel == null || buildLabel.trim().isEmpty()) { + def eventName = providers.environmentVariable('GITHUB_EVENT_NAME').getOrNull() + def eventPath = providers.environmentVariable('GITHUB_EVENT_PATH').getOrNull() + if (eventName == 'pull_request_target' && eventPath) { + try { + def eventFile = layout.file(providers.provider { new File(eventPath) }) + def eventText = providers.fileContents(eventFile).asText.get() + def pullRequest = new groovy.json.JsonSlurper().parseText(eventText).pull_request + if (pullRequest?.number && pullRequest?.head?.sha) { + buildLabel = "pr${pullRequest.number} at ${pullRequest.head.sha.take(7)}" + } + } catch (Exception ignored) { + } + } + if (buildLabel == null || buildLabel.trim().isEmpty()) { + def branch = providers.environmentVariable('GITHUB_REF_NAME').getOrNull() + ?: gitValue(['branch', '--show-current']) ?: 'local' + def commit = providers.environmentVariable('GITHUB_SHA').getOrNull() + ?.take(7) ?: gitValue(['rev-parse', '--short=7', 'HEAD']) ?: 'unknown' + buildLabel = "${branch} at ${commit}" + } +} +def buildOrigin = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true' ? 'remote' : 'local' +def treeState = providers.environmentVariable('DROIDDECK_BUILD_TREE_STATE').getOrNull() +if (!(treeState in ['clean', 'dirty'])) { + def status = gitValue(['status', '--porcelain']) + treeState = status == null ? 'unknown' : (status.isEmpty() ? 'clean' : 'dirty') +} +buildLabel = "${buildOrigin} ${treeState} · ${buildLabel}" +def escapedBuildLabel = buildLabel.replace('\\', '\\\\').replace('"', '\\"') + android { namespace 'com.droiddeck.launcher' compileSdk 34 @@ -20,6 +65,7 @@ android { targetSdkVersion 28 versionCode 7 versionName "0.1.6" + buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\"" ndk { abiFilters 'arm64-v8a' @@ -87,6 +133,7 @@ android { buildFeatures { compose true + buildConfig true } compileOptions { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 362a87d12d..dbd5b4ac62 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -123,5 +123,17 @@ android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/log_share_paths" /> + + + + + + diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 55fb521586..5b7642bb7d 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -465,17 +465,23 @@ static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_ /* Each Wine process is a separate client with its own wl_pointer / wl_keyboard. */ struct seat_pointer { struct wl_resource *ptr; struct wl_resource *focus; }; struct seat_keyboard { struct wl_resource *kb; struct wl_resource *focus; }; +struct seat_touch { struct wl_resource *touch; struct wl_resource *focus; }; #define MAX_PTRS 32 +#define MAX_TOUCH_POINTS 32 static struct seat_pointer g_ptrs[MAX_PTRS]; static int g_nptrs; static struct seat_keyboard g_kbs[MAX_PTRS]; static int g_nkbs; +static struct seat_touch g_touches[MAX_PTRS]; +static int g_ntouches; +struct active_touch { struct surface *surface; int pointer_fallback; }; +static struct active_touch g_touch_points[MAX_TOUCH_POINTS]; +static void touch_cancel_surface(struct surface *surface); static struct surface *g_grab; /* no-desktop fallback: surface holding the button */ static struct surface *g_key_target; /* no-desktop fallback: last clicked surface */ static struct surface *g_ime_click; /* last clicked program window: where text input goes */ static int g_input_pipe[2] = {-1, -1}; -/* type 0 = pointer (p1=action 0down/1move/2up, p2=x, p3=y); type 1 = key (p1=evdev, p2=state 1down/0up) */ -struct input_msg { int type; int p1; int p2; int p3; }; +struct input_msg { int type; int p1; int p2; int p3; int p4; }; /* Pointer constraints (zwp_pointer_constraints_v1) and relative pointers * (zwp_relative_pointer_manager_v1); see the "pointer constraints" section. */ @@ -1002,6 +1008,7 @@ static void surface_resource_destroy(struct wl_resource *r) { if (!s) return; for (int i = 0; i < g_nptrs; i++) if (g_ptrs[i].focus == r) g_ptrs[i].focus = NULL; for (int i = 0; i < g_nkbs; i++) if (g_kbs[i].focus == r) g_kbs[i].focus = NULL; + touch_cancel_surface(s); if (g_grab == s) g_grab = NULL; if (g_key_target == s) g_key_target = NULL; if (g_ime_click == s) g_ime_click = NULL; @@ -2401,6 +2408,10 @@ static void keyboard_res_destroy(struct wl_resource *r) { } static void touch_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } static const struct wl_touch_interface touch_impl = { .release = touch_release }; +static void touch_res_destroy(struct wl_resource *r) { + for (int i = 0; i < g_ntouches; i++) + if (g_touches[i].touch == r) { g_touches[i] = g_touches[--g_ntouches]; break; } +} static void seat_get_pointer(struct wl_client *c, struct wl_resource *r, uint32_t id) { struct wl_resource *p = wl_resource_create(c, &wl_pointer_interface, wl_resource_get_version(r), id); @@ -2432,7 +2443,13 @@ static void seat_get_keyboard(struct wl_client *c, struct wl_resource *r, uint32 } static void seat_get_touch(struct wl_client *c, struct wl_resource *r, uint32_t id) { struct wl_resource *t = wl_resource_create(c, &wl_touch_interface, wl_resource_get_version(r), id); - if (t) wl_resource_set_implementation(t, &touch_impl, NULL, NULL); + if (!t) { wl_client_post_no_memory(c); return; } + wl_resource_set_implementation(t, &touch_impl, NULL, touch_res_destroy); + if (g_ntouches < MAX_PTRS) { + g_touches[g_ntouches].touch = t; + g_touches[g_ntouches].focus = NULL; + g_ntouches++; + } } static void seat_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } static const struct wl_seat_interface seat_impl = { @@ -2442,7 +2459,7 @@ static const struct wl_seat_interface seat_impl = { static void bind_seat(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { struct wl_resource *r = wl_resource_create(c, &wl_seat_interface, ver, id); wl_resource_set_implementation(r, &seat_impl, NULL, NULL); - wl_seat_send_capabilities(r, WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_KEYBOARD); + wl_seat_send_capabilities(r, WL_SEAT_CAPABILITY_POINTER | WL_SEAT_CAPABILITY_KEYBOARD | WL_SEAT_CAPABILITY_TOUCH); if (ver >= 2) wl_seat_send_name(r, "bannerlator-seat"); } @@ -2466,6 +2483,9 @@ static struct seat_keyboard *keyboard_for(struct wl_client *client) { #define for_each_keyboard_of(client, sk) \ for (int _i = 0; _i < g_nkbs; _i++) \ if (((sk) = &g_kbs[_i]), wl_resource_get_client((sk)->kb) == (client)) +#define for_each_touch_of(client, st) \ + for (int _i = 0; _i < g_ntouches; _i++) \ + if (((st) = &g_touches[_i]), wl_resource_get_client((st)->touch) == (client)) /* Topmost window whose scene rectangle contains the point (no-desktop fallback). */ static struct surface *toplevel_at(double x, double y) { @@ -3000,6 +3020,179 @@ static void deliver_pointer(const struct input_msg *m) { pointer_event(x, y, m->p1 == 1 ? 0 : BTN_LEFT, m->p1 == 0); } +static void input_output_to_scene(int px, int py, double *x, double *y) { + int w, h, ow, oh; + scene_size(&w, &h); + vkp_output_size(&ow, &oh); + if (ow <= 0 || oh <= 0 || + !vkp_output_to_scene((double)px * ow / INPUT_SPACE_W, (double)py * oh / INPUT_SPACE_H, x, y)) { + *x = (double)px * w / INPUT_SPACE_W; + *y = (double)py * h / INPUT_SPACE_H; + } + if (*x < 0) *x = 0; + if (*y < 0) *y = 0; + if (*x > w - 1) *x = w - 1; + if (*y > h - 1) *y = h - 1; +} + +static int touch_points_for_client(struct wl_client *client) { + for (int i = 0; i < MAX_TOUCH_POINTS; i++) { + struct surface *surface = g_touch_points[i].surface; + if (surface && wl_resource_get_client(surface->resource) == client) return 1; + } + return 0; +} + +static void touch_frame(struct wl_client *client) { + struct seat_touch *st; + for_each_touch_of(client, st) + if (wl_resource_get_version(st->touch) >= WL_TOUCH_FRAME_SINCE_VERSION) + wl_touch_send_frame(st->touch); +} + +static void touch_cancel_client(struct wl_client *client) { + struct seat_touch *st; + int release_pointer = 0; + for_each_touch_of(client, st) { + if (st->focus) wl_touch_send_cancel(st->touch); + st->focus = NULL; + } + for (int i = 0; i < MAX_TOUCH_POINTS; i++) { + struct surface *surface = g_touch_points[i].surface; + if (surface && wl_resource_get_client(surface->resource) == client) { + release_pointer |= g_touch_points[i].pointer_fallback; + memset(&g_touch_points[i], 0, sizeof(g_touch_points[i])); + } + } + if (release_pointer) pointer_button(BTN_LEFT, 0); + wl_display_flush_clients(g_display); +} + +static void touch_cancel_all(void) { + int release_pointer = 0; + for (int i = 0; i < g_ntouches; i++) { + if (g_touches[i].focus) wl_touch_send_cancel(g_touches[i].touch); + g_touches[i].focus = NULL; + } + for (int i = 0; i < MAX_TOUCH_POINTS; i++) + release_pointer |= g_touch_points[i].pointer_fallback; + memset(g_touch_points, 0, sizeof(g_touch_points)); + if (release_pointer) pointer_button(BTN_LEFT, 0); + wl_display_flush_clients(g_display); +} + +static void touch_cancel_surface(struct surface *surface) { + struct wl_client *client = wl_resource_get_client(surface->resource); + for (int i = 0; i < MAX_TOUCH_POINTS; i++) + if (g_touch_points[i].surface == surface) { + touch_cancel_client(client); + return; + } +} + +static struct surface *touch_target_at(double x, double y) { + struct surface *target = toplevel_at(x, y); + if (target) return target; + if (g_desktop) return g_desktop; + return g_grab ? g_grab : g_key_target; +} + +static void touch_down(int id, double x, double y) { + if (id < 0 || id >= MAX_TOUCH_POINTS) return; + struct surface *target = touch_target_at(x, y); + if (!target) return; + struct wl_client *client = wl_resource_get_client(target->resource); + int any_active = 0; + for (int i = 0; i < MAX_TOUCH_POINTS; i++) { + struct surface *active = g_touch_points[i].surface; + if (!active) continue; + any_active = 1; + if (active != target) { + touch_cancel_all(); + any_active = 0; + break; + } + } + if (g_touch_points[id].surface) touch_cancel_client(client); + struct seat_touch *st; + int has_touch = 0; + for_each_touch_of(client, st) has_touch = 1; + if (!has_touch) { + if (any_active) return; + g_touch_points[id].surface = target; + g_touch_points[id].pointer_fallback = 1; + pointer_event(x, y, BTN_LEFT, 1); + wl_display_flush_clients(g_display); + return; + } + int tx = 0, ty = 0; + if (target != g_desktop && target->placed) { tx = target->x; ty = target->y; } + wl_fixed_t fx = wl_fixed_from_double(x - tx), fy = wl_fixed_from_double(y - ty); + int sent = 0; + for_each_touch_of(client, st) { + st->focus = target->resource; + wl_touch_send_down(st->touch, wl_display_next_serial(g_display), now_ms(), + target->resource, id, fx, fy); + sent = 1; + } + if (!sent) return; + g_touch_points[id].surface = target; + touch_frame(client); + wl_display_flush_clients(g_display); +} + +static void touch_motion(int id, double x, double y) { + if (id < 0 || id >= MAX_TOUCH_POINTS) return; + struct surface *target = g_touch_points[id].surface; + if (!target) return; + if (g_touch_points[id].pointer_fallback) { + pointer_event(x, y, 0, 0); + wl_display_flush_clients(g_display); + return; + } + struct wl_client *client = wl_resource_get_client(target->resource); + int tx = 0, ty = 0; + if (target != g_desktop && target->placed) { tx = target->x; ty = target->y; } + wl_fixed_t fx = wl_fixed_from_double(x - tx), fy = wl_fixed_from_double(y - ty); + struct seat_touch *st; + for_each_touch_of(client, st) + if (st->focus == target->resource) + wl_touch_send_motion(st->touch, now_ms(), id, fx, fy); + touch_frame(client); + wl_display_flush_clients(g_display); +} + +static void touch_up(int id, double x, double y) { + if (id < 0 || id >= MAX_TOUCH_POINTS) return; + struct surface *target = g_touch_points[id].surface; + if (!target) return; + if (g_touch_points[id].pointer_fallback) { + memset(&g_touch_points[id], 0, sizeof(g_touch_points[id])); + pointer_event(x, y, BTN_LEFT, 0); + wl_display_flush_clients(g_display); + return; + } + struct wl_client *client = wl_resource_get_client(target->resource); + struct seat_touch *st; + for_each_touch_of(client, st) + if (st->focus == target->resource) + wl_touch_send_up(st->touch, wl_display_next_serial(g_display), now_ms(), id); + memset(&g_touch_points[id], 0, sizeof(g_touch_points[id])); + touch_frame(client); + if (!touch_points_for_client(client)) + for_each_touch_of(client, st) st->focus = NULL; + wl_display_flush_clients(g_display); +} + +static void deliver_touch(const struct input_msg *m) { + double x, y; + input_output_to_scene(m->p3, m->p4, &x, &y); + if (m->p1 == 0) touch_down(m->p2, x, y); + else if (m->p1 == 1) touch_motion(m->p2, x, y); + else if (m->p1 == 2) touch_up(m->p2, x, y); + else if (m->p1 == 3) touch_cancel_all(); +} + static void key_event(uint32_t evdev, int pressed); struct wl_resource *banner_ime_target(void); static void deliver_key(const struct input_msg *m) { @@ -3068,6 +3261,7 @@ static int on_input_readable(int fd, uint32_t mask, void *data) { case 4: scroll_event(m.p1); break; case 5: on_vsync(((int64_t)m.p1 << 32) | (uint32_t)m.p2); break; case 6: pointer_delta(m.p1 / 256.0, m.p2 / 256.0); break; /* relative motion, 1/256 px */ + case 7: deliver_touch(&m); break; default: deliver_pointer(&m); break; } } @@ -3078,7 +3272,14 @@ static int on_input_readable(int fd, uint32_t mask, void *data) { * dispatches it. x/y are in INPUT_SPACE (0..1919, 0..1079) over the whole output. */ void banner_wayland_send_pointer(int action, int x, int y) { if (g_input_pipe[1] < 0) return; - struct input_msg m = { 0, action, x, y }; + struct input_msg m = { 0, action, x, y, 0 }; + ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); + (void)n; +} + +void banner_wayland_send_touch(int action, int pointer_id, int x, int y) { + if (g_input_pipe[1] < 0) return; + struct input_msg m = { 7, action, pointer_id, x, y }; ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); (void)n; } @@ -3086,7 +3287,7 @@ void banner_wayland_send_pointer(int action, int x, int y) { /* Called from JNI. Queues a key event. evdev = Linux input keycode (e.g. KEY_A=30); state 1=down 0=up. */ void banner_wayland_send_key(int evdev, int state) { if (g_input_pipe[1] < 0) return; - struct input_msg m = { 1, evdev, state, 0 }; + struct input_msg m = { 1, evdev, state, 0, 0 }; ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); (void)n; } @@ -3094,7 +3295,7 @@ void banner_wayland_send_key(int evdev, int state) { /* Called from JNI on every screen refresh (Choreographer). */ void banner_wayland_vsync(int64_t frame_time_ns) { if (g_input_pipe[1] < 0) return; - struct input_msg m = { 5, (int)(frame_time_ns >> 32), (int)(uint32_t)frame_time_ns, 0 }; + struct input_msg m = { 5, (int)(frame_time_ns >> 32), (int)(uint32_t)frame_time_ns, 0, 0 }; ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); (void)n; } @@ -3104,7 +3305,7 @@ void banner_wayland_vsync(int64_t frame_time_ns) { * 6 = relative motion by a,b in 1/256 pixel (the app's Relative Mouse / captured-mouse path). */ void banner_wayland_send_scene_input(int type, int a, int b) { if (g_input_pipe[1] < 0) return; - struct input_msg m = { type, a, b, 0 }; + struct input_msg m = { type, a, b, 0, 0 }; ssize_t n = write(g_input_pipe[1], &m, sizeof(m)); (void)n; } diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 9698e1cfd2..2125a5c088 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -23,6 +23,7 @@ extern int banner_wayland_run(void); extern void banner_wayland_send_pointer(int action, int x, int y); +extern void banner_wayland_send_touch(int action, int pointer_id, int x, int y); extern void banner_wayland_send_key(int evdev, int state); extern void banner_wayland_send_scene_input(int type, int a, int b); extern void banner_wayland_vsync(int64_t frame_time_ns); @@ -271,6 +272,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendPointer( banner_wayland_send_pointer(action, x, y); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendTouch( + JNIEnv *env, jclass clazz, jint action, jint pointer_id, jint x, jint y) { + banner_wayland_send_touch(action, pointer_id, x, y); +} + /* Inject a key event. evdev = Linux input keycode (KEY_A=30…); state 1=down 0=up. */ JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey( diff --git a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt index 8be97a55ca..c460825a00 100644 --- a/app/src/main/java/com/droiddeck/launcher/HomeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/HomeApp.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher +import android.app.ActivityOptions import android.app.role.RoleManager import android.graphics.Bitmap import android.content.ComponentName @@ -73,11 +74,19 @@ object HomeApp { return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }) } - fun launch(context: Context, app: LaunchableApp) { + fun launch(context: Context, app: LaunchableApp, displayId: Int? = null) { val intent = Intent(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_LAUNCHER) .setComponent(ComponentName(app.packageName, app.className)) - context.startActivity(intent) + if (displayId == null) { + context.startActivity(intent) + return + } + // Keep the target app's task separate from DroidDeck. Without this, Android can put the + // app on top of the caller's task and move the entire task to the chosen display. + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId) + context.startActivity(intent, options.toBundle()) } fun isActiveSteamSession(): Boolean = diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index e587aac8c1..0617fde309 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -4,12 +4,14 @@ import android.Manifest import android.content.Intent import java.io.File import android.content.pm.PackageManager +import android.hardware.display.DisplayManager import android.net.Uri import android.provider.OpenableColumns import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log +import android.view.Display import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts @@ -55,6 +57,8 @@ import com.droiddeck.launcher.files.InAppFilePicker import com.droiddeck.launcher.session.SessionArtifacts import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.GameStorage +import com.droiddeck.launcher.input.SecondScreenDisplay +import com.droiddeck.launcher.input.SecondScreenDisplays /** * The whole app outside a session: is the runtime installed, is there a newer one, frame @@ -105,6 +109,7 @@ class MainActivity : ComponentActivity() { private var phantomWarning by mutableStateOf(null) private var directAudio by mutableStateOf(false) private var clientDirectAudio by mutableStateOf(false) + private var forceFullscreen by mutableStateOf(true) private var mic by mutableStateOf(false) private var linuxRows by mutableStateOf>(emptyList()) /** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */ @@ -170,6 +175,7 @@ class MainActivity : ComponentActivity() { private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO) private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO) + private var backActionsInverted by mutableStateOf(false) private var renderer by mutableStateOf("vulkan") private var gameStorage by mutableStateOf("") private var storageOptions by mutableStateOf>>(emptyList()) @@ -185,6 +191,13 @@ class MainActivity : ComponentActivity() { private var homeAppSelected by mutableStateOf(false) private var defaultHomeLabel by mutableStateOf(null) private var androidApps by mutableStateOf>(emptyList()) + private var secondScreenDisplays by mutableStateOf>(emptyList()) + private lateinit var displayManager: DisplayManager + private val secondScreenDisplayListener = object : DisplayManager.DisplayListener { + override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays() + override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays() + override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays() + } private val homeRoleRequest = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { refreshHomeAppState() @@ -210,7 +223,9 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager theme = SessionPrefs.theme(this) + backActionsInverted = SessionPrefs.backActionsInverted(this) setContent { DroidDeckTheme(theme) { val sm = settingsMode @@ -235,12 +250,15 @@ class MainActivity : ComponentActivity() { isHomeApp = homeAppSelected, defaultHomeLabel = defaultHomeLabel, androidApps = androidApps, + secondScreenDisplays = secondScreenDisplays, packages = packageRows, packageCatalogLoading = catalogLoading, packageBusyId = pkgId, packageStage = pkgStage, packagePercent = pkgPercent, sessionRunning = SessionState.running, + backActionsInverted = backActionsInverted, + buildLabel = BuildConfig.BUILD_LABEL, ), FrontEndActions( onPlay = { startSession(Intent(this, SessionActivity::class.java)) }, @@ -300,7 +318,14 @@ class MainActivity : ComponentActivity() { onPageBack = { settingsMode = null; showPerformance = false; showProtons = false }, onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id }, onHomeApp = { manageHomeApp() }, - onAndroidApp = { app -> launchAndroidApp(app) }, + onAndroidApp = { app, displayId -> launchAndroidApp(app, displayId) }, + onBackActionsInverted = { inverted -> + SessionPrefs.setBackActionsInverted(this, inverted) + backActionsInverted = inverted + }, + onCheckLatestBuild = { + startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/The412Banner/DroidDeck/actions/workflows/build.yml"))) + }, ), page = page, ) @@ -355,6 +380,7 @@ class MainActivity : ComponentActivity() { override fun onResume() { super.onResume() refreshHomeAppState() + refreshSecondScreenDisplays() refresh() // Added games' art (a store lookup for what the folders lack) starts here, not only when // the cog opens. @@ -363,17 +389,35 @@ class MainActivity : ComponentActivity() { if (!busy) Thread({ checkCatalog() }, "catalog").start() } + override fun onStart() { + super.onStart() + displayManager.registerDisplayListener(secondScreenDisplayListener, ui) + refreshSecondScreenDisplays() + } + + override fun onStop() { + displayManager.unregisterDisplayListener(secondScreenDisplayListener) + super.onStop() + } + private fun refreshHomeAppState() { homeAppSelected = HomeApp.isDefault(this) defaultHomeLabel = HomeApp.defaultLabel(this) androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList() } - private fun launchAndroidApp(app: HomeApp.LaunchableApp) { + private fun refreshSecondScreenDisplays() { + if (!::displayManager.isInitialized) return + secondScreenDisplays = SecondScreenDisplays.available(displayManager) + } + + private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) { try { - HomeApp.launch(this, app) + HomeApp.launch(this, app, displayId) } catch (_: Exception) { - android.widget.Toast.makeText(this, "Could not open ${app.label}", android.widget.Toast.LENGTH_SHORT).show() + val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen" + else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId" + android.widget.Toast.makeText(this, "Could not open ${app.label} on $target", android.widget.Toast.LENGTH_SHORT).show() } } @@ -516,8 +560,10 @@ class MainActivity : ComponentActivity() { touchMode = touchMode, suspendPolicy = suspendPolicy, oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null, + backActionsInverted = backActionsInverted, directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null, clientDirectAudio = clientDirectAudio, + forceFullscreen = if (mode == SessionService.MODE_STEAM) forceFullscreen else null, mic = if (mode == SessionService.MODE_STEAM) mic else null, renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null, gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null, @@ -547,8 +593,13 @@ class MainActivity : ComponentActivity() { onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t }, onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy }, onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o }, + onBackActionsInverted = { inverted -> + SessionPrefs.setBackActionsInverted(this, inverted) + backActionsInverted = inverted + }, onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on }, onClientDirectAudio = { on -> SessionPrefs.setClientDirectAudio(this, on); clientDirectAudio = on }, + onForceFullscreen = { on -> SessionPrefs.setForceFullscreen(this, on); forceFullscreen = on }, onMic = { on -> SessionPrefs.setMicEnabled(this, on) mic = on @@ -642,8 +693,10 @@ class MainActivity : ComponentActivity() { touchMode = SessionPrefs.touchMode(this) suspendPolicy = SessionPrefs.suspendPolicy(this, mode) oscMode = SessionPrefs.oscMode(this) + backActionsInverted = SessionPrefs.backActionsInverted(this) directAudio = SessionPrefs.directAudio(this) clientDirectAudio = SessionPrefs.clientDirectAudio(this) + forceFullscreen = SessionPrefs.forceFullscreen(this) mic = SessionPrefs.micEnabled(this) renderer = SessionPrefs.desktopRenderer(this) gameStorage = SessionPrefs.gameStorage(this) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index a2d31962e2..5a36bc60b2 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -8,9 +8,12 @@ import android.os.Bundle import android.os.Environment import android.os.Handler import android.os.Looper +import android.os.SystemClock import android.util.Log +import android.view.InputDevice import android.view.KeyEvent import android.view.MotionEvent +import android.view.ViewConfiguration import android.view.Display import android.view.SurfaceHolder import android.view.SurfaceView @@ -35,6 +38,7 @@ import com.droiddeck.launcher.input.OnScreenControls import com.droiddeck.launcher.input.PadBridge import com.droiddeck.launcher.input.PointerGestures import com.droiddeck.launcher.input.SecondScreenDisplay +import com.droiddeck.launcher.input.SecondScreenDisplays import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.input.TouchpadGestures import com.droiddeck.launcher.runtime.LinuxRuntime @@ -58,6 +62,7 @@ import com.droiddeck.launcher.ui.DroidDeckTheme import com.droiddeck.launcher.wayland.CompositorHost import com.droiddeck.launcher.wayland.WaylandCompositor import java.io.File +import kotlin.math.abs /** * The session's screen: our Wayland compositor presenting onto this activity's Surface, and the @@ -72,25 +77,54 @@ import java.io.File */ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private lateinit var surfaceView: SurfaceView + private lateinit var sessionOverlay: ComposeView private lateinit var loading: LoadingState private lateinit var hud: PerfHud private var padBridge: PadBridge? = null private var onScreenControls: OnScreenControls? = null private var keyboard: KeyboardHost? = null private var watching = true - private lateinit var gestures: PointerGestures private lateinit var touchpad: TouchpadGestures private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO) private var cursorPos by mutableStateOf(androidx.compose.ui.geometry.Offset(-100f, -100f)) private var cursorVisible by mutableStateOf(false) private val cursorHide = Runnable { cursorVisible = false } private val uiHandler = Handler(Looper.getMainLooper()) + private var pendingBackAction: Runnable? = null + private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN + private var drawerDirectionDownTime = 0L + private var drawerDirectionDeviceId = -1 + private var drawerDirectionRepeatCount = 0 + private val drawerFirstRepeatDelayMs = ViewConfiguration.getKeyRepeatTimeout().toLong() + private val drawerSlowRepeatIntervalMs = maxOf( + ViewConfiguration.getKeyRepeatDelay().toLong(), DRAWER_SLOW_REPEAT_FLOOR_MS, + ) + private val drawerDirectionRepeat = object : Runnable { + override fun run() { + if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) return + + val now = SystemClock.uptimeMillis() + val heldMs = now - drawerDirectionDownTime + val progress = ((heldMs - drawerFirstRepeatDelayMs).toFloat() / DRAWER_REPEAT_ACCELERATION_MS) + .coerceIn(0f, 1f) + val intervalMs = ( + drawerSlowRepeatIntervalMs + + (DRAWER_FAST_REPEAT_INTERVAL_MS - drawerSlowRepeatIntervalMs) * progress + ).toLong() + + dispatchDrawerKey(KeyEvent.ACTION_DOWN, ++drawerDirectionRepeatCount, now) + uiHandler.postDelayed(this, intervalMs) + } + } + private val resumeKeysDown = mutableSetOf>() // Compose reads these; the activity writes them. private var drawerOpen by mutableStateOf(false) + private var backActionsInverted by mutableStateOf(false) /** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */ private var pcKeyboardOpen by mutableStateOf(false) private var hudOn by mutableStateOf(true) + private var fillScreen by mutableStateOf(true) private var frameGenLabel by mutableStateOf("Off") private var frameGenEngine by mutableStateOf(FrameGen.ENGINE_OFF) private var frameGenMultiplier by mutableStateOf(2) @@ -147,7 +181,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { padBridge = bridge onScreenControls = OnScreenControls(this, bridge).also { root.addView(it) } keyboard = KeyboardHost(this).also { root.addView(it) } - gestures = PointerGestures(PointerGestures.slop(this), pointerListener) touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener) // One arrow, ours: Android draws a system pointer for a mouse over any window, and the // session already draws the pointer it is sent. @@ -175,14 +208,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // One Compose layer for every menu and overlay. Touches nothing in it consumes fall // through to the pad and the game underneath. - root.addView(ComposeView(this).apply { + sessionOverlay = ComposeView(this).apply { + isFocusable = true + isFocusableInTouchMode = true setContent { DroidDeckTheme { CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density) if (hud.text.isNotEmpty()) HudText(hud.text) if (loading.visible) LoadingOverlay(loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended) // Opening the drawer takes the controller away from the game: release its pad. - androidx.compose.runtime.LaunchedEffect(drawerOpen) { if (drawerOpen) padBridge?.releaseAll() } + androidx.compose.runtime.LaunchedEffect(drawerOpen) { + if (drawerOpen) { + padBridge?.releaseAll() + androidx.compose.runtime.withFrameNanos { } + val requested = sessionOverlay.requestFocus() + Log.i(TAG, "drawer root focus requested=$requested focused=${sessionOverlay.hasFocus()}") + } else { + releaseDrawerDirection() + } + } // The PC keyboard takes it too, for moving over the keys; the drawer opens over it. androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) padBridge?.releaseAll() } if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard( @@ -197,6 +241,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { isHomeApp = isHomeApp, androidApps = androidApps, hudOn = hudOn, + fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null, frameGenEngine = frameGenEngine, frameGenMultiplier = frameGenMultiplier, lsfgReady = LsfgNative.isInstalled(this@SessionActivity), oscMode = oscMode, touchMode = touchMode, @@ -206,6 +251,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { secondScreenDisplays = secondScreenDisplays, selectedSecondScreenDisplay = selectedSecondScreenDisplay, onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() }, + onFillScreen = { on -> SessionPrefs.setForceFullscreen(this@SessionActivity, on); fillScreen = on }, onFrameGenPick = { engine, multiplier -> FrameGen.set(this@SessionActivity, engine, multiplier) readPrefs() @@ -214,22 +260,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() }, onHardwareKeyboard = { drawerOpen = false; pcKeyboardOpen = !pcKeyboardOpen }, onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null, - onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ - drawerOpen = false - padBridge?.triggerQam() - }) else null, + onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null, + backActionsInverted = backActionsInverted, + onBackActionsInverted = { inverted -> + SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted) + backActionsInverted = inverted + }, onOsc = { v -> SessionPrefs.setOscMode(this@SessionActivity, v); readPrefs(); updateOnScreenControls() }, onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() }, onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() }, onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() }, onSecondScreenMode = ::selectSecondScreenMode, onSecondScreenDisplay = ::selectSecondScreenDisplay, - onLaunchAndroidApp = { app -> + onLaunchAndroidApp = { app, displayId -> drawerOpen = false try { - HomeApp.launch(this@SessionActivity, app) + HomeApp.launch(this@SessionActivity, app, displayId) } catch (_: Exception) { - Toast.makeText(this@SessionActivity, "Could not open ${app.label}", Toast.LENGTH_SHORT).show() + val target = if (displayId == null || displayId == Display.DEFAULT_DISPLAY) "the primary screen" + else secondScreenDisplays.firstOrNull { it.id == displayId }?.label ?: "display $displayId" + Toast.makeText(this@SessionActivity, "Could not open ${app.label} on $target", Toast.LENGTH_SHORT).show() } }, onBackground = { drawerOpen = false; moveTaskToBack(true) }, @@ -241,7 +291,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } } - }) + } + root.addView(sessionOverlay) setContentView(root) handleHomeGuideIntent(intent) @@ -254,13 +305,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } SessionState.endListener = endListener - // Back opens the drawer (and closes it again). Leaving the session running in the - // background and ending it are both actions in there, so neither can happen by accident - // from a button a game might also be reading. + // A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord. + // The single action waits out the double-press window so the two actions stay distinct. onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { // The PC keyboard closes first (B on a controller), then Back is the drawer again. - if (pcKeyboardOpen && !drawerOpen) pcKeyboardOpen = false else drawerOpen = !drawerOpen + when { + drawerOpen -> drawerOpen = false + pcKeyboardOpen -> pcKeyboardOpen = false + else -> routeBackAction() + } } }) watchSession() @@ -279,6 +333,32 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { }, 90) } + private fun triggerSteamQam() { + drawerOpen = false + padBridge?.triggerQam() + } + + private fun routeBackAction() { + pendingBackAction?.let { pending -> + uiHandler.removeCallbacks(pending) + pendingBackAction = null + performBackAction(double = true) + return + } + val pending = Runnable { + pendingBackAction = null + performBackAction(double = false) + } + pendingBackAction = pending + uiHandler.postDelayed(pending, BACK_DOUBLE_PRESS_TIMEOUT_MS) + } + + private fun performBackAction(double: Boolean) { + val isSteam = SessionState.mode == SessionService.MODE_STEAM + val opensQam = isSteam && (double xor backActionsInverted) + if (opensQam) triggerSteamQam() else drawerOpen = !drawerOpen + } + private fun handleHomeGuideIntent(incoming: Intent?) { if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return incoming.action = null @@ -288,6 +368,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun readPrefs() { hudOn = SessionPrefs.hudEnabled(this) + fillScreen = SessionPrefs.forceFullscreen(this) touchMode = SessionPrefs.touchMode(this) frameGenLabel = FrameGen.label(this) frameGenEngine = FrameGen.engine(this) @@ -295,6 +376,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { fexPreset = SessionPrefs.fexPreset(this) oscMode = SessionPrefs.oscMode(this) shapeMode = SessionPrefs.shapeMode(this) + backActionsInverted = SessionPrefs.backActionsInverted(this) } // ── Compositor ────────────────────────────────────────────────────────────────────────── @@ -622,10 +704,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> return super.dispatchKeyEvent(event) } - // With the drawer open the controller drives the drawer, not the game: Android's own - // handling moves focus with the d-pad and stick, and its fallbacks make A select and B Back - // (which closes the drawer) - the same as on the app's main screen. - if ((drawerOpen || pcKeyboardOpen) && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchKeyEvent(event) + if (drawerOpen) { + val handled = super.dispatchKeyEvent(event) + if (event.action == KeyEvent.ACTION_DOWN) { + Log.i(TAG, "drawer key=${KeyEvent.keyCodeToString(event.keyCode)} handled=$handled viewFocused=${sessionOverlay.hasFocus()}") + } + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK) { + if (!handled && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) drawerOpen = false + releaseDrawerDirection() + } + return true + } + val fromController = PadBridge.isFromController(event.device) + val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START + val resumeKeyId = event.deviceId to event.keyCode + if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) { + if (event.action == KeyEvent.ACTION_DOWN) { + resumeKeysDown.add(resumeKeyId) + if (event.repeatCount == 0 && SessionState.suspended) SessionService.resume(this) + } else if (event.action == KeyEvent.ACTION_UP) { + resumeKeysDown.remove(resumeKeyId) + } + return true + } + if (drawerOpen) { + if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) { + if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) drawerOpen = false + releaseDrawerDirection() + return true + } + return super.dispatchKeyEvent(event) + } + if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchKeyEvent(event) if (event.keyCode != KeyEvent.KEYCODE_BACK && padBridge?.onKeyEvent(event) == true) return true // A hardware keyboard, forwarded to the compositor's wl_keyboard. Back is left to the // activity, which opens the drawer. @@ -667,18 +777,93 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { - if ((drawerOpen || pcKeyboardOpen) && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event) + if (drawerOpen && event.device != null && PadBridge.isFromController(event.device)) { + if (event.actionMasked == MotionEvent.ACTION_MOVE && + event.isFromSource(InputDevice.SOURCE_JOYSTICK) + ) { + dispatchDrawerDirection(event) + } + return true + } + if (drawerDirectionKey != KeyEvent.KEYCODE_UNKNOWN) releaseDrawerDirection() + if (pcKeyboardOpen && event.device != null && PadBridge.isFromController(event.device)) return super.dispatchGenericMotionEvent(event) if (padBridge?.onMotionEvent(event) == true) return true if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true return super.dispatchGenericMotionEvent(event) } - /** - * The pointer. Touch goes through [PointerGestures] (tap, hold, drag, two-finger scroll); a - * mouse arrives with real buttons and a wheel and is forwarded as it is. Every position is - * mapped through the letterboxed rectangle into the compositor's fixed 1920x1080 pointer - * space, and the arrow is drawn where the app last sent the pointer. - */ + private fun dispatchDrawerDirection(event: MotionEvent) { + val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X) + val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y) + val hatActive = maxOf(abs(hatX), abs(hatY)) >= DRAWER_HAT_THRESHOLD + val x = if (hatActive) hatX else centeredStickAxis(event, MotionEvent.AXIS_X) + val y = if (hatActive) hatY else centeredStickAxis(event, MotionEvent.AXIS_Y) + val directionThreshold = if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) { + DRAWER_STICK_ENTER_THRESHOLD + } else { + DRAWER_STICK_EXIT_THRESHOLD + } + val previousWasHorizontal = drawerDirectionKey == KeyEvent.KEYCODE_DPAD_LEFT || + drawerDirectionKey == KeyEvent.KEYCODE_DPAD_RIGHT + val horizontalWins = if (previousWasHorizontal) { + abs(x) >= abs(y) * DRAWER_ACTIVE_DIRECTION_MARGIN + } else { + abs(x) > abs(y) * DRAWER_DIRECTION_MARGIN + } + val keyCode = when { + maxOf(abs(x), abs(y)) < directionThreshold -> KeyEvent.KEYCODE_UNKNOWN + horizontalWins && x < 0f -> KeyEvent.KEYCODE_DPAD_LEFT + horizontalWins -> KeyEvent.KEYCODE_DPAD_RIGHT + y < 0f -> KeyEvent.KEYCODE_DPAD_UP + else -> KeyEvent.KEYCODE_DPAD_DOWN + } + val now = SystemClock.uptimeMillis() + if (keyCode == drawerDirectionKey) return + + Log.i(TAG, "drawer axis source=${event.source} x=$x y=$y direction=$keyCode") + releaseDrawerDirection() + if (keyCode == KeyEvent.KEYCODE_UNKNOWN) return + + drawerDirectionKey = keyCode + drawerDirectionDeviceId = event.deviceId + drawerDirectionDownTime = now + drawerDirectionRepeatCount = 0 + dispatchDrawerKey(KeyEvent.ACTION_DOWN, 0, now) + uiHandler.postDelayed(drawerDirectionRepeat, drawerFirstRepeatDelayMs) + } + + /** Use Android's per-device flat region, then rescale the remaining stick travel to 0..1. */ + private fun centeredStickAxis(event: MotionEvent, axis: Int): Float { + val value = event.getAxisValue(axis) + val flat = (event.device?.getMotionRange(axis, event.source)?.flat ?: 0f) + .coerceIn(0f, 0.95f) + val magnitude = abs(value) + if (magnitude <= flat) return 0f + + val centered = ((magnitude - flat) / (1f - flat)).coerceIn(0f, 1f) + return if (value < 0f) -centered else centered + } + + private fun releaseDrawerDirection() { + uiHandler.removeCallbacks(drawerDirectionRepeat) + if (drawerDirectionKey == KeyEvent.KEYCODE_UNKNOWN) return + dispatchDrawerKey(KeyEvent.ACTION_UP, 0, SystemClock.uptimeMillis()) + drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN + drawerDirectionDeviceId = -1 + drawerDirectionRepeatCount = 0 + } + + private fun dispatchDrawerKey(action: Int, repeatCount: Int, eventTime: Long) { + val event = KeyEvent( + drawerDirectionDownTime, eventTime, action, drawerDirectionKey, + repeatCount, 0, drawerDirectionDeviceId, 0, 0, InputDevice.SOURCE_DPAD, + ) + if (action == KeyEvent.ACTION_DOWN && repeatCount == 0) { + Log.i(TAG, "drawer synthetic key=${KeyEvent.keyCodeToString(drawerDirectionKey)} viewFocused=${sessionOverlay.hasFocus()}") + } + super.dispatchKeyEvent(event) + } + private val pointerListener = object : PointerGestures.Listener { override fun onMove(x: Float, y: Float) = movePointer(x, y) override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) { @@ -718,14 +903,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun refreshSecondScreenDisplays() { if (!::displayManager.isInitialized) return val primaryId = display?.displayId ?: windowManager.defaultDisplay.displayId - val candidates = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION) - .asSequence() - .filter { it.isValid && it.displayId != primaryId && (it.flags and Display.FLAG_PRESENTATION) != 0 } - .map { target -> - val mode = target.mode - SecondScreenDisplay(target.displayId, "${target.name} · ${mode.physicalWidth}×${mode.physicalHeight}") - } - .toList() + val candidates = SecondScreenDisplays.available(displayManager, primaryId) val oldIds = secondScreenDisplays.map { it.id }.toSet() secondScreenDisplays = candidates val newIds = candidates.map { it.id }.toSet() @@ -786,6 +964,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onQam = { if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam() }, + onClose = { selectSecondScreenMode(SecondScreenMode.NONE) }, ) secondScreenPresentation = presentation } @@ -846,7 +1025,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } return touchpad.onTouch(event) } - return gestures.onTouch(event) + val rect = drawnRect() ?: return false + fun sendTouch(action: Int, index: Int) { + val x = ((event.getX(index) - rect.left) / rect.width()).coerceIn(0f, 1f) + val y = ((event.getY(index) - rect.top) / rect.height()).coerceIn(0f, 1f) + WaylandCompositor.nativeSendTouch(action, event.getPointerId(index), (x * 1919f).toInt(), (y * 1079f).toInt()) + } + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> sendTouch(0, event.actionIndex) + MotionEvent.ACTION_MOVE -> for (index in 0 until event.pointerCount) sendTouch(1, index) + MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> sendTouch(2, event.actionIndex) + MotionEvent.ACTION_CANCEL -> WaylandCompositor.nativeSendTouch(3, -1, 0, 0) + else -> return false + } + return true } /** A mouse: hover moves, buttons press, the wheel scrolls. Android sends buttons as touch @@ -946,6 +1138,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onPause() { (getSystemService(INPUT_SERVICE) as? InputManager)?.unregisterInputDeviceListener(deviceListener) + releaseDrawerDirection() // A button held when the app goes away would stay held in the ring for the whole session. onScreenControls?.releaseAll() keyboard?.takeIf { it.shown }?.hide() @@ -980,6 +1173,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // Deliberately does NOT end the session: this activity can be destroyed while the user is // in another app, and the whole point of the service is that Steam survives that. watching = false + releaseDrawerDirection() + pendingBackAction?.let(uiHandler::removeCallbacks) + pendingBackAction = null closeSecondScreen(reset = true) if (::hud.isInitialized) hud.stop() padBridge?.stop() @@ -996,6 +1192,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { companion object { private const val TAG = "SessionActivity" + private const val BACK_DOUBLE_PRESS_TIMEOUT_MS = 500L + private const val DRAWER_HAT_THRESHOLD = 0.5f + private const val DRAWER_STICK_ENTER_THRESHOLD = 0.55f + private const val DRAWER_STICK_EXIT_THRESHOLD = 0.35f + private const val DRAWER_DIRECTION_MARGIN = 1.15f + private const val DRAWER_ACTIVE_DIRECTION_MARGIN = 0.85f + private const val DRAWER_SLOW_REPEAT_FLOOR_MS = 240L + private const val DRAWER_FAST_REPEAT_INTERVAL_MS = 90L + private const val DRAWER_REPEAT_ACCELERATION_MS = 1_400L /** Compositor scale modes (Container.FULLSCREEN_* values): 1 = fit with bars, centred. */ private const val SCALE_FIT = 1 private const val ALIGN_CENTER = 0 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 060efb5b93..498eb1fd24 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -149,6 +149,7 @@ object DeviceReport { k("Skip xalia", SessionPrefs.noXalia(context)) k("proot without seccomp", SessionPrefs.prootNoSeccomp(context)) k("DirectAudio for games", SessionPrefs.directAudio(context)) + k("Stretch games to fill", SessionPrefs.forceFullscreen(context)) k("Client audio", if (SessionPrefs.clientDirectAudio(context)) "DirectAudio" else "classic") k("Microphone", SessionPrefs.micEnabled(context)) k("On-screen controls", SessionPrefs.oscMode(context)) diff --git a/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt b/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt new file mode 100644 index 0000000000..c5bbef88e7 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt @@ -0,0 +1,243 @@ +package com.droiddeck.launcher.files + +import android.content.Context +import android.content.pm.ProviderInfo +import android.content.res.AssetFileDescriptor +import android.database.Cursor +import android.database.MatrixCursor +import android.graphics.Point +import android.os.CancellationSignal +import android.os.ParcelFileDescriptor +import android.provider.DocumentsContract.Document +import android.provider.DocumentsContract.Root +import android.provider.DocumentsProvider +import android.webkit.MimeTypeMap +import com.droiddeck.launcher.R +import java.io.File +import java.io.FileNotFoundException +import java.io.IOException +import java.nio.file.FileVisitResult +import java.nio.file.Files +import java.nio.file.LinkOption +import java.nio.file.Path +import java.nio.file.SimpleFileVisitor +import java.nio.file.attribute.BasicFileAttributes + +/** + * The app's own data folder (the Linux runtime, settings, logs) in Android's file picker, under the + * app's name beside the phone's storage - what MT Manager's "documents provider" injection does, as + * part of the app. Only the system's documents UI can bind it (MANAGE_DOCUMENTS); another app sees + * a file only when the user picks it there. + * + * A document id is the file's absolute path, and nothing outside the data folder is ever handed out + * or accepted: every id is resolved and checked to lie inside it. + */ +class AppFilesProvider : DocumentsProvider() { + private lateinit var base: File + private lateinit var baseCanonical: String + + override fun attachInfo(context: Context, info: ProviderInfo) { + super.attachInfo(context, info) + base = context.dataDir + baseCanonical = base.canonicalPath + } + + override fun onCreate() = true + + override fun queryRoots(projection: Array?): Cursor { + val ctx = context!! + val result = MatrixCursor(projection ?: ROOT_COLUMNS) + result.newRow().apply { + add(Root.COLUMN_ROOT_ID, ROOT_ID) + add(Root.COLUMN_DOCUMENT_ID, base.absolutePath) + add(Root.COLUMN_TITLE, titleFor(ctx)) + add(Root.COLUMN_SUMMARY, null) + add(Root.COLUMN_FLAGS, Root.FLAG_SUPPORTS_CREATE or Root.FLAG_SUPPORTS_SEARCH or Root.FLAG_SUPPORTS_IS_CHILD) + add(Root.COLUMN_MIME_TYPES, "*/*") + add(Root.COLUMN_AVAILABLE_BYTES, base.freeSpace) + add(Root.COLUMN_ICON, R.mipmap.ic_launcher) + } + return result + } + + override fun queryDocument(documentId: String, projection: Array?): Cursor = + MatrixCursor(projection ?: DOCUMENT_COLUMNS).also { addRow(it, fileFor(documentId)) } + + override fun queryChildDocuments(parentDocumentId: String, projection: Array?, sortOrder: String?): Cursor { + val result = MatrixCursor(projection ?: DOCUMENT_COLUMNS) + // A link in the runtime that leads out of the data folder (/etc/localtime and the like) is + // left out rather than listed as something that cannot be opened. + fileFor(parentDocumentId).listFiles()?.filter { inside(it) }?.forEach { addRow(result, it) } + return result + } + + override fun openDocument(documentId: String, mode: String, signal: CancellationSignal?): ParcelFileDescriptor = + ParcelFileDescriptor.open(fileFor(documentId), ParcelFileDescriptor.parseMode(mode)) + + override fun openDocumentThumbnail(documentId: String, sizeHint: Point?, signal: CancellationSignal?): AssetFileDescriptor { + val file = fileFor(documentId) + return AssetFileDescriptor(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY), 0, file.length()) + } + + override fun createDocument(parentDocumentId: String, mimeType: String, displayName: String): String { + val parent = fileFor(parentDocumentId) + val name = displayName.substringAfterLast('/') + var file = File(parent, name) + var n = 2 + while (file.exists()) file = File(parent, "$name (${n++})") + val made = try { + if (mimeType == Document.MIME_TYPE_DIR) file.mkdir() else file.createNewFile() + } catch (e: IOException) { + false + } + if (!made) throw FileNotFoundException("could not create ${file.path}") + return file.absolutePath + } + + override fun deleteDocument(documentId: String) { + val file = fileFor(documentId) + if (file.absolutePath == base.absolutePath) throw FileNotFoundException("the app folder itself is not deleted") + try { + deleteTree(file.toPath()) + } catch (e: IOException) { + throw FileNotFoundException("could not delete $documentId: ${e.message}") + } + } + + /** + * Deletes a file or a folder and what is in it without ever following a link: the runtime holds + * links to places outside it, and deleting a folder must remove the link, not what it points at. + */ + private fun deleteTree(root: Path) { + if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) { + Files.delete(root) + return + } + Files.walkFileTree(root, object : SimpleFileVisitor() { + override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { + Files.delete(file) + return FileVisitResult.CONTINUE + } + + override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult { + if (exc != null) throw exc + Files.delete(dir) + return FileVisitResult.CONTINUE + } + }) + } + + override fun removeDocument(documentId: String, parentDocumentId: String) = deleteDocument(documentId) + + override fun renameDocument(documentId: String, displayName: String): String { + val file = fileFor(documentId) + val target = File(file.parentFile, displayName.substringAfterLast('/')) + if (target.exists() || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId") + return target.absolutePath + } + + override fun moveDocument(sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String): String { + val source = fileFor(sourceDocumentId) + val targetParent = fileFor(targetParentDocumentId) + if (!targetParent.isDirectory) throw FileNotFoundException("$targetParentDocumentId is not a folder") + val target = File(targetParent, source.name) + if (target.exists() || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId") + return target.absolutePath + } + + override fun getDocumentType(documentId: String): String = mimeOf(fileFor(documentId)) + + override fun isChildDocument(parentDocumentId: String, documentId: String): Boolean { + val parent = runCatching { fileFor(parentDocumentId).absolutePath }.getOrNull() ?: return false + val child = runCatching { fileFor(documentId).absolutePath }.getOrNull() ?: return false + return child == parent || child.startsWith("$parent/") + } + + override fun querySearchDocuments(rootId: String, query: String, projection: Array?): Cursor { + val result = MatrixCursor(projection ?: DOCUMENT_COLUMNS) + val needle = query.lowercase() + val pending = ArrayDeque(listOf(base)) + var visited = 0 + // The runtime is tens of thousands of files: a bounded walk, not the whole tree. + while (pending.isNotEmpty() && result.count < 50 && visited++ < 20000) { + val f = pending.removeFirst() + if (!inside(f)) continue + if (f.isDirectory) f.listFiles()?.let { pending.addAll(it) } + else if (f.name.lowercase().contains(needle)) addRow(result, f) + } + return result + } + + /** The file an id names, when it exists and lies inside the data folder (links followed). */ + private fun fileFor(documentId: String): File { + val f = File(documentId) + if (!f.isAbsolute || !inside(f)) throw FileNotFoundException("$documentId is outside the app's files") + if (!f.exists()) throw FileNotFoundException("$documentId not found") + return f + } + + private fun inside(f: File): Boolean { + // The folder's own entries are listed as they are; a link is judged by where it leads. + val abs = f.absoluteFile.normalize().path + if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false + val real = runCatching { f.canonicalPath }.getOrNull() ?: return false + return real == baseCanonical || real.startsWith("$baseCanonical/") + } + + private fun addRow(result: MatrixCursor, file: File) { + var flags = 0 + if (file.isDirectory) { + if (file.canWrite()) flags = flags or Document.FLAG_DIR_SUPPORTS_CREATE + } else if (file.canWrite()) { + flags = flags or Document.FLAG_SUPPORTS_WRITE + } + if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true) { + flags = flags or Document.FLAG_SUPPORTS_DELETE or Document.FLAG_SUPPORTS_RENAME or + Document.FLAG_SUPPORTS_MOVE or Document.FLAG_SUPPORTS_REMOVE + } + val mime = mimeOf(file) + if (mime.startsWith("image/")) flags = flags or Document.FLAG_SUPPORTS_THUMBNAIL + result.newRow().apply { + add(Document.COLUMN_DOCUMENT_ID, file.absolutePath) + add(Document.COLUMN_DISPLAY_NAME, if (file.absolutePath == base.absolutePath) titleFor(context!!) else file.name) + add(Document.COLUMN_SIZE, if (file.isDirectory) null else file.length()) + add(Document.COLUMN_MIME_TYPE, mime) + add(Document.COLUMN_LAST_MODIFIED, file.lastModified()) + add(Document.COLUMN_FLAGS, flags) + } + } + + private fun mimeOf(file: File): String { + if (file.isDirectory) return Document.MIME_TYPE_DIR + val ext = file.extension.lowercase() + return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) ?: "application/octet-stream" + } + + companion object { + private const val ROOT_ID = "app" + + private val ROOT_COLUMNS = arrayOf( + Root.COLUMN_ROOT_ID, Root.COLUMN_MIME_TYPES, Root.COLUMN_FLAGS, Root.COLUMN_ICON, + Root.COLUMN_TITLE, Root.COLUMN_SUMMARY, Root.COLUMN_DOCUMENT_ID, Root.COLUMN_AVAILABLE_BYTES, + ) + private val DOCUMENT_COLUMNS = arrayOf( + Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE, Document.COLUMN_DISPLAY_NAME, + Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE, + ) + + /** + * The name in the picker. The same app ships under other package names (for the performance + * modes some phones give only named apps); each says which it is, so four installs are not + * four identical "DroidDeck" entries. + */ + fun titleFor(context: Context): String { + val name = context.getString(R.string.app_name) + return when (context.packageName) { + "com.tencent.ig" -> "$name PUBG" + "com.antutu.benchmark.full" -> "$name AnTuTu" + "com.ludashi.benchmark" -> "$name Ludashi" + else -> name + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt index 0337e9d940..e255d314b6 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt @@ -104,7 +104,9 @@ object Library { // The root itself only one deep, for a file left loose there. val systemDirs = romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() in spec.folders }.orEmpty().toList() val dirs = LinkedHashSet() - for (top in systemDirs) top.walkTopDown().maxDepth(3).filter { it.isDirectory }.forEach { dirs.add(it) } + // A BIOS folder holds the console's firmware, not games (psx/bios/SCPH1001.BIN). + for (top in systemDirs) top.walkTopDown().maxDepth(3).onEnter { it.name.lowercase() !in firmwareFolders } + .filter { it.isDirectory }.forEach { dirs.add(it) } dirs.add(romsRoot) // ...and not into another system's folder: a PS3 .iso in ps3/ is not a PS2 game. romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() !in systemFolders }?.forEach { dirs.add(it) } @@ -117,10 +119,15 @@ object Library { art = File(dir, "PS3_GAME/ICON0.PNG").takeIf { it.isFile })) continue } - dir.listFiles()?.sortedBy { it.name.lowercase() }?.forEach { f -> + val files = dir.listFiles()?.sortedBy { it.name.lowercase() }.orEmpty() + // A disc sheet (.cue, .gdi) names its track files and a playlist (.m3u) its + // discs: the sheet is the game, what it names is part of it. A .bin beside a + // .cue of the same name is a track even when the sheet can't be read. + val parts = files.filter { it.isFile && it.extension.lowercase() in sheetExts }.flatMap(::sheetParts).toSet() + files.forEach { f -> val ext = f.extension.lowercase() - // A .bin beside a .cue is a track, not a game. - if (f.isFile && ext in spec.exts && !(ext == "bin" && File(dir, f.nameWithoutExtension + ".cue").isFile)) { + if (f.isFile && ext in spec.exts && f.name.lowercase() !in parts && + !(ext == "bin" && File(dir, f.nameWithoutExtension + ".cue").isFile)) { val rel = f.relativeTo(romsRoot).path games.add(Rom(displayTitle(f.nameWithoutExtension.removeSuffix(".dec")), f, "/root/ROMs/$rel", spec.id)) } @@ -134,6 +141,25 @@ object Library { } } + private val firmwareFolders = setOf("bios", "firmware") + private val sheetExts = setOf("cue", "gdi", "m3u") + + /** The file names (lower case) a .cue, .gdi or .m3u refers to, from its own folder. */ + private fun sheetParts(sheet: File): List = runCatching { + if (sheet.length() > 64 * 1024) return emptyList() + sheet.readLines().mapNotNull { line -> + val t = line.trim() + when (sheet.extension.lowercase()) { + // FILE "Tekken 3 (USA) (Track 1).bin" BINARY + "cue" -> Regex("^FILE\\s+\"([^\"]+)\"", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1) + ?: Regex("^FILE\\s+(\\S+)", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1) + // 1 0 4 2352 "track01.bin" 0 / 1 0 4 2352 track01.bin 0 + "gdi" -> Regex("\"([^\"]+)\"").find(t)?.groupValues?.get(1) ?: t.split(Regex("\\s+")).getOrNull(4) + else -> t.takeIf { it.isNotEmpty() && !it.startsWith("#") } + } + }.map { File(it.replace('\\', '/')).name.lowercase() } + }.getOrDefault(emptyList()) + /** * What RPCS3 has installed on its own HDD - packages (PSN games) land in dev_hdd0/game/ * with a PARAM.SFO for the title and an EBOOT to boot - as RPCS3's own file list would show @@ -191,6 +217,8 @@ object Library { // Straight into the game in its controller-driven full-screen UI (first-time setup there // too), and gone when the game is quit from its pause menu (guide button): -batch. "armsx2" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath) + // DuckStation shares PCSX2's flags (src/duckstation-qt/qthost.cpp): the same launch and exit. + "duckstation" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath) "dolphin" -> listOf("-e", guestPath) "cemu" -> listOf("-g", guestPath) else -> listOf(guestPath) diff --git a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt index 86daa46204..85fc94ca8c 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt @@ -1,5 +1,8 @@ package com.droiddeck.launcher.input +import android.hardware.display.DisplayManager +import android.view.Display + /** The control surface shown on a secondary Android display during a Linux session. */ enum class SecondScreenMode(val id: String, val label: String) { NONE("none", "None"), @@ -8,3 +11,19 @@ enum class SecondScreenMode(val id: String, val label: String) { } data class SecondScreenDisplay(val id: Int, val label: String) + +/** The presentation-capable displays shared by the session controls and Android app launcher. */ +object SecondScreenDisplays { + fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List = + displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION) + .asSequence() + .filter { it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0 } + .map { target -> + val mode = target.mode + SecondScreenDisplay( + target.displayId, + "${target.name} · ${mode.physicalWidth}×${mode.physicalHeight}", + ) + } + .toList() +} 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 a2c1dbe772..3498e525c2 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -13,6 +13,12 @@ object SessionPrefs { const val OSC_STEAM_QAM = "steam-qam" const val OSC_NEVER = "never" + const val BACK_MENU_THEN_QAM = "1: menu 2: QAM" + const val BACK_QAM_THEN_MENU = "1: QAM 2: menu" + + fun backActionsOrder(inverted: Boolean): String = + if (inverted) BACK_QAM_THEN_MENU else BACK_MENU_THEN_QAM + private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE) fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean("hud", true) @@ -21,6 +27,13 @@ object SessionPrefs { prefs(context).edit().putBoolean("hud", on).apply() } + /** When enabled, a single Back opens Steam QAM and a double Back opens the session menu. */ + fun backActionsInverted(context: Context): Boolean = prefs(context).getBoolean("backActionsInverted", false) + + fun setBackActionsInverted(context: Context, inverted: Boolean) { + prefs(context).edit().putBoolean("backActionsInverted", inverted).apply() + } + const val TOUCH_AUTO = "auto" const val TOUCH_PAD = "touchpad" const val TOUCH_DIRECT = "direct" @@ -87,6 +100,32 @@ object SessionPrefs { prefs(context).edit().putBoolean("clientDirectAudio", on).apply() } + /** + * Steam only: gamescope makes every game window the size of the screen. A game that resizes + * its own window when it loses focus (FlatOut) otherwise comes back smaller, drawn in a + * corner; a game that sets its own resolution and never looks at its window again (Quake 3) + * instead draws small in the bottom-left of the stretched one. On unless turned off. + */ + fun forceFullscreen(context: Context): Boolean = prefs(context).getBoolean("forceFullscreen", true) + + fun setForceFullscreen(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("forceFullscreen", on).apply() + writeForceFullscreenFlag(context) + } + + /** + * The same choice as a file the running session watches, so the drawer can change it live: + * the session hands every change to gamescope, which reads GAMESCOPE_FORCE_WINDOWS_FULLSCREEN + * off its root window whenever it changes. Written again at every session start so a file left + * by an earlier session never disagrees with the setting. + */ + fun writeForceFullscreenFlag(context: Context) { + runCatching { + java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.droiddeck-fill") + .writeText(if (forceFullscreen(context)) "1\n" else "0\n") + } + } + /** * DirectAudio for games: their Wine audio driver talks to the relay helper on this side. On * unless the user turned it off. 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 830cbe71be..ec15c5c2c6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -304,6 +304,10 @@ class SessionService : Service() { if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1") if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0")) if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this)) + if (SessionState.mode == MODE_STEAM) { + guest.add("BL_GAMESCOPE_FORCE_FULLSCREEN=" + (if (SessionPrefs.forceFullscreen(this)) "1" else "0")) + SessionPrefs.writeForceFullscreenFlag(this) + } // Proton's own gate for its xalia helper (its `proton` script reads this, and sets // XALIA_SUPPORTED_ONLY itself otherwise). Off by default: xalia is Valve's, and on a device // whose seccomp answers its syscalls normally there is no reason to take it away. 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 d37e689638..0d355d5d93 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -1,8 +1,18 @@ package com.droiddeck.launcher.ui +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.foundation.focusGroup +import androidx.compose.ui.focus.FocusDirection +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.onFocusChanged import android.graphics.Bitmap import android.os.Build import android.provider.Settings +import android.view.Display import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility @@ -54,6 +64,7 @@ import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -64,6 +75,7 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator @@ -76,6 +88,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.snapshotFlow +import kotlinx.coroutines.flow.first import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -97,7 +111,14 @@ import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.input.InputMode import androidx.compose.ui.res.painterResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset @@ -106,8 +127,11 @@ import androidx.compose.ui.unit.sp import androidx.compose.ui.zIndex import coil.compose.AsyncImage import com.droiddeck.launcher.R +import com.droiddeck.launcher.HomeApp import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.input.SecondScreenDisplay +import com.droiddeck.launcher.session.SessionPrefs import java.io.File import kotlin.math.roundToInt @@ -134,13 +158,16 @@ class FrontEndState( val theme: String = Themes.PAPER, val isHomeApp: Boolean = false, val defaultHomeLabel: String? = null, - val androidApps: List = emptyList(), + val androidApps: List = emptyList(), + val secondScreenDisplays: List = emptyList(), val packages: List? = null, val packageCatalogLoading: Boolean = false, val packageBusyId: String? = null, val packageStage: String? = null, val packagePercent: Int = -1, val sessionRunning: Boolean = false, + val backActionsInverted: Boolean = false, + val buildLabel: String = "local", ) class FrontEndActions( @@ -168,7 +195,9 @@ class FrontEndActions( val onPageBack: () -> Unit = {}, val onTheme: (String) -> Unit = {}, val onHomeApp: () -> Unit = {}, - val onAndroidApp: (com.droiddeck.launcher.HomeApp.LaunchableApp) -> Unit = {}, + val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> }, + val onBackActionsInverted: (Boolean) -> Unit = {}, + val onCheckLatestBuild: () -> Unit = {}, ) @@ -227,9 +256,82 @@ private fun Modifier.shine(trigger: Boolean, strength: Float = 0.22f): Modifier } +/** + * Controller focus on the front end: each rail item's requester and the page's main button (Play, + * Open desktop, Open , Launch...). The pane leaves, to the left, for the selected rail + * item - whatever tile or button it leaves from - and remembers that control, so coming back in + * lands on it again; a page not yet visited enters on its main button. + */ +private class FrontFocus { + val rail = HashMap() + val primary = FocusRequester() + var primaryAttached by mutableStateOf(0) + var railFocused by mutableStateOf(false) + fun railFor(key: String): FocusRequester = rail.getOrPut(key) { FocusRequester() } + // The pane's controls by id (a tile's key, a button's label), how many of each are on screen, + // and the last one focused. + val items = HashMap() + val attached = HashMap() + var last: String? = null + // The first tile of the page's grid: Down from the page's buttons goes to it, not to whichever + // tile happens to sit under the button. + val firstTile = FocusRequester() + var firstTileAttached = 0 + fun paneEntry(): FocusRequester { + val id = last + return when { + id == PRIMARY && primaryAttached > 0 -> primary + id != null && id != PRIMARY && (attached[id] ?: 0) > 0 -> items.getValue(id) + primaryAttached > 0 -> primary + else -> FocusRequester.Default + } + } + companion object { const val PRIMARY = "\u0000primary" } +} + +/** Down from this button goes to the first tile of the page's grid, when there is one. */ +@Composable +private fun Modifier.downToFirstTile(): Modifier { + val ff = LocalFrontFocus.current ?: return this + return this.focusProperties { down = if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default } +} + +/** Marks the first tile of the page's grid. */ +@Composable +private fun Modifier.firstTile(): Modifier { + val ff = LocalFrontFocus.current ?: return this + DisposableEffect(Unit) { + ff.firstTileAttached++ + onDispose { ff.firstTileAttached-- } + } + return this.focusRequester(ff.firstTile) +} + +/** Lets the pane come back to this control: it is remembered when focused. */ +@Composable +private fun Modifier.paneItem(id: String): Modifier { + val ff = LocalFrontFocus.current ?: return this + val req = remember(id) { ff.items.getOrPut(id) { FocusRequester() } } + DisposableEffect(id) { + ff.attached[id] = (ff.attached[id] ?: 0) + 1 + onDispose { ff.attached[id] = (ff.attached[id] ?: 1) - 1 } + } + return this.focusRequester(req).onFocusChanged { if (it.isFocused) ff.last = id } +} + +private val LocalFrontFocus = staticCompositionLocalOf { null } + @Composable fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) { + val frontFocus = remember { FrontFocus() } + CompositionLocalProvider(LocalFrontFocus provides frontFocus) { FrontEndScreenBody(s, a, page, frontFocus) } +} + +@OptIn(ExperimentalComposeUiApi::class) +@Composable +private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) { var selected by rememberSaveable { mutableStateOf("steam") } + var appToChooseDisplay by remember { mutableStateOf(null) } val colors = MaterialTheme.colorScheme val ctx = LocalContext.current BackHandler(enabled = s.pageKey != null && page != null) { a.onPageBack() } @@ -248,7 +350,8 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () - LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" } remember { Motion.scale = Settings.Global.getFloat(ctx.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f); true } - BoxWithConstraints(modifier = Modifier.fillMaxSize().background(colors.background).systemBarsPadding()) { + var anyFocused by remember { mutableStateOf(false) } + BoxWithConstraints(modifier = Modifier.fillMaxSize().background(colors.background).systemBarsPadding().onFocusChanged { anyFocused = it.hasFocus }) { val wide = maxWidth >= 640.dp val railSelection = when { s.pageKey == "performance" || s.pageKey == "protons" -> "setup" @@ -269,9 +372,66 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () - modifier = if (wide) Modifier.width(236.dp).fillMaxHeight() else Modifier.fillMaxWidth().height(maxHeight * 0.42f), ) } - val content: @Composable (Modifier) -> Unit = { m -> Pane(s, selected, a, page, m) { selected = it } } + // The app opens with the selected rail item focused, so a controller sees where it is. An + // app starts in touch mode, where clickables refuse focus, so leave it first (a touch goes + // straight back to it); a request before the window has focus is dropped, so wait for + // that and retry until it sticks. + val window = LocalWindowInfo.current + val inputMode = LocalInputModeManager.current + LaunchedEffect(Unit) { + snapshotFlow { window.isWindowFocused }.first { it } + repeat(20) { + if (frontFocus.railFocused) return@LaunchedEffect + if (inputMode.inputMode != InputMode.Keyboard) inputMode.requestInputMode(InputMode.Keyboard) + runCatching { frontFocus.railFor(railSelection).requestFocus() } + kotlinx.coroutines.delay(100) + } + } + // A tile or button that opens a page goes away with the page it was on, and focus with it; + // the pad then had nothing to move from (a press landed back on the rail's first item). So + // once the new page is in, a controller lands on its main button. + val inputModeManager = LocalInputModeManager.current + LaunchedEffect(selected, s.pageKey) { + kotlinx.coroutines.delay(450) + if (!anyFocused && inputModeManager.inputMode == InputMode.Keyboard) runCatching { + if (frontFocus.primaryAttached > 0) frontFocus.primary.requestFocus() + else frontFocus.railFor(railSelection).requestFocus() + } + } + val back = if (wide) FocusDirection.Left else FocusDirection.Up + val paneFocus = Modifier + .focusProperties { + enter = { frontFocus.paneEntry() } + exit = { dir -> + if (dir == back) frontFocus.rail[railSelection] ?: FocusRequester.Default else FocusRequester.Default + } + } + .focusGroup() + val content: @Composable (Modifier) -> Unit = { m -> + Pane(s, selected, a, page, m.then(paneFocus), { selected = it }) { app -> + if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null) + else appToChooseDisplay = app + } + } if (wide) Row(modifier = Modifier.fillMaxSize()) { rail(); content(Modifier.weight(1f).fillMaxHeight()) } else Column(modifier = Modifier.fillMaxSize()) { rail(); content(Modifier.weight(1f).fillMaxWidth()) } + + appToChooseDisplay?.let { app -> + val secondaryDisplay = s.secondScreenDisplays.firstOrNull() + ChooseAppDisplayDialog( + app = app, + secondaryDisplay = secondaryDisplay, + onPrimary = { + appToChooseDisplay = null + a.onAndroidApp(app, Display.DEFAULT_DISPLAY) + }, + onSecondary = { + appToChooseDisplay = null + secondaryDisplay?.let { a.onAndroidApp(app, it.id) } + }, + onDismiss = { appToChooseDisplay = null }, + ) + } } } @@ -283,82 +443,89 @@ private fun Rail( ) { val colors = MaterialTheme.colorScheme Column( - modifier = modifier.background(colors.surface).verticalScroll(rememberScrollState()).padding(horizontal = 10.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(2.dp), + modifier = modifier.background(colors.surface).padding(horizontal = 10.dp, vertical = 12.dp), ) { - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 8.dp, bottom = 10.dp)) { - Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(30.dp)) - Spacer(Modifier.width(10.dp)) - Column { - Text("DroidDeck", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) - val status = when { - s.busy -> if (s.percent >= 0) "${s.stage} ${s.percent}%" else s.stage - !s.ready -> "runtime not installed" - s.available != null && s.available != s.installed -> "runtime update available" - else -> null + Column( + modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 8.dp, bottom = 10.dp)) { + Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(30.dp)) + Spacer(Modifier.width(10.dp)) + Column { + Text("DroidDeck", fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.onBackground) + val status = when { + s.busy -> if (s.percent >= 0) "${s.stage} ${s.percent}%" else s.stage + !s.ready -> "runtime not installed" + s.available != null && s.available != s.installed -> "runtime update available" + else -> null + } + if (status != null) Text(status, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) } - if (status != null) Text(status, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) } - } - AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { - LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) - } + AnimatedVisibility(s.busy, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { + LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) + } - var lastRunning by remember { mutableStateOf("") } - if (s.running != null) lastRunning = s.running - AnimatedVisibility( - s.running != null, - enter = expandVertically(Motion.sp(0.75f)) + fadeIn(Motion.tw(300)) + slideInVertically(Motion.sp(0.6f)) { -it / 2 }, - exit = shrinkVertically(Motion.tw(220)) + fadeOut(Motion.tw(180)), - ) { RunningTile(lastRunning, a.onResume) } + var lastRunning by remember { mutableStateOf("") } + if (s.running != null) lastRunning = s.running + AnimatedVisibility( + s.running != null, + enter = expandVertically(Motion.sp(0.75f)) + fadeIn(Motion.tw(300)) + slideInVertically(Motion.sp(0.6f)) { -it / 2 }, + exit = shrinkVertically(Motion.tw(220)) + fadeOut(Motion.tw(180)), + ) { RunningTile(lastRunning, a.onResume) } - val pal = LocalPalette.current - var navOrigin by remember { mutableStateOf(Offset.Zero) } - val positions = remember { mutableStateMapOf() } - Box(modifier = Modifier.fillMaxWidth().onGloballyPositioned { val o = it.positionInRoot(); if (o != navOrigin) navOrigin = o }) { - val target = positions[selected]?.translate(-navOrigin) - val y by animateFloatAsState(target?.top ?: 0f, Motion.sp(0.72f, Spring.StiffnessLow), label = "indY") - val x by animateFloatAsState(target?.left ?: 0f, Motion.sp(0.9f), label = "indX") - val h by animateFloatAsState(target?.height ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indH") - val w by animateFloatAsState(target?.width ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indW") - val alpha by animateFloatAsState(if (target != null) 1f else 0f, Motion.tw(250), label = "indA") - val density = LocalDensity.current - Box( - modifier = Modifier - .offset { IntOffset(x.roundToInt(), y.roundToInt()) } - .width(with(density) { w.toDp() }).height(with(density) { h.toDp() }) - .alpha(alpha) - .graphicsLayer { shadowElevation = 6.dp.toPx(); shape = Shape10; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal } - .clip(Shape10) - .background(Brush.linearGradient(listOf(colors.primary, pal.primary2))), + val pal = LocalPalette.current + var navOrigin by remember { mutableStateOf(Offset.Zero) } + val positions = remember { mutableStateMapOf() } + Box(modifier = Modifier.fillMaxWidth().onGloballyPositioned { val o = it.positionInRoot(); if (o != navOrigin) navOrigin = o }) { + val target = positions[selected]?.translate(-navOrigin) + val y by animateFloatAsState(target?.top ?: 0f, Motion.sp(0.72f, Spring.StiffnessLow), label = "indY") + val x by animateFloatAsState(target?.left ?: 0f, Motion.sp(0.9f), label = "indX") + val h by animateFloatAsState(target?.height ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indH") + val w by animateFloatAsState(target?.width ?: 0f, Motion.sp(1f, Spring.StiffnessMediumLow), label = "indW") + val alpha by animateFloatAsState(if (target != null) 1f else 0f, Motion.tw(250), label = "indA") + val density = LocalDensity.current + Box( + modifier = Modifier + .offset { IntOffset(x.roundToInt(), y.roundToInt()) } + .width(with(density) { w.toDp() }).height(with(density) { h.toDp() }) + .alpha(alpha) + .graphicsLayer { shadowElevation = 6.dp.toPx(); shape = Shape10; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal } + .clip(Shape10) + .background(Brush.linearGradient(listOf(colors.primary, pal.primary2))), + ) + val register: (String, LayoutCoordinates) -> Unit = { key, c -> + val o = c.positionInRoot(); val r = Rect(o.x, o.y, o.x + c.size.width, o.y + c.size.height) + if (positions[key] != r) positions[key] = r + } + val unregister: (String) -> Unit = { positions.remove(it) } + Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) { + if (s.isHomeApp) { + NavItem("Android apps", "android-apps", selected == "android-apps", count = s.androidApps.size, + register = register, unregister = unregister) { onSelect("android-apps") } + } + NavItem("Steam", "steam", selected == "steam", count = s.steamGames.size, register = register, unregister = unregister) { onSelect("steam") } + NavItem("Desktop", "desktop", selected == "desktop", count = s.emulators.count { it.installed }, register = register, unregister = unregister) { onSelect("desktop") } + NavItem("Setup", "setup", selected == "setup", register = register, unregister = unregister) { onSelect("setup") } + Spacer(Modifier.height(6.dp)) + } + } + + val creditsSrc = remember { MutableInteractionSource() } + val creditsHot = rememberHot(creditsSrc) + Text( + "credits", fontSize = 11.sp, color = if (creditsHot) LocalPalette.current.signal else colors.onSurfaceVariant, + modifier = Modifier.clip(Shape10) + .border(2.dp, if (creditsHot) LocalPalette.current.signal else Color.Transparent, Shape10) + .hoverable(creditsSrc).clickable(interactionSource = creditsSrc, indication = null, onClick = a.onCredits) + .padding(horizontal = 10.dp, vertical = 8.dp), ) - val register: (String, LayoutCoordinates) -> Unit = { key, c -> - val o = c.positionInRoot(); val r = Rect(o.x, o.y, o.x + c.size.width, o.y + c.size.height) - if (positions[key] != r) positions[key] = r - } - val unregister: (String) -> Unit = { positions.remove(it) } - Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) { - if (s.isHomeApp) { - NavItem("Android apps", "android-apps", selected == "android-apps", count = s.androidApps.size, - register = register, unregister = unregister) { onSelect("android-apps") } - } - NavItem("Steam", "steam", selected == "steam", count = s.steamGames.size, register = register, unregister = unregister) { onSelect("steam") } - NavItem("Desktop", "desktop", selected == "desktop", count = s.emulators.count { it.installed }, register = register, unregister = unregister) { onSelect("desktop") } - NavItem("Setup", "setup", selected == "setup", register = register, unregister = unregister) { onSelect("setup") } - Spacer(Modifier.height(6.dp)) - } } - - // Outlined when a controller is on it, like every other control; the ripple alone was - // a faint box on the dark rail. - val creditsSrc = remember { MutableInteractionSource() } - val creditsHot = rememberHot(creditsSrc) - Text( - "credits", fontSize = 11.sp, color = if (creditsHot) LocalPalette.current.signal else colors.onSurfaceVariant, - modifier = Modifier.clip(Shape10) - .border(2.dp, if (creditsHot) LocalPalette.current.signal else Color.Transparent, Shape10) - .hoverable(creditsSrc).clickable(interactionSource = creditsSrc, indication = null, onClick = a.onCredits) - .padding(horizontal = 10.dp, vertical = 8.dp), + BuildStatus( + label = s.buildLabel, + onCheckLatest = a.onCheckLatestBuild, + modifier = Modifier.align(Alignment.Start).padding(start = 8.dp, top = 4.dp, bottom = 2.dp), ) } } @@ -403,6 +570,9 @@ private fun NavItem( val colors = MaterialTheme.colorScheme val src = remember { MutableInteractionSource() } val focused by src.collectIsFocusedAsState() + val frontFocus = if (register != null && key != "x") LocalFrontFocus.current else null + val railRequester = frontFocus?.railFor(key) + if (frontFocus != null) LaunchedEffect(focused) { if (focused) frontFocus.railFocused = true } val hovered by src.collectIsHoveredAsState() val pressed by src.collectIsPressedAsState() val fg by animateColorAsState(if (current) colors.onPrimary else if (muted) colors.onSurfaceVariant else colors.onBackground, Motion.tw(280), label = "navFg") @@ -415,6 +585,7 @@ private fun NavItem( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() .then(if (register != null && key != "x") Modifier.onGloballyPositioned { register(key, it) } else Modifier) + .then(if (railRequester != null) Modifier.focusRequester(railRequester) else Modifier) .then(if (small && i >= 0 && register != null) Modifier.staggerIn(i) else Modifier) .graphicsLayer { scaleX = scale; scaleY = scale } .clip(Shape10) @@ -441,7 +612,10 @@ private fun NavItem( @Composable -private fun Pane(s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier, onSelect: (String) -> Unit) { +private fun Pane( + s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier, + onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit, +) { Box(modifier = modifier) { val wash: Pair = when { s.pageKey != null && page != null -> null to 250f @@ -462,7 +636,48 @@ private fun Pane(s: FrontEndState, selected: String, a: FrontEndActions, page: ( .apply { targetContentZIndex = 1f } }, label = "pane", - ) { key -> if (page != null && key == s.pageKey) page() else Content(s, key, a, Modifier.fillMaxSize(), onSelect) } + ) { key -> if (page != null && key == s.pageKey) page() else Content(s, key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick) } + } +} + +@Composable +private fun BuildStatus(label: String, onCheckLatest: () -> Unit, modifier: Modifier = Modifier) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val interaction = remember { MutableInteractionSource() } + val hot = rememberHot(interaction) + val contextDivider = label.indexOf(" · ") + val context = if (contextDivider >= 0) label.substring(0, contextDivider) else "" + val identity = if (contextDivider >= 0) label.substring(contextDivider + 3) else label + val identityDivider = identity.lastIndexOf(" at ") + val branch = (if (identityDivider >= 0) identity.substring(0, identityDivider) else identity).substringAfterLast('/') + val commit = if (identityDivider >= 0) identity.substring(identityDivider + 4) else "" + Column( + verticalArrangement = Arrangement.spacedBy(1.dp), + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(6.dp)) + .semantics { contentDescription = "Build $label. Check for newest build." } + .hoverable(interaction) + .clickable( + interactionSource = interaction, + indication = LocalIndication.current, + role = Role.Button, + onClick = onCheckLatest, + ) + .heightIn(min = 44.dp) + .padding(horizontal = 4.dp, vertical = 3.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(5.dp), + modifier = Modifier.fillMaxWidth(), + ) { + Text(branch, modifier = Modifier.weight(1f), fontSize = 9.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = if (hot) colors.onSurfaceVariant else colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1, overflow = TextOverflow.Ellipsis) + if (commit.isNotEmpty()) Text("@$commit", fontSize = 8.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1) + Icon(Icons.Filled.Refresh, contentDescription = null, tint = if (hot) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.82f), modifier = Modifier.size(12.dp)) + } + if (context.isNotEmpty()) Text(context, fontSize = 8.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1) } } @@ -491,7 +706,10 @@ private fun romFor(s: FrontEndState, selected: String): Pair Unit) { +private fun Content( + s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier, + onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit, +) { val colors = MaterialTheme.colorScheme Column(modifier = modifier.padding(horizontal = 22.dp, vertical = 18.dp)) { when { @@ -507,7 +725,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi null, null, "android:${app.packageName}", - onClick = { a.onAndroidApp(app) }, + onClick = { onAndroidAppClick(app) }, iconBitmap = app.icon, ) }) @@ -518,7 +736,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi Rise(3) { Actions { // Enabled without a runtime: the session's loading screen installs it first. - PrimaryButton("Play", enabled = !s.busy, onClick = a.onPlay) + PrimaryButton("Play", enabled = !s.busy, main = true, onClick = a.onPlay) SecondaryButton("Steam Desktop UI", enabled = !s.busy, onClick = a.onPlayDesktopUi) Cog(a.onSteamSettings) } @@ -544,7 +762,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi Row { Column(modifier = Modifier.weight(1f)) { Actions { - PrimaryButton("Launch", enabled = s.ready && !s.busy) { a.onSteamGame(g) } + PrimaryButton("Launch", enabled = s.ready && !s.busy, main = true) { a.onSteamGame(g) } Cog(a.onSteamSettings) Chip(if (s.ready) "● ready" else "runtime missing", ok = s.ready) } @@ -564,7 +782,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi Rise(3) { Actions { // Enabled without a runtime or the desktop: the session's loading screen installs them first. - PrimaryButton(if (s.desktopInstalled) "Open desktop" else "Install & open desktop", enabled = !s.busy, onClick = a.onDesktop) + PrimaryButton(if (s.desktopInstalled) "Open desktop" else "Install & open desktop", enabled = !s.busy, main = true, onClick = a.onDesktop) Cog(a.onDesktopSettings) } } @@ -590,7 +808,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi Rise(3) { Actions { Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp)) - PrimaryButton("Open ${e.name}", enabled = s.ready && !s.busy) { a.onEmulator(e) } + PrimaryButton("Open ${e.name}", enabled = s.ready && !s.busy, main = true) { a.onEmulator(e) } SecondaryButton("ROMs folder", onClick = a.onRoms) if (pkg != null) SecondaryButton( if (pkg.kind == "appimage") "Remove" else "Forget", @@ -667,7 +885,7 @@ private fun Content(s: FrontEndState, selected: String, a: FrontEndActions, modi Spacer(Modifier.height(14.dp)) Actions { Image(painterResource(e.iconRes), null, modifier = Modifier.size(40.dp)) - PrimaryButton("Launch in ${e.name}", enabled = s.ready && !s.busy) { a.onRom(g) } + PrimaryButton("Launch in ${e.name}", enabled = s.ready && !s.busy, main = true) { a.onRom(g) } Chip(g.hostPath.extension.uppercase().ifEmpty { "folder" }, ok = false) } } @@ -711,12 +929,19 @@ private fun SetupPanel(s: FrontEndState, a: FrontEndActions) { ActionRow("ROMs folder", s.romsDir ?: "Choose where emulator games are stored", "Choose", a.onRoms) } SettingsGroup("Session") { + ChoiceRow( + host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted), + listOf( + false to SessionPrefs.BACK_MENU_THEN_QAM, + true to SessionPrefs.BACK_QAM_THEN_MENU, + ), s.backActionsInverted, onPick = a.onBackActionsInverted, + ) SettingsRow("Frame generation", "Select the frame generation mode") { Box { ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" } - AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { + AnchoredMenu(host.open == "fg", onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus -> val need = if (s.lsfgReady) null else "Install Lossless Scaling in Steam" - MenuItem("Off", checked = s.frameGenEngine == FrameGen.ENGINE_OFF) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null } + MenuItem("Off", checked = s.frameGenEngine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null } for (m in 2..4) MenuItem("Win-FG ${m}×", checked = s.frameGenEngine == FrameGen.ENGINE_WINFG && s.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null } for (m in 2..4) MenuItem("LSFG ${m}×", checked = s.frameGenEngine == FrameGen.ENGINE_LSFG && s.frameGenMultiplier == m, enabled = s.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null } } @@ -737,8 +962,13 @@ private fun SetupPanel(s: FrontEndState, a: FrontEndActions) { SettingsRow("Theme", "Choose the launcher appearance") { Box { ValueChip(Themes.byId(s.theme).label, host.open == "theme") { host.open = if (host.open == "theme") null else "theme" } - AnchoredMenu(host.open == "theme", onDismiss = { if (host.open == "theme") host.open = null }, title = "Theme") { - for (t in Themes.all) MenuItem(t.label, checked = s.theme == t.id) { a.onTheme(t.id); host.open = null } + AnchoredMenu(host.open == "theme", onDismiss = { if (host.open == "theme") host.open = null }, title = "Theme") { firstItemFocus -> + Themes.all.forEachIndexed { index, theme -> + MenuItem(theme.label, checked = s.theme == theme.id, focusRequester = if (index == 0) firstItemFocus else null) { + a.onTheme(theme.id) + host.open = null + } + } } } } @@ -793,9 +1023,16 @@ private fun Chip(t: String, ok: Boolean) { private fun rememberHot(src: MutableInteractionSource): Boolean = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value @Composable -private fun PrimaryButton(text: String, enabled: Boolean = true, onClick: () -> Unit) { +private fun PrimaryButton(text: String, enabled: Boolean = true, main: Boolean = false, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current + // The page's main button is where the pane is entered from the rail. + val frontFocus = if (main) LocalFrontFocus.current else null + if (frontFocus != null) DisposableEffect(Unit) { + frontFocus.primaryAttached++ + onDispose { frontFocus.primaryAttached-- } + } + val track = (if (frontFocus == null) Modifier.paneItem("btn:$text") else Modifier).downToFirstTile() val src = remember { MutableInteractionSource() } val hot = rememberHot(src) && enabled val pressed by src.collectIsPressedAsState() @@ -803,7 +1040,8 @@ private fun PrimaryButton(text: String, enabled: Boolean = true, onClick: () -> val lift by animateFloatAsState(if (hot) 14f else 6f, Motion.tw(300), label = "btnLift") Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier + modifier = track + .then(if (frontFocus != null) Modifier.focusRequester(frontFocus.primary).onFocusChanged { if (it.isFocused) frontFocus.last = FrontFocus.PRIMARY } else Modifier) .graphicsLayer { scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = Shape12; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal } .clip(Shape12) .background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant))) @@ -829,9 +1067,10 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, onClick: () val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "secEdge") val fill by animateColorAsState(if (hot) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f), Motion.tw(250), label = "secFill") Box( - modifier = Modifier.graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12) + modifier = Modifier.paneItem("btn:$text").downToFirstTile().graphicsLayer { scaleX = scale; scaleY = scale }.clip(Shape12).background(fill).border(1.dp, edge, Shape12) .alpha(if (enabled) 1f else 0.5f) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 16.dp, vertical = 11.dp), ) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) } } @@ -846,7 +1085,7 @@ private fun Cog(onClick: () -> Unit) { val edge by animateColorAsState(if (hot) pal.signal else pal.line2, Motion.tw(250), label = "cogEdge") Box( contentAlignment = Alignment.Center, - modifier = Modifier.size(42.dp).clip(Shape12).background(Color.White.copy(alpha = 0.03f)).border(1.dp, edge, Shape12) + modifier = Modifier.paneItem("cog").downToFirstTile().size(42.dp).clip(Shape12).background(Color.White.copy(alpha = 0.03f)).border(1.dp, edge, Shape12) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick), ) { Icon(Icons.Filled.Settings, "Settings", tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(18.dp).rotate(rot)) } } @@ -887,7 +1126,8 @@ private fun ArtGrid(tiles: List, wide: Boolean = false) { for (t in row) key(t.key) { val src = remember { MutableInteractionSource() } val hot = rememberHot(src) - Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot) } + val track = Modifier.paneItem("tile:" + t.key).then(if (t === tiles.first()) Modifier.firstTile() else Modifier) + Box(modifier = Modifier.width(tileWidth).zIndex(if (hot) 1f else 0f)) { GameTile(t, wide, square, src, hot, track) } } } } @@ -896,7 +1136,7 @@ private fun ArtGrid(tiles: List, wide: Boolean = false) { } @Composable -private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableInteractionSource, hot: Boolean) { +private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableInteractionSource, hot: Boolean, track: Modifier) { val colors = MaterialTheme.colorScheme val pressed by src.collectIsPressedAsState() val scale by animateFloatAsState(if (pressed) 0.97f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "tileScale") @@ -905,7 +1145,7 @@ private fun GameTile(t: Tile, wide: Boolean, square: Boolean, src: MutableIntera val pal = LocalPalette.current val ring by animateColorAsState(if (hot) pal.signal else Color.Transparent, Motion.tw(220), label = "tileRing") Column( - modifier = Modifier + modifier = track .graphicsLayer { scaleX = scale; scaleY = scale; translationY = lift.dp.toPx(); shadowElevation = elev.dp.toPx(); shape = Shape12; clip = false; ambientShadowColor = if (hot) pal.signal else Color.Black; spotShadowColor = if (hot) pal.signal else Color.Black; transformOrigin = androidx.compose.ui.graphics.TransformOrigin(0.5f, 0.9f) } .clip(Shape12) .background(colors.surface) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt index 5fb8fc0e63..f701360206 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/MainScreen.kt @@ -12,6 +12,34 @@ import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.HomeApp +import com.droiddeck.launcher.input.SecondScreenDisplay + +@Composable +fun ChooseAppDisplayDialog( + app: HomeApp.LaunchableApp, + secondaryDisplay: SecondScreenDisplay?, + onPrimary: () -> Unit, + onSecondary: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Launch ${app.label}") }, + text = { + Text( + secondaryDisplay?.let { "Choose a screen. Secondary: ${it.label}." } + ?: "The secondary display is no longer available.", + ) + }, + confirmButton = { TextButton(onClick = onPrimary) { Text("Primary screen") } }, + dismissButton = { + TextButton(onClick = onSecondary, enabled = secondaryDisplay != null) { + Text("Secondary screen") + } + }, + ) +} @Composable fun ConfirmDialog(title: String, text: String, confirm: String, onConfirm: () -> Unit, onDismiss: () -> Unit) { 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 7460914bcc..06af6c7459 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -46,6 +46,8 @@ class ModeSettings( val suspendPolicy: String, /** Steam only. */ val oscMode: String?, + /** Steam only: whether single and double Back actions are swapped. */ + val backActionsInverted: Boolean = false, val directAudio: Boolean?, val clientDirectAudio: Boolean = false, val mic: Boolean?, @@ -53,6 +55,8 @@ class ModeSettings( val gameStorage: String? = null, val storageOptions: List> = emptyList(), val fexPreset: String? = null, + /** Steam only: games are stretched to fill the screen (null = not a Steam page). */ + val forceFullscreen: Boolean? = null, /** Steam only: the client branch forced on the command line. */ val steamChannel: String? = null, /** Steam only: the user's own games folder and what was found in it. */ @@ -91,6 +95,7 @@ class ModeSettingsActions( val onTouch: (String) -> Unit, val onSuspendPolicy: (String) -> Unit, val onOsc: (String) -> Unit, + val onBackActionsInverted: (Boolean) -> Unit = {}, val onDirectAudio: (Boolean) -> Unit, val onClientDirectAudio: (Boolean) -> Unit = {}, val onMic: (Boolean) -> Unit, @@ -98,6 +103,7 @@ class ModeSettingsActions( val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> }, val onPickGameStorageFolder: () -> Unit = {}, val onFexPreset: (String) -> Unit = {}, + val onForceFullscreen: (Boolean) -> Unit = {}, val onSteamChannel: (String) -> Unit = {}, val onPickAddedGamesDir: () -> Unit = {}, val onForgetAddedGamesDir: (path: String) -> Unit = {}, @@ -226,6 +232,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { ), s.oscMode, note = "Auto shows all controls without a controller. Steam + QAM shows only those buttons.", onPick = a.onOsc, ) + if (steam) ChoiceRow( + host, "back-actions", "Back", SessionPrefs.backActionsOrder(s.backActionsInverted), + listOf( + false to SessionPrefs.BACK_MENU_THEN_QAM, + true to SessionPrefs.BACK_QAM_THEN_MENU, + ), s.backActionsInverted, onPick = a.onBackActionsInverted, + ) } SettingsGroup("Session") { ChoiceRow( @@ -280,6 +293,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { FexPreset.all.map { it.id to it.label }, s.fexPreset, note = FexPreset.byId(s.fexPreset).detail, onPick = a.onFexPreset, ) + if (s.forceFullscreen != null) ToggleRow( + host, "fill", "Stretch games to fill the screen", + "Keeps games that resize their own window (FlatOut) full screen. Turn it off if a game shows up small in a corner (Quake 3). Applies next session.", + s.forceFullscreen, onChange = a.onForceFullscreen, + ) } if (steam && s.directAudio != null && s.mic != null) SettingsGroup("Audio") { ToggleRow(host, "da", "DirectAudio for games", "Bypasses PulseAudio for lower latency in games.", s.directAudio, onChange = a.onDirectAudio) @@ -309,10 +327,12 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { AnchoredMenu( open, onDismiss = { if (host.open == "storage") host.open = null }, title = "Second library", note = "Games that stream assets from SD or shared storage may stutter. Keep them internal.", - ) { - for ((path, label) in options) MenuItem(label, checked = path == s.gameStorage) { - a.onGameStorage(path, if (path.isEmpty() || path == "off") "" else label.substringBefore(" ·")) - host.open = null + ) { firstItemFocus -> + options.forEachIndexed { index, (path, label) -> + MenuItem(label, checked = path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) { + a.onGameStorage(path, if (path.isEmpty() || path == "off") "" else label.substringBefore(" ·")) + host.open = null + } } MenuItem("Choose a folder…", checked = false) { host.open = null; a.onPickGameStorageFolder() } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index 818d72624d..3a4bdb2ef6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -44,6 +44,7 @@ class SecondScreenPresentation( private val sendWheel: (steps: Int) -> Unit, private val onSteamMenu: () -> Unit, private val onQam: () -> Unit, + private val onClose: () -> Unit, ) : Presentation(sessionActivity, display) { private val root = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL @@ -124,6 +125,12 @@ class SecondScreenPresentation( setPadding(dp(12), dp(8), dp(12), dp(8)) setBackgroundColor(0xE6191E24.toInt()) } + controls.addView(Button(context).apply { + text = "×" + contentDescription = "Close second-screen controls" + minWidth = dp(48) + setOnClickListener { onClose() } + }) controls.addView(TextView(context).apply { text = "Trackpad" textSize = 14f @@ -169,6 +176,12 @@ class SecondScreenPresentation( setPadding(dp(8), dp(4), dp(8), dp(4)) setBackgroundColor(Color.rgb(27, 32, 38)) } + bar.addView(Button(context).apply { + text = "×" + contentDescription = "Close second-screen controls" + minWidth = dp(48) + setOnClickListener { onClose() } + }) bar.addView(TextView(context).apply { text = "Linux terminal" textSize = 14f 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 400caaeb82..b3eab4b6c5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -1,8 +1,11 @@ package com.droiddeck.launcher.ui +import android.view.Display +import androidx.activity.compose.BackHandler import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable +import androidx.compose.foundation.focusGroup import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.ui.focus.focusRequester import androidx.compose.material3.ButtonDefaults @@ -30,7 +33,9 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment +import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.res.painterResource @@ -51,6 +56,7 @@ import androidx.compose.animation.slideOutHorizontally import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.border import androidx.compose.foundation.hoverable +import androidx.compose.foundation.focusGroup import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.layout.Arrangement @@ -62,8 +68,13 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.InputMode +import androidx.compose.ui.platform.LocalInputModeManager import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight @@ -121,6 +132,11 @@ fun LoadingOverlay(step: String, percent: Int, elapsed: String, hint: String, en @Composable fun SessionPausedOverlay(onResume: () -> Unit) { val interactionSource = remember { MutableInteractionSource() } + val resumeFocus = remember { FocusRequester() } + LaunchedEffect(Unit) { + androidx.compose.runtime.withFrameNanos { } + runCatching { resumeFocus.requestFocus() } + } Box( modifier = Modifier .fillMaxSize() @@ -132,7 +148,10 @@ fun SessionPausedOverlay(onResume: () -> Unit) { horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(32.dp), ) { - OutlinedButton(onClick = onResume) { + OutlinedButton( + onClick = onResume, + modifier = Modifier.focusRequester(resumeFocus).controllerConfirm(onClick = onResume), + ) { Text("Resume session") } } @@ -151,10 +170,13 @@ class DrawerActions( val frameGenMultiplier: Int, val lsfgReady: Boolean, val oscMode: String, + val backActionsInverted: Boolean, val touchMode: String, val touchAuto: String, val shapeMode: String, val fexPreset: String, + /** Steam only: games stretched to the screen's size, changed live (null = not Steam). */ + val fillScreen: Boolean? = null, val secondScreenMode: SecondScreenMode, val secondScreenDisplays: List, val selectedSecondScreenDisplay: Int, @@ -167,32 +189,47 @@ class DrawerActions( val onSteamMenu: (() -> Unit)?, val onQam: (() -> Unit)?, val onOsc: (String) -> Unit, + val onBackActionsInverted: (Boolean) -> Unit, val onTouch: (String) -> Unit, val onShape: (String) -> Unit, val onFexPreset: (String) -> Unit, + val onFillScreen: (Boolean) -> Unit = {}, val onSecondScreenMode: (SecondScreenMode) -> Unit, val onSecondScreenDisplay: (Int) -> Unit, - val onLaunchAndroidApp: (HomeApp.LaunchableApp) -> Unit, + val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit, val onBackground: () -> Unit, val onStop: () -> Unit, val onClose: () -> Unit, ) +@OptIn(ExperimentalComposeUiApi::class) @Composable fun SessionDrawer(open: Boolean, a: DrawerActions) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val host = rememberMenuHost() var androidAppsExpanded by rememberSaveable { mutableStateOf(false) } + var appToChooseDisplay by remember { mutableStateOf(null) } val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil") // A controller starts on the drawer's first control, highlighted, as on the app's main screen: // the STEAM button, or in a desktop session the first setting. val firstFocus = remember { androidx.compose.ui.focus.FocusRequester() } + var firstControlFocused by remember { mutableStateOf(false) } + val inputModeManager = LocalInputModeManager.current val steamButtons = a.onSteamMenu != null && a.onQam != null + BackHandler(enabled = open) { + if (host.open != null) host.open = null else a.onClose() + } LaunchedEffect(open) { if (open) { - androidx.compose.runtime.withFrameNanos { } - runCatching { firstFocus.requestFocus() } + inputModeManager.requestInputMode(InputMode.Keyboard) + var attempts = 0 + while (attempts < 24 && !firstControlFocused) { + firstFocus.requestFocus() + androidx.compose.runtime.withFrameNanos { } + attempts++ + } + if (!firstControlFocused) android.util.Log.w("SessionDrawer", "first controller focus request did not focus a control") } } if (open || veil > 0.01f) Box( @@ -211,6 +248,10 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { .width(340.dp) .background(pal.background.copy(alpha = 0.97f)) .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} + .focusGroup() + .controllerBack { + if (host.open != null) host.open = null else a.onClose() + } .verticalScroll(rememberScrollState()) .padding(horizontal = 14.dp, vertical = 16.dp), ) { @@ -241,7 +282,14 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { OutlinedButton( onClick = { host.open = null; a.onSteamMenu.invoke() }, interactionSource = steamSrc, - modifier = Modifier.weight(1f).height(48.dp).focusRequester(firstFocus), + modifier = Modifier.weight(1f).height(48.dp).focusRequester(firstFocus) + .onFocusChanged { + firstControlFocused = it.isFocused + android.util.Log.i("SessionDrawer", "first control focused=${it.isFocused}") + }.controllerConfirm { + host.open = null + a.onSteamMenu.invoke() + }, shape = RoundedCornerShape(12.dp), border = BorderStroke(if (steamHot) 2.dp else 1.dp, if (steamHot) pal.signal else colors.outline), colors = ButtonDefaults.outlinedButtonColors(containerColor = if (steamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent), @@ -255,7 +303,10 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { qamStartedOnPress = false }, interactionSource = qamInteraction, - modifier = Modifier.weight(1f).height(48.dp).semantics { contentDescription = "Open Quick Access Menu" }, + modifier = Modifier.weight(1f).height(48.dp).semantics { contentDescription = "Open Quick Access Menu" }.controllerConfirm { + host.open = null + a.onQam.invoke() + }, shape = RoundedCornerShape(12.dp), border = BorderStroke(if (qamHot) 2.dp else 1.dp, if (qamHot) pal.signal else colors.outline), colors = ButtonDefaults.outlinedButtonColors(containerColor = if (qamHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent), @@ -287,7 +338,11 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { ) } }, - ) { a.onLaunchAndroidApp(app) } + ) { + host.open = null + if (a.secondScreenDisplays.isEmpty()) a.onLaunchAndroidApp(app, null) + else appToChooseDisplay = app + } } } } @@ -296,7 +351,12 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { SettingsGroup("Now") { ToggleRow( host, "hud", "Performance HUD", null, a.hudOn, - chipModifier = if (steamButtons) Modifier else Modifier.focusRequester(firstFocus), onChange = a.onHud, + chipModifier = if (steamButtons) Modifier else Modifier.focusRequester(firstFocus) + .onFocusChanged { firstControlFocused = it.isFocused }, onChange = a.onHud, + ) + if (a.fillScreen != null) ToggleRow( + host, "fill", "Stretch games to fill the screen", + "Off for a game that shows up small in a corner (Quake 3).", a.fillScreen, onChange = a.onFillScreen, ) val fgOpen = host.open == "fg" val fgLabel = when (a.frameGenEngine) { @@ -307,9 +367,9 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { SettingsRow("Frame generation", null, highlighted = fgOpen) { Box { ValueChip(fgLabel, fgOpen) { host.open = if (fgOpen) null else "fg" } - AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { + AnchoredMenu(fgOpen, onDismiss = { if (host.open == "fg") host.open = null }, title = "Frame generation") { firstItemFocus -> val need = if (a.lsfgReady) null else "install Lossless Scaling in Steam" - MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null } + MenuItem("Off", checked = a.frameGenEngine == FrameGen.ENGINE_OFF, focusRequester = firstItemFocus) { a.onFrameGenPick(FrameGen.ENGINE_OFF, 2); host.open = null } for (m in 2..4) MenuItem("Win-FG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_WINFG && a.frameGenMultiplier == m) { a.onFrameGenPick(FrameGen.ENGINE_WINFG, m); host.open = null } for (m in 2..4) MenuItem("LSFG ${m}×", checked = a.frameGenEngine == FrameGen.ENGINE_LSFG && a.frameGenMultiplier == m, enabled = a.lsfgReady, detail = need) { a.onFrameGenPick(FrameGen.ENGINE_LSFG, m); host.open = null } } @@ -327,6 +387,13 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { a.oscMode, onPick = a.onOsc, ) + if (a.steam) ChoiceRow( + host, "back-actions", "Back", SessionPrefs.backActionsOrder(a.backActionsInverted), + listOf( + false to SessionPrefs.BACK_MENU_THEN_QAM, + true to SessionPrefs.BACK_QAM_THEN_MENU, + ), a.backActionsInverted, onPick = a.onBackActionsInverted, + ) SettingsRow("Keyboard", null) { Row(verticalAlignment = Alignment.CenterVertically) { SecondaryButton("Hardware") { host.open = null; a.onHardwareKeyboard() } @@ -373,6 +440,24 @@ fun SessionDrawer(open: Boolean, a: DrawerActions) { } } } + + appToChooseDisplay?.let { app -> + val secondaryDisplay = a.secondScreenDisplays.firstOrNull { it.id == a.selectedSecondScreenDisplay } + ?: a.secondScreenDisplays.firstOrNull() + ChooseAppDisplayDialog( + app = app, + secondaryDisplay = secondaryDisplay, + onPrimary = { + appToChooseDisplay = null + a.onLaunchAndroidApp(app, Display.DEFAULT_DISPLAY) + }, + onSecondary = { + appToChooseDisplay = null + secondaryDisplay?.let { a.onLaunchAndroidApp(app, it.id) } + }, + onDismiss = { appToChooseDisplay = null }, + ) + } } @Composable @@ -384,6 +469,7 @@ private fun DangerButton(text: String, onClick: () -> Unit) { Box( modifier = Modifier.clip(RoundedCornerShape(12.dp)).background(fill).border(1.dp, colors.error.copy(alpha = if (hot) 0.9f else 0.5f), RoundedCornerShape(12.dp)) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, onClick = onClick) + .controllerConfirm(onClick = onClick) .padding(horizontal = 16.dp, vertical = 11.dp), ) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.error, maxLines = 1) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index da7fd678db..a7322987b0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import android.view.KeyEvent import androidx.compose.animation.AnimatedContent import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColorAsState @@ -39,6 +40,7 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -49,9 +51,12 @@ import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.draw.shadow +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow @@ -69,6 +74,26 @@ import androidx.compose.ui.window.PopupProperties private val RowShape = RoundedCornerShape(12.dp) private val GroupShape = RoundedCornerShape(14.dp) +internal fun Modifier.controllerConfirm(enabled: Boolean = true, onClick: () -> Unit): Modifier = onPreviewKeyEvent { event -> + val keyEvent = event.nativeKeyEvent + if (keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_A) { + false + } else { + if (enabled && keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) onClick() + true + } +} + +internal fun Modifier.controllerBack(onBack: () -> Unit): Modifier = onPreviewKeyEvent { event -> + val keyEvent = event.nativeKeyEvent + if (keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_B && keyEvent.keyCode != KeyEvent.KEYCODE_BACK) { + false + } else { + if (keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) onBack() + true + } +} + class MenuHost { var open by mutableStateOf(null) } @@ -88,10 +113,18 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider { } @Composable -fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.() -> Unit) { +fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, content: @Composable ColumnScope.(FocusRequester) -> Unit) { val state = remember { MutableTransitionState(false) } state.targetState = open if (!state.currentState && !state.targetState && state.isIdle) return + val firstItemFocus = remember { FocusRequester() } + LaunchedEffect(open) { + if (open) { + repeat(2) { androidx.compose.runtime.withFrameNanos { } } + runCatching { firstItemFocus.requestFocus() } + android.util.Log.i("AnchoredMenu", "requested first option focus") + } + } val gap = with(LocalDensity.current) { 6.dp.roundToPx() } val provider = remember(gap) { BelowEndProvider(gap) } val colors = MaterialTheme.colorScheme @@ -114,13 +147,14 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no .clip(RowShape) .background(pal.surfaceVariant.copy(alpha = 0.95f)) .border(1.dp, pal.signal.copy(alpha = 0.22f), RowShape) + .controllerBack(onDismiss) .padding(6.dp), ) { if (title != null) Text( title.uppercase(), fontSize = 10.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 10.dp, top = 6.dp, bottom = 6.dp), ) - Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { content() } + Column(Modifier.weight(1f, fill = false).verticalScroll(rememberScrollState())) { content(firstItemFocus) } if (note != null) { Spacer(Modifier.height(4.dp)) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) @@ -134,7 +168,8 @@ fun AnchoredMenu(open: Boolean, onDismiss: () -> Unit, title: String? = null, no @Composable fun MenuItem( label: String, checked: Boolean, enabled: Boolean = true, detail: String? = null, - trailing: (@Composable () -> Unit)? = null, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit, + trailing: (@Composable () -> Unit)? = null, leading: (@Composable () -> Unit)? = null, + focusRequester: FocusRequester? = null, onClick: () -> Unit, ) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -145,10 +180,12 @@ fun MenuItem( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() .graphicsLayer { translationX = shift.dp.toPx() } + .then(focusRequester?.let { Modifier.focusRequester(it) } ?: Modifier) .clip(RoundedCornerShape(8.dp)) .background(if (hot && enabled) Color.White.copy(alpha = 0.07f) else Color.Transparent) .alpha(if (enabled) 1f else 0.4f) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 10.dp, vertical = 9.dp), ) { Text("✓", fontSize = 12.sp, color = pal.signal, modifier = Modifier.width(18.dp).alpha(if (checked) 1f else 0f)) @@ -181,6 +218,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo .border(1.dp, edge, RoundedCornerShape(10.dp)) .alpha(if (enabled) 1f else 0.5f) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = 12.dp, vertical = 8.dp), ) { AnimatedContent( @@ -234,8 +272,13 @@ fun ChoiceRow( SettingsRow(label, hint, highlighted = open) { Box { ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier) { host.open = if (open) null else key } - AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { - for ((value, text) in options) MenuItem(text, checked = value == selected) { onPick(value); host.open = null } + AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus -> + options.forEachIndexed { index, (value, text) -> + MenuItem(text, checked = value == selected, focusRequester = if (index == 0) firstItemFocus else null) { + onPick(value) + host.open = null + } + } } } } @@ -260,10 +303,10 @@ fun MultiRow( SettingsRow(label, hint, highlighted = open) { Box { ValueChip(summary, open, enabled) { host.open = if (open) null else key } - AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { - for ((value, text) in items) { + AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus -> + items.forEachIndexed { index, (value, text) -> val on = value in selected - MenuItem(text, checked = on) { onToggle(value, !on) } + MenuItem(text, checked = on, focusRequester = if (index == 0) firstItemFocus else null) { onToggle(value, !on) } } } } 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 52afd790f0..b9b2eb5d15 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -169,6 +169,8 @@ public final class WaylandCompositor { * action: 0=down, 1=move, 2=up. x/y in compositor output space (0..1919, 0..1079). */ public static native void nativeSendPointer(int action, int x, int y); + public static native void nativeSendTouch(int action, int pointerId, int x, int y); + /** Inject a key event. evdev = Linux input keycode (KEY_A=30…); state: 1=down, 0=up. */ public static native void nativeSendKey(int evdev, int state); diff --git a/app/src/main/res/drawable-nodpi/logo.png b/app/src/main/res/drawable-nodpi/logo.png index 936dba3bd4..a9c737a397 100644 Binary files a/app/src/main/res/drawable-nodpi/logo.png and b/app/src/main/res/drawable-nodpi/logo.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_background.png b/app/src/main/res/mipmap-hdpi/ic_launcher_background.png index 4d43523810..8538bed392 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_background.png and b/app/src/main/res/mipmap-hdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png index 70d64c0ed6..6998da4247 100644 Binary files a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_background.png b/app/src/main/res/mipmap-mdpi/ic_launcher_background.png index adcd0243a0..a92ccfafbb 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_background.png and b/app/src/main/res/mipmap-mdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png index 29b8eaef83..a9a5f33dc0 100644 Binary files a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png index 1ef58344be..3ba37c9e97 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png and b/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png index 9eb6b35a8c..98c616ee8c 100644 Binary files a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png index abac9697ec..07f6de5a9b 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png index 8fdd7a8b24..35a8ddbbcb 100644 Binary files a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png index 8ab6e6ea4c..5ae3008fea 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png index 7e9120421c..91ae0e397b 100644 Binary files a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/artwork/README.md b/artwork/README.md new file mode 100644 index 0000000000..9379fc54f6 --- /dev/null +++ b/artwork/README.md @@ -0,0 +1,5 @@ +# DroidDeck mark + +`droiddeck-mark.svg` is the editable source for the split-D mark. The blue orb is `#1A9FFF`; its halo and the two separator bars are transparent cutouts. The bars are centered on x=63.97, the endpoint of the curved half in the original Steam Deck symbol, and use the halo's 15.83-unit thickness. The mark is optically centered in its view box with a small rightward offset to balance its asymmetric silhouette. + +Android currently consumes raster resources for the launcher layers and the Compose logo. The `mipmap-*/ic_launcher_foreground.png` files are density-sized exports of the SVG, with the mark kept inside the adaptive icon safe area. The matching backgrounds are white. `drawable-nodpi/logo.png` composes the same mark on a white circular badge for use on the app's dark surfaces. diff --git a/artwork/droiddeck-mark.svg b/artwork/droiddeck-mark.svg new file mode 100644 index 0000000000..6b071bde25 --- /dev/null +++ b/artwork/droiddeck-mark.svg @@ -0,0 +1,13 @@ + + DroidDeck split D with a circular orb halo and solid blue orb + + + + + + + + + + + diff --git a/docs/progress-log.md b/docs/progress-log.md index 74f418d665..82c55b60ae 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -230,7 +230,9 @@ State: **main = `90c7574`** (PR #14 merge), main build run 35895701784. No tag, - Thor Pro: trackpad tap; the 1–2 min in-game crash once a `crash.log` arrives. - Xfce as a second desktop shell (Max's branch runs XFCE 4.20 on labwc) - a catalog package + a shell choice in the Desktop cog; comfort, not performance. -- Quick Access Menu for non-Deck pads - no confirmed chord; needs research, not a guess. +- Quick Access Menu for non-Deck pads - Back double-press (500 ms) now routes to the existing Guide+A + chord; the in-session menu, Steam settings, and Setup › Session can swap the single- and double-Back + actions. Device confirmation is still needed. - FlatOut shrink: try `vk_wsi_force_swapchain_to_current_extent=false` via `steamdeck-env`. - Max's stricter `winnative-directaudio` guards; `winnative-epic-launch` (a feature). - Rename before anything truly public: "SteamDeck" is Valve's mark. diff --git a/keystore/release-signer.sha256 b/keystore/release-signer.sha256 new file mode 100644 index 0000000000..21b2147916 --- /dev/null +++ b/keystore/release-signer.sha256 @@ -0,0 +1 @@ +b241ea7d77822d39b89d3227e06f3ecf62adec6cbfd38ad06196787991b5d3f0 diff --git a/tools/build_local.sh b/tools/build_local.sh index 450fef9cc3..cd831a8dfe 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -2,6 +2,15 @@ set -euo pipefail repo_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +if tree_status=$(git -C "${repo_root}" status --porcelain 2>/dev/null); then + if [[ -n "${tree_status}" ]]; then + export DROIDDECK_BUILD_TREE_STATE=dirty + else + export DROIDDECK_BUILD_TREE_STATE=clean + fi +else + export DROIDDECK_BUILD_TREE_STATE=unknown +fi sdk_dir=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-"${HOME}/Library/Android/sdk"}} java_dir=${JAVA_HOME:-"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"} image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v2} diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-pad-defaults b/tools/linuxfs/overlay/usr/local/bin/bannerlator-pad-defaults index 45459a0e26..88e56d76de 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-pad-defaults +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-pad-defaults @@ -180,9 +180,131 @@ SmallMotor = SDL-0/SmallMotor """ +def ini_get(path, section, key): + try: + with open(path, encoding="utf-8", errors="replace") as f: + lines = f.read().splitlines() + except OSError: + return None + span = ini_section(lines, section) + if not span: + return None + for l in lines[span[0]:span[1]]: + if "=" in l and l.split("=", 1)[0].strip() == key: + return l.split("=", 1)[1].strip() + return None + + +def ini_set(path, section, key, value): + """Sets one key (the first of that name) in [section], adding either as needed.""" + with open(path, encoding="utf-8", errors="replace") as f: + lines = f.read().splitlines() + span = ini_section(lines, section) + if span is None: + lines += ["", f"[{section}]", f"{key} = {value}"] + else: + for i in range(span[0], span[1]): + if "=" in lines[i] and lines[i].split("=", 1)[0].strip() == key: + lines[i] = f"{key} = {value}" + break + else: + end = span[1] + while end > span[0] and not lines[end - 1].strip(): + end -= 1 + lines.insert(end, f"{key} = {value}") + with open(path + ".tmp", "w", encoding="utf-8") as f: + f.write("\n".join(lines) + "\n") + os.replace(path + ".tmp", path) + + +def drop_line(path, line): + with open(path, encoding="utf-8", errors="replace") as f: + lines = f.read().splitlines() + kept = [l for l in lines if l.replace(" ", "") != line.replace(" ", "")] + if len(kept) != len(lines): + with open(path + ".tmp", "w", encoding="utf-8") as f: + f.write("\n".join(kept) + "\n") + os.replace(path + ".tmp", path) + + +def system_folder(names, default): + for name in names: + for cand in (name, name.upper()): + d = os.path.join(ROMS, cand) + if os.path.isdir(d): + return d + return os.path.join(ROMS, default) + + +def bios_folder(base): + for name in ("bios", "BIOS", "firmware"): + d = os.path.join(base, name) + if os.path.isdir(d): + return d + d = os.path.join(base, "bios") + if os.path.isdir(ROMS): + try: + os.makedirs(d, exist_ok=True) # where the user is told to put their BIOS + except OSError: + pass + return d + + +# DuckStation (PS1) - set up like ARMSX2: users bring their own BIOS and games, in the ROMs folder. +# Front-end runs use -batch -bigpicture -fullscreen, so the guide button is the pause menu +# (Hotkeys OpenPauseMenu, src/core/hotkeys.cpp), not the analog toggle. Keys from +# src/core/settings.cpp: [BIOS] SearchDirectory, [GPU] Renderer ("Vulkan"), [Main] +# SetupWizardIncomplete (src/duckstation-qt/qthost.cpp). +DUCKSTATION_PAD1_GUIDE_FREE = "\n".join(l for l in DUCKSTATION_PAD1.splitlines() if not l.startswith("Analog ")) + "\n" + + def duckstation(): - for d in (os.path.join(CONFIG, "duckstation"), os.path.join(HOME, ".local/share/duckstation")): - patch_ini_section(os.path.join(d, "settings.ini"), "Pad1", DUCKSTATION_PAD1, "DuckStation") + ps1 = system_folder(("psx", "ps1"), "psx") + d = os.path.join(CONFIG, "duckstation") + ini = os.path.join(d, "settings.ini") + legacy = os.path.join(HOME, ".local/share/duckstation/settings.ini") + if not os.path.isfile(ini) and os.path.isfile(legacy): + ini = legacy + if not os.path.isfile(ini): + # A new player: everything DuckStation's first-time setup asks is answered here (it finds + # the BIOS in its folder by itself), so a game from the front end boots straight away. + bios = bios_folder(ps1) + seed(ini, "[Main]\nSetupWizardIncomplete = false\nInhibitScreensaver = false\n\n" + f"[BIOS]\nSearchDirectory = {bios}\n\n" + f"[GameList]\nRecursivePaths = {ps1}\n\n" + "[GPU]\nRenderer = Vulkan\n\n" + "[Hotkeys]\nOpenPauseMenu = Keyboard/Escape\nOpenPauseMenu = SDL-0/Guide\n\n" + "[Pad1]\n" + DUCKSTATION_PAD1_GUIDE_FREE, "DuckStation", "first-time setup, BIOS from " + bios) + return + patch_ini_section(ini, "Pad1", DUCKSTATION_PAD1_GUIDE_FREE, "DuckStation") + drop_line(ini, "Analog = SDL-0/Guide") + patch_ini_section(ini, "Hotkeys", "OpenPauseMenu = SDL-0/Guide\n", "DuckStation", needle="SDL-0/Guide", + done="the guide button opens the pause menu") + patch_ini_section(ini, "GameList", f"RecursivePaths = {ps1}\n", "DuckStation", needle=ROMS, + done="games listed from the ROMs folder") + # One set up by an earlier build still has its first-time setup pending, in the way of a game. + if ini_get(ini, "Main", "SetupWizardIncomplete") == "true": + ini_set(ini, "Main", "SetupWizardIncomplete", "false") + print("bannerlator-pad-defaults: DuckStation: first-time setup already done here") + # Keeping the screen awake goes through org.freedesktop.ScreenSaver, which nothing in the session + # provides (Android decides when the screen sleeps): DuckStation only warns it failed, every game. + if (ini_get(ini, "Main", "InhibitScreensaver") or "true") == "true": + ini_set(ini, "Main", "InhibitScreensaver", "false") + print("bannerlator-pad-defaults: DuckStation: no screensaver inhibit (no such service here)") + # Once, for a DuckStation set up before this: its own empty BIOS folder moves to the ROMs folder, + # and Automatic becomes Vulkan. A later choice in DuckStation's settings is kept. + marker = os.path.join(os.path.dirname(ini), ".droiddeck-setup") + if os.path.exists(marker): + return + current = ini_get(ini, "BIOS", "SearchDirectory") or "bios" + own = current if os.path.isabs(current) else os.path.join(os.path.dirname(ini), current) + if not (os.path.isdir(own) and os.listdir(own)): + ini_set(ini, "BIOS", "SearchDirectory", bios_folder(ps1)) + print(f"bannerlator-pad-defaults: DuckStation: BIOS from {bios_folder(ps1)}") + if (ini_get(ini, "GPU", "Renderer") or "Automatic") == "Automatic": + ini_set(ini, "GPU", "Renderer", "Vulkan") + print("bannerlator-pad-defaults: DuckStation: renderer Vulkan") + open(marker, "w").close() # PCSX2: FaceSouth/... names (pcsx2/Input/SDLInputSource.cpp), keys from SIO/Pad/PadDualshock2.cpp. @@ -331,17 +453,18 @@ def armsx2(): shutil.copytree(src, os.path.join(root, sub), dirs_exist_ok=True) print(f"bannerlator-pad-defaults: ARMSX2: settings and memory cards copied from PCSX2 ({root})") elif not os.path.isfile(ini): - # A new player: ARMSX2's own first-time setup still runs (SetupWizardIncomplete) to pick the - # BIOS, but looking in the ROMs folder, with the ps2 folder as its game list and the - # controller already on Player 1. + # A new player: everything ARMSX2's first-time setup asks is answered here - the BIOS + # folder in the ROMs folder, the ps2 folder as its game list, the controller on Player 1 - + # and the BIOS file itself is picked below once one is there. bios, games = ps2_bios_folder(), ps2_folder() - seed(ini, "[UI]\nSettingsVersion = 1\nSetupWizardIncomplete = true\n\n" + seed(ini, "[UI]\nSettingsVersion = 1\nSetupWizardIncomplete = false\n\n" f"[Folders]\nBios = {bios}\n\n" f"[GameList]\nRecursivePaths = {games}\n\n" # Vulkan outright rather than Auto's pick: the renderer every other path here uses. "[EmuCore/GS]\nRenderer = 14\n\n" "[Hotkeys]\nOpenPauseMenu = Keyboard/Escape\nOpenPauseMenu = SDL-0/Guide\n\n" "[Pad1]\n" + ARMSX2_PAD1, "ARMSX2", "first-time setup, BIOS from " + bios) + armsx2_bios(ini) return patch_ini_section(ini, "Pad1", ARMSX2_PAD1, "ARMSX2", require="SettingsVersion") # The guide button is the pause menu here; PCSX2's profile (ours, copied over) had it as the @@ -357,6 +480,34 @@ def armsx2(): require="SettingsVersion", done="the guide button opens the pause menu") patch_ini_section(ini, "GameList", f"RecursivePaths = {ps2_folder()}\n", "ARMSX2", needle=ROMS, require="SettingsVersion", done="games listed from the ROMs folder") + if ini_get(ini, "UI", "SetupWizardIncomplete") == "true": + ini_set(ini, "UI", "SetupWizardIncomplete", "false") + print("bannerlator-pad-defaults: ARMSX2: first-time setup already done here") + armsx2_bios(ini) + + +def armsx2_bios(ini): + """PCSX2 boots the one BIOS file named in [Filenames] BIOS (inside [Folders] Bios); its first-time + setup is what names it. With that skipped, the first dump in the folder is named here - a US one + first - while none is named or the named one is gone. A choice made in ARMSX2 is kept.""" + folder = ini_get(ini, "Folders", "Bios") or ps2_bios_folder() + if not os.path.isabs(folder): + folder = os.path.join(os.path.dirname(os.path.dirname(ini)), folder) + current = ini_get(ini, "Filenames", "BIOS") + if current and os.path.isfile(os.path.join(folder, current)): + return + try: + # A PS2 BIOS dump is 4 MiB (a few are 8); the .nvm/.mec files beside it are not dumps. + dumps = sorted(f for f in os.listdir(folder) + if os.path.isfile(os.path.join(folder, f)) and 4 << 20 <= os.path.getsize(os.path.join(folder, f)) <= 8 << 20) + except OSError: + return + if not dumps: + return + us = [f for f in dumps if any(t in f.lower() for t in ("usa", "(us)", "(us,", "ntsc-u"))] + pick = (us or dumps)[0] + ini_set(ini, "Filenames", "BIOS", pick) + print(f"bannerlator-pad-defaults: ARMSX2: BIOS {pick}") def dolphin(): diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session index 0bc8477cd4..bdcc653c9e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session @@ -347,6 +347,22 @@ case $mode in # moments later, so the seeder has only that gap to mark the redistributables as already run. # It stamps each prefix it has covered and skips it thereafter, so the extra passes cost # almost nothing. + # The drawer's "Stretch games to fill the screen" works live: the app writes its choice to + # ~/.droiddeck-fill, and each change goes to gamescope as GAMESCOPE_FORCE_WINDOWS_FULLSCREEN on + # the root window, which it watches. What gamescope was started with is where this begins. + ( + last=${BL_GAMESCOPE_FORCE_FULLSCREEN:-1} + while :; do + sleep 1 + want=$(cat "$HOME/.droiddeck-fill" 2>/dev/null) || continue + case $want in 0|1) ;; *) continue ;; esac + [ "$want" = "$last" ] && continue + if xprop -root -f GAMESCOPE_FORCE_WINDOWS_FULLSCREEN 32c -set GAMESCOPE_FORCE_WINDOWS_FULLSCREEN "$want" 2>/dev/null; then + echo "== stretch games to fill the screen: $want (live)" + last=$want + fi + done + ) & ( beat=0 for _ in $(seq 1 720); do diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat index b7c0659ad1..4156846a5b 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat @@ -87,6 +87,31 @@ bl_game_cpus() { } """ +# Quake III engine games (id Tech 3) set their own resolution and switch the display to it. Under +# gamescope with the ARM64 Proton that switch is refused ("calling CDS: failed, bad mode") and the +# game never gets OpenGL; left at its own size in a window, it draws small in a corner. So these +# titles are told to stay windowed at the session's own size - unless the user's launch options +# already say something about the video mode, which are left as they are. +BL_IDTECH3_SETUP = """ +bl_idtech3() { + BL_EXTRA_ARGS=() + case "${SteamAppId:-${STEAM_COMPAT_APP_ID:-}}" in + # Quake III Arena, Quake III: Team Arena, Return to Castle Wolfenstein, Jedi Academy. + 2200|2350|9010|6020) ;; + *) return 0 ;; + esac + case " $* " in + *r_fullscreen*|*r_mode*|*r_customwidth*|*r_customheight*) + echo "bannerlator-proton: Quake-engine title; its launch options set the video mode, left as they are" >&2 + return 0 ;; + esac + w=${BL_WIDTH:-1280} + h=${BL_HEIGHT:-720} + BL_EXTRA_ARGS=(+set r_fullscreen 0 +set r_mode -1 +set r_customwidth "$w" +set r_customheight "$h") + echo "bannerlator-proton: Quake-engine title: windowed at ${w}x${h}" >&2 +} +""" + BL_DIRECTAUDIO_SETUP = """ bl_directaudio() { base=$1 @@ -152,7 +177,8 @@ for name in %s; do if [ -d "$depot/files/bin-arm64" ] && [ -x "$depot/proton" ]; then bl_directaudio "$depot" bl_game_cpus - exec ${BL_TASKSET:-} "$depot/proton" "$verb" "$@" + bl_idtech3 "$@" + exec ${BL_TASKSET:-} "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" fi done echo "bannerlator-proton: no ARM64 Proton depot yet - the client downloads one as this tool's dependency; retry the launch once it has" >&2 @@ -162,7 +188,7 @@ exit 1 # and a % format would eat that into a single %, leaving a shell expansion that silently does # something else. LAUNCHER_SH = LAUNCHER_SH.replace( - "verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP, 1) + "verb=$1; shift", "verb=$1; shift\n" + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP, 1) # A third-party Proton dropped into compatibilitytools.d - GE-Proton, proton-cachyos, anything of # that shape - is adopted rather than used as shipped, for the same two reasons Valve's ARM64 depot @@ -196,9 +222,10 @@ if [ -f "$fake" ]; then fi bl_directaudio "$here" bl_game_cpus +bl_idtech3 "$@" # Proton takes its base directory from dirname(sys.argv[0]) without resolving it, so it has to be # started from its own tree. -exec ${BL_TASKSET:-} "$here/%s" "$verb" "$@" +exec ${BL_TASKSET:-} "$here/%s" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" """ EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools" { @@ -357,7 +384,7 @@ def adopt_extras(tools): # ${major%%.*} of its own, and putting it through the format would eat both. body = (EXTRA_WRAPPER_SH % entry_point).replace( 'here=$(dirname "$0")', - 'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP, 1) + 'here=$(dirname "$0")\n' + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP, 1) with open(wrapper, "w", encoding="utf-8") as f: f.write(body) os.chmod(wrapper, 0o755) diff --git a/tools/release/axml_rename.py b/tools/release/axml_rename.py new file mode 100644 index 0000000000..ec553a12c7 --- /dev/null +++ b/tools/release/axml_rename.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +# axml_rename.py in.apk out.apk old=new ... : rewrite whole strings in AndroidManifest.xml's string +# pool (binary XML), leaving every other entry of the apk byte-identical. Unsigned output. +import struct, sys, zipfile + +def dec_len8(b, o): + n = b[o]; o += 1 + if n & 0x80: n = ((n & 0x7f) << 8) | b[o]; o += 1 + return n, o + +def dec_len16(b, o): + n = struct.unpack_from('> 8), n & 0xff]) + +def enc_len16(n): + return struct.pack('> 16), n & 0xffff) + +def rewrite(axml, repl): + ftype, fhs, fsize = struct.unpack_from('&2; exit 1; } +command -v keytool >/dev/null || die "keytool not found (Termux: pkg install openjdk-17)" +command -v gh >/dev/null || die "gh not found" +gh auth status >/dev/null 2>&1 || die "gh is not logged in (gh auth login)" +[ -e "$OUT/droiddeck-release.p12" ] && die "a key already exists in $OUT - there must only ever be one" +case "$OUT" in "$repo"|"$repo"/*) die "the key must not be made inside the repo" ;; esac +for env in "${ENVIRONMENTS[@]}"; do + gh api "repos/$REPO/environments/$env" >/dev/null 2>&1 || die "GitHub environment '$env' does not exist yet" +done + +umask 077 +mkdir -p "$OUT" +KS="$OUT/droiddeck-release.p12" +# 48 random characters; PKCS12 uses one password for the store and the key. +KS_PW=$(head -c 60 /dev/urandom | base64 -w0 | tr -d '/+=') +KS_PW=${KS_PW:0:48} +[ ${#KS_PW} -ge 40 ] || die "could not make a password" +export KS_PW +printf '%s\n' "$KS_PW" > "$OUT/password.txt" + +keytool -genkeypair -keystore "$KS" -storetype PKCS12 -alias "$ALIAS" \ + -keyalg RSA -keysize 4096 -validity 10950 -dname "CN=DroidDeck, O=The412Banner" \ + -storepass:env KS_PW -keypass:env KS_PW >/dev/null 2>&1 || die "keytool could not make the key" +listing=$(keytool -list -v -keystore "$KS" -storepass:env KS_PW -alias "$ALIAS") +SHA=$(awk '/SHA256:/ { print $2 }' <<<"$listing" | head -n1 | tr -d ':' | tr 'A-F' 'a-f') +[[ $SHA =~ ^[0-9a-f]{64}$ ]] || die "could not read the key's certificate digest" + +for env in "${ENVIRONMENTS[@]}"; do + base64 -w0 < "$KS" | gh secret set RELEASE_KEYSTORE_B64 --env "$env" -R "$REPO" >/dev/null + printf '%s' "$KS_PW" | gh secret set RELEASE_STORE_PASSWORD --env "$env" -R "$REPO" >/dev/null + echo "secrets set for environment: $env" +done +unset KS_PW + +printf '%s\n' "$SHA" > "$repo/keystore/release-signer.sha256" +cat < +# +# Turns a CI build (signed with the public AOSP testkey) into one package of tools/release/variants.txt +# signed with DroidDeck's own key, carrying the hand-over from the testkey: +# - v1 + v2 are signed by the testkey, v3 by our key, with a signed lineage testkey -> our key; +# - an install from before (testkey) updates to it and keeps its data; +# - the testkey loses its rollback right, so an apk signed with the testkey alone - which anyone +# can make - is refused as an update to it (device-proven on the Pocket FIT, 2026-09-24); +# - --rotation-min-sdk-version 28: the lineage applies from Android 9, not only from 13. +# +# The key comes from the environment and is never written anywhere but the path given: +# RELEASE_KEYSTORE path to the PKCS12 keystore +# RELEASE_STORE_PASSWORD its password (the key has the same one: PKCS12) +# RELEASE_KEY_ALIAS the key's alias +# BUILD_TOOLS Android build-tools dir (zipalign, apksigner, aapt) +# RELEASE_SIGNER_SHA256 optional: the expected certificate digest, else keystore/release-signer.sha256 +set -euo pipefail + +die() { echo "::error::$*" >&2; exit 1; } +[ $# -eq 3 ] || die "usage: sign-apk.sh " +in=$1 variant=$2 out=$3 +here=$(cd "$(dirname "$0")" && pwd) +repo=$(cd "$here/../.." && pwd) + +pkg=$(awk -v v="$variant" '!/^#/ && $1 == v { print $2 }' "$here/variants.txt") +[ -n "$pkg" ] || die "no variant '$variant' in tools/release/variants.txt" +expected=${RELEASE_SIGNER_SHA256:-$(tr -d ' \n' < "$repo/keystore/release-signer.sha256" 2>/dev/null || true)} +[[ $expected =~ ^[0-9a-f]{64}$ ]] \ + || die "keystore/release-signer.sha256 is missing: make the key first (tools/release/make-release-key.sh)" +: "${RELEASE_KEYSTORE:?}" "${RELEASE_STORE_PASSWORD:?}" "${RELEASE_KEY_ALIAS:?}" "${BUILD_TOOLS:?}" +[ -s "$RELEASE_KEYSTORE" ] || die "the release keystore is empty - is the secret set for this environment?" + +TESTKEY="$repo/keystore/testkey.p12" +TESTKEY_SHA256=a40da80a59d170caa950cf15c18c454d47a39b26989d8b640ecd745ba71bf5dc +export TESTKEY_PASSWORD=android +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +# The package name and everything the manifest derives from it; component class names stay. +P=com.droiddeck.launcher +if [ "$pkg" = "$P" ]; then + python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" +else + python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" \ + "$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \ + "$P.documents=$pkg.documents" "$P.home=$pkg.home" \ + "$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION" +fi +got=$("$BUILD_TOOLS/aapt" dump badging "$work/renamed.apk" | sed -n "s/^package: name='\([^']*\)'.*/\1/p") +[ "$got" = "$pkg" ] || die "$variant: the apk says package '$got', not '$pkg'" +if [ "$pkg" != "$P" ]; then + # A provider left on the old authority would clash with the standard app installed beside it. + tree=$("$BUILD_TOOLS/aapt" dump xmltree "$work/renamed.apk" AndroidManifest.xml) + grep -E 'android:(authorities|taskAffinity)' <<<"$tree" | grep -F "\"$P." \ + && die "$variant: the manifest still names $P in an authority or task" +fi + +"$BUILD_TOOLS/zipalign" -p -f 4 "$work/renamed.apk" "$work/aligned.apk" + +# The lineage: the testkey vouches for our key. Made fresh each time (it is two certificates and +# a signature, nothing secret beyond the key that signs it). +"$BUILD_TOOLS/apksigner" rotate --out "$work/lineage" \ + --old-signer --ks "$TESTKEY" --ks-type PKCS12 --ks-pass env:TESTKEY_PASSWORD \ + --ks-key-alias testkey --key-pass env:TESTKEY_PASSWORD --set-rollback false \ + --new-signer --ks "$RELEASE_KEYSTORE" --ks-type PKCS12 --ks-pass env:RELEASE_STORE_PASSWORD \ + --ks-key-alias "$RELEASE_KEY_ALIAS" --key-pass env:RELEASE_STORE_PASSWORD + +"$BUILD_TOOLS/apksigner" sign \ + --ks "$TESTKEY" --ks-type PKCS12 --ks-pass env:TESTKEY_PASSWORD \ + --ks-key-alias testkey --key-pass env:TESTKEY_PASSWORD \ + --next-signer --ks "$RELEASE_KEYSTORE" --ks-type PKCS12 --ks-pass env:RELEASE_STORE_PASSWORD \ + --ks-key-alias "$RELEASE_KEY_ALIAS" --key-pass env:RELEASE_STORE_PASSWORD \ + --lineage "$work/lineage" --rotation-min-sdk-version 28 \ + --v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true --v4-signing-enabled false \ + --out "$out" "$work/aligned.apk" +rm -f "$out.idsig" + +# What the apk must carry, checked rather than assumed. +"$BUILD_TOOLS/apksigner" verify --min-sdk-version 26 "$out" >/dev/null || die "$variant: does not verify" +# (Listed first, then searched: grep -q stops reading early, which fails a pipe under pipefail.) +listing=$(unzip -l "$out") +grep -qE 'META-INF/.*\.(SF|RSA)$' <<<"$listing" || die "$variant: no JAR signature (old installers)" +# Android 9+ must see our key and only our key. apksigner labels signers "Signer #1", "Signer +# (minSdkVersion=28, ...)" or "V3.0 Signer:" depending on its version; the digests are what count. +certs=$("$BUILD_TOOLS/apksigner" verify --min-sdk-version 28 --print-certs "$out") +v3=$(sed -n 's/^.*Signer.* certificate SHA-256 digest: //p' <<<"$certs" | sort -u) +if [ "$v3" != "$expected" ]; then + echo "$certs" >&2 + die "$variant: Android 9+ sees signer(s) [$(tr '\n' ' ' <<<"$v3")], not only DroidDeck's key $expected" +fi +lineage=$("$BUILD_TOOLS/apksigner" lineage --in "$out" --print-certs) +grep -q "Signer #1 in lineage certificate SHA-256 digest: $TESTKEY_SHA256" <<<"$lineage" \ + || die "$variant: the lineage does not start at the testkey - old installs could not update" +grep -q "Signer #2 in lineage certificate SHA-256 digest: $expected" <<<"$lineage" \ + || die "$variant: the lineage does not hand over to DroidDeck's key" +rollback=$(awk '/Signer #1 in lineage/{s=1} /Signer #2 in lineage/{s=0} s && /rollback capability/' <<<"$lineage") +grep -q false <<<"$rollback" \ + || die "$variant: the testkey kept its rollback right - a testkey-signed apk could replace this one" +echo "$variant ($pkg): signed, hand-over from the testkey, v3 signer $expected" diff --git a/tools/release/variants.txt b/tools/release/variants.txt new file mode 100644 index 0000000000..6071068008 --- /dev/null +++ b/tools/release/variants.txt @@ -0,0 +1,9 @@ +# The packages a signed build ships as. The same apk, with only the manifest's package name (and +# the names derived from it) changed: some phones give their performance modes only to apps with +# certain names. Each is its own app to Android - installs beside the others, with its own data. +# +# name package file suffix +standard com.droiddeck.launcher - +pubg com.tencent.ig -pubg +antutu com.antutu.benchmark.full -antutu +ludashi com.ludashi.benchmark -ludashi