Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
332c4ea751 | ||
|
|
41b065e89c | ||
|
|
bc35bb5d43 | ||
|
|
c378489f45 | ||
|
|
ef4e43032c | ||
|
|
62f49756bf | ||
|
|
510c7e35e6 | ||
|
|
57578501e5 | ||
|
|
53b5fde2ff | ||
|
|
6f5db08efb | ||
|
|
d9efc1efee | ||
|
|
f44e3c46e1 | ||
|
|
51e911f9a8 | ||
|
|
f0f17b9b63 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
# GitHub PR openers trusted for automatic release-signed test builds.
|
||||
FX192
|
||||
K11MCH1
|
||||
kingokksa
|
||||
ovurrsl
|
||||
+35
-157
@@ -8,8 +8,6 @@ on:
|
||||
- '**/*.md'
|
||||
- 'LICENSE'
|
||||
- '.gitignore'
|
||||
- 'docs/**'
|
||||
- '.github/ISSUE_TEMPLATE/**'
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
types: [ opened, synchronize, reopened, ready_for_review ]
|
||||
@@ -17,8 +15,6 @@ on:
|
||||
- '**/*.md'
|
||||
- 'LICENSE'
|
||||
- '.gitignore'
|
||||
- 'docs/**'
|
||||
- '.github/ISSUE_TEMPLATE/**'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
rebuild_preloads:
|
||||
@@ -32,8 +28,8 @@ permissions:
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: build-${{ github.event.pull_request.number || (github.event_name == 'push' && 'main') || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' }}
|
||||
group: build-${{ github.event.pull_request.number || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
source:
|
||||
@@ -282,8 +278,6 @@ jobs:
|
||||
timeout-minutes: 45
|
||||
outputs:
|
||||
variants: ${{ steps.variants.outputs.list }}
|
||||
build: ${{ steps.build.outcome }}
|
||||
apk: ${{ steps.apk-upload.outcome }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -410,7 +404,7 @@ jobs:
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
cache-read-only: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
|
||||
cache-cleanup: ${{ github.event_name == 'pull_request' && 'never' || 'on-success' }}
|
||||
cache-cleanup: on-success
|
||||
|
||||
- name: Resolve the pinned Android NDK
|
||||
run: bash tools/ci/resolve-ndk.sh
|
||||
@@ -547,6 +541,29 @@ jobs:
|
||||
path: app/src/main/rust/stores/Cargo.lock
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Unit tests
|
||||
id: unit-tests
|
||||
env:
|
||||
DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }}
|
||||
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
|
||||
run: |
|
||||
set -o pipefail
|
||||
mkdir -p app/build
|
||||
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
|
||||
|
||||
- name: Upload unit test diagnostics
|
||||
id: unit-test-diagnostics
|
||||
if: always() && steps.unit-tests.outcome != 'skipped'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: unit-test-results
|
||||
path: |
|
||||
app/build/unit-tests.log
|
||||
app/build/test-results/testReleaseUnitTest/
|
||||
app/build/reports/tests/testReleaseUnitTest/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
- name: Sign with the testkey (v1 + v2 + v3)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -592,156 +609,18 @@ jobs:
|
||||
retention-days: 30
|
||||
compression-level: 0
|
||||
|
||||
- name: Keep the build log for the pull request report
|
||||
if: always() && github.event_name == 'pull_request'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: build-report
|
||||
path: |
|
||||
/tmp/build.log
|
||||
/tmp/pr-merge.md
|
||||
if-no-files-found: ignore
|
||||
retention-days: 1
|
||||
|
||||
unit-tests:
|
||||
needs: [source, components, xbox]
|
||||
name: Android unit tests
|
||||
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
outputs:
|
||||
outcome: ${{ steps.unit-tests.outcome }}
|
||||
diagnostics: ${{ steps.unit-test-diagnostics.outputs.artifact-url }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Merge the pinned APK base
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
BUILD_BASE_SHA: ${{ needs.source.outputs.base-sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch --no-tags origin "$BUILD_BASE_SHA"
|
||||
git config user.name "ci"
|
||||
git config user.email "ci@users.noreply.github.com"
|
||||
git merge --no-ff --no-edit FETCH_HEAD
|
||||
- name: Verify backend and APK source match
|
||||
env:
|
||||
XBOX_SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
||||
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
cache-read-only: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
|
||||
cache-cleanup: ${{ github.event_name == 'pull_request' && 'never' || 'on-success' }}
|
||||
|
||||
- name: Resolve the pinned Android NDK
|
||||
run: bash tools/ci/resolve-ndk.sh
|
||||
|
||||
- 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 "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV"
|
||||
echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV"
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: prepared-components
|
||||
path: app/build
|
||||
- name: Verify and unpack prepared components
|
||||
env:
|
||||
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
||||
run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE"
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: xbox-arm64
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
|
||||
|
||||
- name: Cache checksum-pinned pack inputs
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/droiddeck-pack-inputs
|
||||
key: pack-inputs-v1-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env') }}
|
||||
restore-keys: pack-inputs-v1-
|
||||
- name: Build the add-on packs
|
||||
run: bash tools/packs/build.sh app/build/packs
|
||||
|
||||
- name: Unit tests
|
||||
id: unit-tests
|
||||
env:
|
||||
DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }}
|
||||
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
|
||||
run: |
|
||||
set -o pipefail
|
||||
mkdir -p app/build
|
||||
python3 tools/release/runtime_inputs.py record
|
||||
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PskipRust=true -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
|
||||
|
||||
- name: Upload unit test diagnostics
|
||||
id: unit-test-diagnostics
|
||||
if: always() && steps.unit-tests.outcome != 'skipped'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: unit-test-results
|
||||
path: |
|
||||
app/build/unit-tests.log
|
||||
app/build/test-results/testReleaseUnitTest/
|
||||
app/build/reports/tests/testReleaseUnitTest/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
report:
|
||||
name: Report the build on the pull request
|
||||
needs: [build, unit-tests]
|
||||
if: ${{ always() && github.event_name == 'pull_request' && !github.event.pull_request.draft }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
persist-credentials: false
|
||||
- uses: actions/download-artifact@v4
|
||||
continue-on-error: true
|
||||
with:
|
||||
name: build-report
|
||||
path: /tmp
|
||||
- name: Report on the pull request
|
||||
if: always() && github.event_name == 'pull_request'
|
||||
continue-on-error: true
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
BUILD_OUTCOME: ${{ needs.build.outputs.build || needs.build.result }}
|
||||
UNIT_TEST_OUTCOME: ${{ needs.unit-tests.result }}
|
||||
TEST_DIAGNOSTICS_URL: ${{ needs.unit-tests.outputs.diagnostics }}
|
||||
APK_OUTCOME: ${{ needs.build.result == 'success' && needs.build.outputs.apk || needs.build.result }}
|
||||
BUILD_OUTCOME: ${{ steps.build.outcome }}
|
||||
UNIT_TEST_OUTCOME: ${{ steps.unit-tests.outcome }}
|
||||
TEST_DIAGNOSTICS_URL: ${{ steps.unit-test-diagnostics.outputs.artifact-url }}
|
||||
APK_OUTCOME: ${{ steps.apk-upload.outcome }}
|
||||
SAME_REPO: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
|
||||
run: bash tools/release/report-build.sh
|
||||
|
||||
python-tests:
|
||||
@@ -803,11 +682,11 @@ jobs:
|
||||
timeout 10 /tmp/test-presenter-shutdown
|
||||
|
||||
- name: Steam import and game environment tests
|
||||
run: bash tools/ci/run-python-tests.sh
|
||||
run: python3 -m unittest discover -s tools/tests -p 'test_*.py'
|
||||
|
||||
checks:
|
||||
name: Compile and test APK
|
||||
needs: [build, unit-tests, python-tests]
|
||||
needs: [build, python-tests]
|
||||
if: ${{ always() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }}
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
@@ -815,9 +694,8 @@ jobs:
|
||||
- name: Require compilation and every test job
|
||||
env:
|
||||
BUILD_RESULT: ${{ needs.build.result }}
|
||||
UNIT_RESULT: ${{ needs.unit-tests.result }}
|
||||
PYTHON_RESULT: ${{ needs.python-tests.result }}
|
||||
run: test "$BUILD_RESULT" = success && test "$UNIT_RESULT" = success && test "$PYTHON_RESULT" = success
|
||||
run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success
|
||||
|
||||
sign:
|
||||
needs: [build, checks]
|
||||
|
||||
@@ -8,10 +8,6 @@ on:
|
||||
description: Open pull request number
|
||||
required: true
|
||||
type: string
|
||||
automatic_build_run_id:
|
||||
description: Completed build run for automatic publishing
|
||||
required: false
|
||||
type: string
|
||||
pull_request_target:
|
||||
types: [labeled]
|
||||
branches: [main]
|
||||
@@ -31,47 +27,16 @@ concurrency:
|
||||
queue: max
|
||||
|
||||
jobs:
|
||||
dispatch-fork-builds:
|
||||
if: >-
|
||||
github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' &&
|
||||
github.event.workflow_run.conclusion == 'success' &&
|
||||
github.event.workflow_run.head_repository.full_name != github.repository
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
pull-requests: read
|
||||
steps:
|
||||
- name: Find fork PRs for the completed build
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RUN_ID: ${{ github.event.workflow_run.id }}
|
||||
RUN_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
RUN_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
|
||||
RUN_BRANCH: ${{ github.event.workflow_run.head_branch }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
owner=${RUN_REPO%%/*}
|
||||
gh api --paginate --slurp -X GET "repos/$GITHUB_REPOSITORY/pulls" \
|
||||
-f state=open -f base=main -f "head=$owner:$RUN_BRANCH" -f per_page=100 |
|
||||
jq -r --arg sha "$RUN_SHA" --arg repo "$RUN_REPO" --arg branch "$RUN_BRANCH" '
|
||||
.[][] | select(.head.sha == $sha and .head.repo.full_name == $repo and .head.ref == $branch) | .number' |
|
||||
while IFS= read -r number; do
|
||||
gh workflow run pr-release-publish.yml -R "$GITHUB_REPOSITORY" --ref main \
|
||||
-f "pr_number=$number" -f "automatic_build_run_id=$RUN_ID"
|
||||
done
|
||||
|
||||
authorize:
|
||||
if: >-
|
||||
(github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') ||
|
||||
(github.event_name == 'pull_request_target' &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'publish-test')) ||
|
||||
(github.event_name == 'pull_request_target' && github.event.label.name == 'publish-test') ||
|
||||
(github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' &&
|
||||
github.event.workflow_run.conclusion == 'success' &&
|
||||
github.event.workflow_run.head_repository.full_name == github.repository &&
|
||||
github.event.workflow_run.pull_requests[0] != null)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 150
|
||||
timeout-minutes: 45
|
||||
outputs:
|
||||
pr_number: ${{ steps.gate.outputs.pr_number }}
|
||||
run_id: ${{ steps.gate.outputs.run_id }}
|
||||
@@ -85,7 +50,6 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: The packages a signed build ships as
|
||||
id: variants
|
||||
@@ -97,14 +61,22 @@ jobs:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
REQUESTER: ${{ github.actor }}
|
||||
PR_NUMBER: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }}
|
||||
ACTION: ${{ github.event.action }}
|
||||
BUILT_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
AUTO_RUN: ${{ inputs.automatic_build_run_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$PR_NUMBER" =~ ^[1-9][0-9]*$ ]] || { echo "::error::Invalid PR number '$PR_NUMBER'"; exit 1; }
|
||||
skip() { echo "::notice::Not publishing PR #$PR_NUMBER: $1"; echo "skip=true" >> "$GITHUB_OUTPUT"; exit 0; }
|
||||
if [ "$EVENT_NAME" = pull_request_target ] && [ "$ACTION" = labeled ]; then
|
||||
if [ "$EVENT_NAME" = workflow_run ]; then
|
||||
echo "automatic=true" >> "$GITHUB_OUTPUT"
|
||||
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
||||
[ "$(jq -r .state <<<"$pr")" = open ] || skip "it is not open"
|
||||
[ "$(jq -r .draft <<<"$pr")" = false ] || skip "it is a draft"
|
||||
[ "$(jq -r .base.ref <<<"$pr")" = main ] || skip "it does not target main"
|
||||
[ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork"
|
||||
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
|
||||
[ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building"
|
||||
fi
|
||||
if [ "$EVENT_NAME" = pull_request_target ]; then
|
||||
permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$REQUESTER/permission" --jq .permission)
|
||||
case "$permission" in
|
||||
admin|maintain|write) ;;
|
||||
@@ -113,59 +85,29 @@ jobs:
|
||||
fi
|
||||
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
||||
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null ||
|
||||
skip "it must be open, ready for review, and target main"
|
||||
if [ "$EVENT_NAME" = workflow_run ]; then
|
||||
[ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] || skip "it comes from a fork"
|
||||
[ "$(jq -r .head.sha <<<"$pr")" = "$BUILT_SHA" ] || skip "a newer push is building"
|
||||
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
|
||||
echo "automatic=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ "$EVENT_NAME" = workflow_dispatch ] && [ -n "$AUTO_RUN" ]; then
|
||||
[[ "$AUTO_RUN" =~ ^[1-9][0-9]*$ ]] || { echo '::error::Invalid automatic build run ID'; exit 1; }
|
||||
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$pr" >/dev/null && skip "it is labelled no-test-build"
|
||||
git fetch --no-tags origin main
|
||||
opener=$(jq -r .user.login <<<"$pr")
|
||||
git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$opener" || skip "PR opener @$opener is not trusted for automatic signing"
|
||||
echo "automatic=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
{ echo "::error::PR #$PR_NUMBER must be open, ready for review, and target main"; exit 1; }
|
||||
head=$(jq -r '.head.sha' <<<"$pr")
|
||||
base=$(jq -r '.base.sha' <<<"$pr")
|
||||
|
||||
run_id=
|
||||
for attempt in $(seq 1 240); do
|
||||
latest=$(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/build.yml/runs?event=pull_request&head_sha=$head&per_page=100" |
|
||||
jq -c --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
|
||||
[.workflow_runs[] | select(.head_sha == $head and .head_repository.full_name == $repo and .head_branch == $ref)] |
|
||||
sort_by([.created_at, .run_attempt]) | last // empty')
|
||||
if [[ -z "$latest" && "$attempt" == 1 ]]; then
|
||||
git fetch --no-tags origin main
|
||||
git fetch --no-tags origin "refs/pull/$PR_NUMBER/head"
|
||||
git diff --no-renames --name-only -z "$base...FETCH_HEAD" > "$RUNNER_TEMP/pr-changed-paths"
|
||||
excluded=true
|
||||
while IFS= read -r -d '' path; do
|
||||
case "$path" in
|
||||
*.md|LICENSE|.gitignore) ;;
|
||||
*) excluded=false; break ;;
|
||||
esac
|
||||
done < "$RUNNER_TEMP/pr-changed-paths"
|
||||
[ "$excluded" = false ] || skip "its changes do not trigger the APK build"
|
||||
fi
|
||||
for attempt in $(seq 1 60); do
|
||||
latest=$(gh run list -R "$GITHUB_REPOSITORY" --workflow build.yml \
|
||||
--event pull_request --commit "$head" \
|
||||
--json databaseId,headSha,status,conclusion,createdAt,attempt -L 100 |
|
||||
jq -c --arg head "$head" '[.[] | select(.headSha == $head)] |
|
||||
sort_by([.createdAt, .attempt]) | last // empty')
|
||||
if [[ -n "$latest" && $(jq -r .status <<<"$latest") == completed ]]; then
|
||||
conclusion=$(jq -r .conclusion <<<"$latest")
|
||||
if [[ "$conclusion" == success ]]; then
|
||||
run_id=$(jq -r .id <<<"$latest")
|
||||
if [ -n "$AUTO_RUN" ] && [ "$run_id" != "$AUTO_RUN" ]; then
|
||||
skip "a newer build exists"
|
||||
fi
|
||||
break
|
||||
fi
|
||||
[[ "$conclusion" == action_required ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; }
|
||||
[[ "$conclusion" == success ]] || { echo "::error::The latest PR build is not green ($conclusion)"; exit 1; }
|
||||
run_id=$(jq -r .databaseId <<<"$latest")
|
||||
break
|
||||
fi
|
||||
status=not-started
|
||||
[[ -z "$latest" ]] || status=$(jq -r .status <<<"$latest")
|
||||
echo "Waiting for the PR build of ${head:0:7} to finish ($status)"
|
||||
sleep 30
|
||||
done
|
||||
[[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 120 minutes'; exit 1; }
|
||||
[[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 30 minutes'; exit 1; }
|
||||
run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id")
|
||||
jq -e --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
|
||||
.event == "pull_request" and .head_sha == $head and .conclusion == "success" and
|
||||
@@ -195,13 +137,6 @@ jobs:
|
||||
.head.sha == $head and .base.sha == $base
|
||||
' <<<"$current" >/dev/null ||
|
||||
{ echo "::error::PR #$PR_NUMBER moved on while its build was checked; publish again"; exit 1; }
|
||||
if [ "$EVENT_NAME" = workflow_run ] || { [ "$EVENT_NAME" = workflow_dispatch ] && [ -n "$AUTO_RUN" ]; }; then
|
||||
jq -e 'any(.labels[]; .name == "no-test-build")' <<<"$current" >/dev/null && skip "it is labelled no-test-build"
|
||||
if [ "$EVENT_NAME" = workflow_dispatch ]; then
|
||||
git fetch --no-tags origin main
|
||||
git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$(jq -r .user.login <<<"$current")" || skip "the PR opener is no longer trusted"
|
||||
fi
|
||||
fi
|
||||
{
|
||||
echo "pr_number=$PR_NUMBER"
|
||||
echo "run_id=$run_id"
|
||||
@@ -336,24 +271,17 @@ jobs:
|
||||
echo "release=$release" >> "$GITHUB_OUTPUT"
|
||||
echo "apk=$GITHUB_SERVER_URL/$repo/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Whether the PR opener is trusted
|
||||
id: trusted-opener
|
||||
- name: Whether the PR's branch is in this repo
|
||||
id: same-repo
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
|
||||
run: |
|
||||
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
||||
opener=$(jq -r .user.login <<<"$pr")
|
||||
git fetch --no-tags origin main
|
||||
if [ "$(jq -r .head.repo.full_name <<<"$pr")" = "$GITHUB_REPOSITORY" ] ||
|
||||
git show origin/main:.github/trusted-test-builds.txt | grep -Fixq -- "$opener"; then
|
||||
echo "trusted=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "trusted=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
head_repo=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .head.repo.full_name)
|
||||
echo "same=$([ "$head_repo" = "$GITHUB_REPOSITORY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Clear the publish request label
|
||||
if: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && steps.publish.outcome == 'success' }}
|
||||
if: ${{ github.event_name == 'pull_request_target' && steps.publish.outcome == 'success' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
|
||||
@@ -367,12 +295,12 @@ jobs:
|
||||
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
|
||||
RELEASE: ${{ steps.publish.outputs.release }}
|
||||
APK: ${{ steps.publish.outputs.apk }}
|
||||
TRUSTED_OPENER: ${{ steps.trusted-opener.outputs.trusted }}
|
||||
SAME_REPO: ${{ steps.same-repo.outputs.same }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
short=${HEAD_SHA:0:7}
|
||||
mark='<!-- droiddeck-pr-release -->'
|
||||
if [ "$TRUSTED_OPENER" = true ]; then
|
||||
if [ "$SAME_REPO" = true ]; then
|
||||
NEXT='Each green build of a new push is signed and published here on its own. Label the PR `no-test-build` to stop that.'
|
||||
else
|
||||
NEXT='Pushes to this PR do not re-sign automatically. After a new green build, a maintainer can add the `publish-test` label again.'
|
||||
|
||||
@@ -61,7 +61,7 @@ Compatibility and performance vary by device; hardware validation is limited. De
|
||||
|
||||
## Credits and licence
|
||||
|
||||
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. Its games install from Stores through Blizzard's own Agent and the local HTTP API it serves, driven the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) drives it, with the requests described on [wowdev.wiki](https://wowdev.wiki/Agent); how other launchers find, install and start Blizzard games was read in [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader, without taking their code. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. x86 AppImages packed with [sharun](https://github.com/VHSgunzo/sharun) by VHSgunzo (MIT) start because DroidDeck's own [FEX](https://github.com/FEX-Emu/FEX) build (MIT) puts the platform name under `AT_PLATFORM`, which sharun's [userland-execve](https://crates.io/crates/userland-execve) loader (MIT) requires; FEX filed it under `AT_BASE_PLATFORM`. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultLine truncated
|
||||
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. Its games install from Stores through Blizzard's own Agent and the local HTTP API it serves, driven the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) drives it, with the requests described on [wowdev.wiki](https://wowdev.wiki/Agent); how other launchers find, install and start Blizzard games was read in [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader, without taking their code. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. x86 AppImages packed with [sharun](https://github.com/VHSgunzo/sharun) by VHSgunzo (MIT) start because DroidDeck's own [FEX](https://github.com/FEX-Emu/FEX) build (MIT) puts the platform name under `AT_PLATFORM`, which sharun's [userland-execve](https://crates.io/crates/userland-execve) loader (MIT) requires; FEX filed it under `AT_BASE_PLATFORM`. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultLine truncated
|
||||
|
||||
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
|
||||
|
||||
@@ -71,8 +71,6 @@ Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge
|
||||
|
||||
The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead.
|
||||
|
||||
Remote Play from a PC to the arm64 Steam client goes through a stand-in for the V4L2 decoder and the libdrm dumb buffers that Steam's `streaming_client` expects: each frame is decoded by Android's MediaCodec through the app, or by the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) that ships in Steam's own runtime, into dma-heap buffers that its Vulkan renderer imports. The Qualcomm low-latency decoder settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0).
|
||||
|
||||
Steam's Browse buttons open a GTK 3 file chooser through PyGObject (LGPL-2.1-or-later). It runs under Steam's own `reaper` with Steam's app ID, which [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) reads from the process tree (`GetAppIdFromReaper` in `src/Utils/Process.cpp`) to show it over Steam.
|
||||
|
||||
Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose fixes for them (`311210.py` sets ALSA audio, `570940.py` installs VC++ 2017) fail under ARM64 Proton.
|
||||
@@ -325,6 +325,57 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
|
||||
if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir)
|
||||
tasks.named('preBuild').configure { dependsOn(buildRustStores) }
|
||||
|
||||
// GeForce NOW: DroidDeck's streamer host (libdroiddeckgfn.so, src/main/rust/gfn) and OpenNOW's
|
||||
// core service (external/opennow, MIT, by Zortos). The core is a program the app runs as a child
|
||||
// process, so it ships as libopennowcore.so in the native library directory (the one place the
|
||||
// app may exec from), like the Mali bridge server.
|
||||
def gfnCrateDir = layout.projectDirectory.dir('src/main/rust/gfn')
|
||||
def openNowCoreDir = rootProject.layout.projectDirectory.dir('external/opennow/native/opennow-core')
|
||||
def gfnJniLibsDir = layout.buildDirectory.dir('gfnJniLibs')
|
||||
def gfnCargoEnvironment = { Exec task ->
|
||||
def cargoBin = "${System.getProperty('user.home')}/.cargo/bin"
|
||||
task.environment 'PATH', "${cargoBin}${File.pathSeparator}${System.getenv('PATH')}"
|
||||
task.environment 'ANDROID_NDK_HOME', android.ndkDirectory.absolutePath
|
||||
task.environment 'CARGO_TERM_COLOR', 'never'
|
||||
// bindgen (the mtu crate) otherwise passes an unversioned Android triple, which the NDK headers reject.
|
||||
task.environment 'BINDGEN_EXTRA_CLANG_ARGS_aarch64_linux_android', '--target=aarch64-linux-android29'
|
||||
}
|
||||
def buildGfnHost = tasks.register('buildGfnHost', Exec) {
|
||||
description = 'Cross-compiles the GeForce NOW streamer host (libdroiddeckgfn.so) with cargo-ndk.'
|
||||
onlyIf { !skipRust }
|
||||
inputs.dir(gfnCrateDir.dir('src'))
|
||||
inputs.files(gfnCrateDir.file('Cargo.toml'), gfnCrateDir.file('Cargo.lock'))
|
||||
inputs.dir(rootProject.file('external/opennow/native/opennow-streamer/crates'))
|
||||
inputs.property('ndkVersion', android.ndkVersion)
|
||||
outputs.dir(gfnJniLibsDir)
|
||||
workingDir gfnCrateDir
|
||||
gfnCargoEnvironment(it)
|
||||
commandLine 'rustup', 'run', 'stable', 'cargo', 'ndk', '--target', 'arm64-v8a', '--platform', '29',
|
||||
'--output-dir', gfnJniLibsDir.get().asFile.absolutePath,
|
||||
'build', '--release', '--locked'
|
||||
}
|
||||
def buildOpenNowCore = tasks.register('buildOpenNowCore', Exec) {
|
||||
description = "Cross-compiles OpenNOW's core service and stages it as libopennowcore.so."
|
||||
onlyIf { !skipRust }
|
||||
inputs.dir(openNowCoreDir.dir('src'))
|
||||
inputs.files(openNowCoreDir.file('Cargo.toml'), openNowCoreDir.file('Cargo.lock'))
|
||||
inputs.property('ndkVersion', android.ndkVersion)
|
||||
outputs.file(gfnJniLibsDir.map { it.file('arm64-v8a/libopennowcore.so') })
|
||||
workingDir openNowCoreDir
|
||||
gfnCargoEnvironment(it)
|
||||
commandLine 'rustup', 'run', 'stable', 'cargo', 'ndk', '--target', 'arm64-v8a', '--platform', '29',
|
||||
'build', '--release', '--locked', '--bin', 'opennow-core'
|
||||
doLast {
|
||||
def built = openNowCoreDir.file('target/aarch64-linux-android/release/opennow-core').asFile
|
||||
def staged = gfnJniLibsDir.get().file('arm64-v8a/libopennowcore.so').asFile
|
||||
staged.parentFile.mkdirs()
|
||||
java.nio.file.Files.copy(built.toPath(), staged.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
}
|
||||
}
|
||||
buildOpenNowCore.configure { mustRunAfter(buildGfnHost) }
|
||||
if (!skipRust) android.sourceSets.main.jniLibs.srcDir(gfnJniLibsDir)
|
||||
tasks.named('preBuild').configure { dependsOn(buildGfnHost, buildOpenNowCore) }
|
||||
|
||||
dependencies {
|
||||
implementation "org.opencv:opencv:${trackingPack.OPENCV_VERSION}"
|
||||
implementation 'org.khronos.openxr:openxr_loader_for_android:1.1.49'
|
||||
|
||||
@@ -30,7 +30,6 @@
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
|
||||
@@ -59,15 +58,6 @@
|
||||
<meta-data android:name="android.game_mode_config" android:resource="@xml/game_mode_config" />
|
||||
<service android:name=".glasses.LumaRgbCaptureService" android:exported="false"
|
||||
android:process=":rgb_diagnostic" />
|
||||
<service android:name=".input.HomeButtonService"
|
||||
android:label="@string/integration_shortcuts_service"
|
||||
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.accessibilityservice.AccessibilityService" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
|
||||
</service>
|
||||
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
|
||||
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
|
||||
android:permission="android.permission.DUMP"
|
||||
@@ -82,17 +72,6 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".PairingGuideActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity="${applicationId}.pairingguide"
|
||||
android:excludeFromRecents="true"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".FrontEndActivity"
|
||||
android:exported="true"
|
||||
@@ -158,18 +137,6 @@
|
||||
</activity>
|
||||
|
||||
|
||||
<activity
|
||||
android:name=".PinRequestActivity"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:taskAffinity="${applicationId}.pin"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
|
||||
<intent-filter>
|
||||
<action android:name="android.content.pm.action.CONFIRM_PIN_SHORTCUT" />
|
||||
<action android:name="android.content.pm.action.CONFIRM_PIN_APPWIDGET" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".input.ControllerEditorActivity"
|
||||
android:exported="false"
|
||||
@@ -213,6 +180,15 @@
|
||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<!-- GeForce NOW (OpenNOW's core and streamer): the core child and the player share the :gfn process;
|
||||
the Stores page reaches the core through GfnCoreService. -->
|
||||
<service android:name=".stores.gfn.GfnCoreService" android:exported="false" android:process=":gfn" />
|
||||
|
||||
<activity android:name=".stores.gfn.GfnPlayerActivity" android:exported="false"
|
||||
android:process=":gfn" android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
|
||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity android:name=".stores.xbox.XboxCloudSettingsActivity" android:exported="false"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
#define VENC_MAX_BUFFERS 16
|
||||
|
||||
enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5, VDEC_CONFIG = 6, VDEC_CAPTURE = 7, VDEC_PACKET = 8, VDEC_RESULT = 9 };
|
||||
enum venc_msg { VENC_CONFIG = 1, VENC_FRAME = 2, VENC_DONE = 3, VENC_BITRATE = 4, VENC_TOUCH = 5 };
|
||||
enum venc_touch_action { VENC_TOUCH_DOWN = 0, VENC_TOUCH_MOVE = 1, VENC_TOUCH_UP = 2 };
|
||||
enum venc_codec { VENC_H264 = 0, VENC_HEVC = 1 };
|
||||
|
||||
@@ -52,30 +52,4 @@ struct venc_touch {
|
||||
uint32_t x, y;
|
||||
};
|
||||
|
||||
struct vdec_config {
|
||||
uint32_t type;
|
||||
uint32_t codec;
|
||||
uint32_t width, height;
|
||||
uint32_t stride, rows;
|
||||
uint32_t bitstreams, bitstream_size;
|
||||
};
|
||||
|
||||
struct vdec_capture {
|
||||
uint32_t type;
|
||||
uint32_t index;
|
||||
uint32_t size;
|
||||
};
|
||||
|
||||
struct vdec_packet {
|
||||
uint32_t type;
|
||||
uint32_t input, bytes, capture;
|
||||
int64_t pts_us;
|
||||
};
|
||||
|
||||
struct vdec_result {
|
||||
uint32_t type;
|
||||
int32_t status;
|
||||
uint32_t frame;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -3,7 +3,6 @@
|
||||
#include <jni.h>
|
||||
#include <media/NdkMediaCodec.h>
|
||||
#include <media/NdkMediaFormat.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
@@ -12,7 +11,6 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
@@ -47,218 +45,6 @@ int32_t avc_profile(int32_t v4l2) {
|
||||
}
|
||||
}
|
||||
|
||||
struct DmaBufSync {
|
||||
uint64_t flags;
|
||||
};
|
||||
constexpr unsigned long kDmaBufIoctlSync = _IOW('b', 0, DmaBufSync);
|
||||
constexpr uint64_t kDmaBufSyncWrite = 2, kDmaBufSyncStart = 0, kDmaBufSyncEnd = 4;
|
||||
constexpr int32_t kColorFormatYuv420Planar = 19;
|
||||
|
||||
class Decoder {
|
||||
public:
|
||||
~Decoder() { release(); }
|
||||
|
||||
void release() {
|
||||
if (codec_) {
|
||||
AMediaCodec_stop(codec_);
|
||||
AMediaCodec_delete(codec_);
|
||||
codec_ = nullptr;
|
||||
}
|
||||
if (bitstream_) munmap((void *)bitstream_, bitstream_size_);
|
||||
bitstream_ = nullptr;
|
||||
for (auto &c : captures_) drop(c);
|
||||
}
|
||||
|
||||
bool configure(const vdec_config &c, int fd) {
|
||||
release();
|
||||
if (c.width < 16 || c.height < 16 || c.stride < c.width || c.rows < c.height || c.bitstreams == 0 ||
|
||||
c.bitstreams > VENC_MAX_BUFFERS || c.bitstream_size == 0) {
|
||||
LOG("bad decoder config: %ux%u stride %u rows %u, %u bitstreams", c.width, c.height, c.stride, c.rows,
|
||||
c.bitstreams);
|
||||
return false;
|
||||
}
|
||||
bitstream_size_ = (size_t)c.bitstreams * c.bitstream_size;
|
||||
void *p = mmap(nullptr, bitstream_size_, PROT_READ, MAP_SHARED, fd, 0);
|
||||
if (p == MAP_FAILED) {
|
||||
LOG("could not map the bitstream buffers: %s", strerror(errno));
|
||||
return false;
|
||||
}
|
||||
bitstream_ = (const uint8_t *)p;
|
||||
config_ = c;
|
||||
codec_ = create(c, true);
|
||||
if (!codec_) codec_ = create(c, false);
|
||||
if (!codec_) {
|
||||
LOG("no %s decoder for %ux%u", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height);
|
||||
release();
|
||||
return false;
|
||||
}
|
||||
src_stride_ = (int32_t)c.width;
|
||||
src_rows_ = (int32_t)c.height;
|
||||
src_width_ = (int32_t)c.width;
|
||||
src_height_ = (int32_t)c.height;
|
||||
src_planar_ = false;
|
||||
shown_ = false;
|
||||
using GetName = media_status_t (*)(AMediaCodec *, char **);
|
||||
using ReleaseName = void (*)(AMediaCodec *, char *);
|
||||
static auto get_name = (GetName)dlsym(RTLD_DEFAULT, "AMediaCodec_getName");
|
||||
static auto release_name = (ReleaseName)dlsym(RTLD_DEFAULT, "AMediaCodec_releaseName");
|
||||
char *name = nullptr;
|
||||
if (get_name && get_name(codec_, &name) != AMEDIA_OK) name = nullptr;
|
||||
LOG("decoding %s %ux%u with %s", c.codec == VENC_HEVC ? "HEVC" : "H.264", c.width, c.height,
|
||||
name ? name : "MediaCodec");
|
||||
if (name && release_name) release_name(codec_, name);
|
||||
return true;
|
||||
}
|
||||
|
||||
void capture(const vdec_capture &c, int fd) {
|
||||
if (c.index >= VENC_MAX_BUFFERS) {
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
Capture &cap = captures_[c.index];
|
||||
drop(cap);
|
||||
void *p = mmap(nullptr, c.size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
if (p == MAP_FAILED) {
|
||||
LOG("could not map capture buffer %u: %s", c.index, strerror(errno));
|
||||
close(fd);
|
||||
return;
|
||||
}
|
||||
cap = {fd, (uint8_t *)p, c.size};
|
||||
}
|
||||
|
||||
bool decode(const vdec_packet &p, bool *frame) {
|
||||
*frame = false;
|
||||
if (!codec_ || p.capture >= VENC_MAX_BUFFERS || !captures_[p.capture].data || p.input >= config_.bitstreams ||
|
||||
p.bytes == 0 || p.bytes > config_.bitstream_size)
|
||||
return false;
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
ssize_t in = AMediaCodec_dequeueInputBuffer(codec_, 20000);
|
||||
if (in < 0) return false;
|
||||
size_t capacity = 0;
|
||||
uint8_t *dst = AMediaCodec_getInputBuffer(codec_, (size_t)in, &capacity);
|
||||
if (!dst || capacity < p.bytes) {
|
||||
AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, 0, 0, 0);
|
||||
return false;
|
||||
}
|
||||
memcpy(dst, bitstream_ + (size_t)p.input * config_.bitstream_size, p.bytes);
|
||||
if (AMediaCodec_queueInputBuffer(codec_, (size_t)in, 0, p.bytes, (uint64_t)std::max<int64_t>(p.pts_us, 0), 0) !=
|
||||
AMEDIA_OK)
|
||||
return false;
|
||||
auto wait = std::chrono::milliseconds(shown_ ? 25 : 250);
|
||||
while (std::chrono::steady_clock::now() - start < wait) {
|
||||
AMediaCodecBufferInfo info;
|
||||
ssize_t o = AMediaCodec_dequeueOutputBuffer(codec_, &info, 2000);
|
||||
if (o == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
|
||||
read_format();
|
||||
continue;
|
||||
}
|
||||
if (o < 0) continue;
|
||||
size_t size = 0;
|
||||
uint8_t *data = AMediaCodec_getOutputBuffer(codec_, (size_t)o, &size);
|
||||
if (data && info.size > 0 && (size_t)info.offset + (size_t)info.size <= size)
|
||||
*frame = copy(data + info.offset, (size_t)info.size, captures_[p.capture]) || *frame;
|
||||
AMediaCodec_releaseOutputBuffer(codec_, (size_t)o, false);
|
||||
if (info.presentationTimeUs >= p.pts_us) break;
|
||||
}
|
||||
shown_ = shown_ || *frame;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Capture {
|
||||
int fd = -1;
|
||||
uint8_t *data = nullptr;
|
||||
size_t size = 0;
|
||||
};
|
||||
|
||||
static void drop(Capture &c) {
|
||||
if (c.data) munmap(c.data, c.size);
|
||||
if (c.fd >= 0) close(c.fd);
|
||||
c = Capture();
|
||||
}
|
||||
|
||||
AMediaCodec *create(const vdec_config &c, bool low_latency) {
|
||||
const char *mime = c.codec == VENC_HEVC ? "video/hevc" : "video/avc";
|
||||
AMediaCodec *codec = AMediaCodec_createDecoderByType(mime);
|
||||
if (!codec) return nullptr;
|
||||
AMediaFormat *f = AMediaFormat_new();
|
||||
AMediaFormat_setString(f, AMEDIAFORMAT_KEY_MIME, mime);
|
||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_WIDTH, (int32_t)c.width);
|
||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_HEIGHT, (int32_t)c.height);
|
||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, kColorFormatYuv420SemiPlanar);
|
||||
AMediaFormat_setInt32(f, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, (int32_t)c.bitstream_size);
|
||||
if (low_latency) {
|
||||
AMediaFormat_setInt32(f, "low-latency", 1);
|
||||
AMediaFormat_setInt32(f, "vendor.qti-ext-dec-low-latency.enable", 1);
|
||||
AMediaFormat_setInt32(f, "vendor.qti-ext-dec-picture-order.enable", 1);
|
||||
AMediaFormat_setInt32(f, "priority", 0);
|
||||
AMediaFormat_setFloat(f, "operating-rate", 120.0f);
|
||||
}
|
||||
media_status_t s = AMediaCodec_configure(codec, f, nullptr, nullptr, 0);
|
||||
AMediaFormat_delete(f);
|
||||
if (s == AMEDIA_OK) s = AMediaCodec_start(codec);
|
||||
if (s != AMEDIA_OK) {
|
||||
AMediaCodec_delete(codec);
|
||||
return nullptr;
|
||||
}
|
||||
return codec;
|
||||
}
|
||||
|
||||
void read_format() {
|
||||
AMediaFormat *f = AMediaCodec_getOutputFormat(codec_);
|
||||
if (!f) return;
|
||||
int32_t v;
|
||||
if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_WIDTH, &v) && v > 0) src_width_ = v;
|
||||
if (AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_HEIGHT, &v) && v > 0) src_height_ = v;
|
||||
src_stride_ = AMediaFormat_getInt32(f, "stride", &v) && v >= src_width_ ? v : src_width_;
|
||||
src_rows_ = AMediaFormat_getInt32(f, "slice-height", &v) && v >= src_height_ ? v : src_height_;
|
||||
src_planar_ = AMediaFormat_getInt32(f, AMEDIAFORMAT_KEY_COLOR_FORMAT, &v) && v == kColorFormatYuv420Planar;
|
||||
LOG("decoder output %dx%d stride %d rows %d %s", src_width_, src_height_, src_stride_, src_rows_,
|
||||
src_planar_ ? "planar" : "semi-planar");
|
||||
AMediaFormat_delete(f);
|
||||
}
|
||||
|
||||
bool copy(const uint8_t *src, size_t size, const Capture &cap) {
|
||||
size_t luma = (size_t)src_stride_ * src_rows_;
|
||||
size_t chroma = src_planar_ ? 2 * (size_t)(src_stride_ / 2) * (src_rows_ / 2) : (size_t)src_stride_ * (src_rows_ / 2);
|
||||
if (size < luma + chroma) return false;
|
||||
uint32_t w = std::min<uint32_t>((uint32_t)src_width_, config_.stride);
|
||||
uint32_t h = std::min<uint32_t>((uint32_t)src_height_, config_.rows);
|
||||
if ((size_t)config_.stride * config_.rows * 3 / 2 > cap.size) return false;
|
||||
DmaBufSync sync = {kDmaBufSyncStart | kDmaBufSyncWrite};
|
||||
ioctl(cap.fd, kDmaBufIoctlSync, &sync);
|
||||
uint8_t *y = cap.data, *uv = cap.data + (size_t)config_.stride * config_.rows;
|
||||
for (uint32_t row = 0; row < h; row++)
|
||||
memcpy(y + (size_t)row * config_.stride, src + (size_t)row * src_stride_, w);
|
||||
const uint8_t *su = src + luma;
|
||||
for (uint32_t row = 0; row < h / 2; row++) {
|
||||
uint8_t *d = uv + (size_t)row * config_.stride;
|
||||
if (!src_planar_) {
|
||||
memcpy(d, su + (size_t)row * src_stride_, w & ~1u);
|
||||
continue;
|
||||
}
|
||||
const uint8_t *u = su + (size_t)row * (src_stride_ / 2);
|
||||
const uint8_t *vv = su + (size_t)(src_stride_ / 2) * (src_rows_ / 2) + (size_t)row * (src_stride_ / 2);
|
||||
for (uint32_t x = 0; x < w / 2; x++) {
|
||||
d[2 * x] = u[x];
|
||||
d[2 * x + 1] = vv[x];
|
||||
}
|
||||
}
|
||||
sync.flags = kDmaBufSyncEnd | kDmaBufSyncWrite;
|
||||
ioctl(cap.fd, kDmaBufIoctlSync, &sync);
|
||||
return true;
|
||||
}
|
||||
|
||||
AMediaCodec *codec_ = nullptr;
|
||||
vdec_config config_ = {};
|
||||
const uint8_t *bitstream_ = nullptr;
|
||||
size_t bitstream_size_ = 0;
|
||||
Capture captures_[VENC_MAX_BUFFERS];
|
||||
int32_t src_width_ = 0, src_height_ = 0, src_stride_ = 0, src_rows_ = 0;
|
||||
bool src_planar_ = false;
|
||||
bool shown_ = false;
|
||||
};
|
||||
|
||||
class Session {
|
||||
public:
|
||||
explicit Session(int fd) : fd_(fd) {}
|
||||
@@ -299,24 +85,6 @@ public:
|
||||
memcpy(&b, buf, sizeof b);
|
||||
set_bitrate(b.bitrate);
|
||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
||||
} else if (type == VDEC_CONFIG && n == (ssize_t)sizeof(vdec_config)) {
|
||||
vdec_config c;
|
||||
memcpy(&c, buf, sizeof c);
|
||||
bool ok = nfds == 1 && decoder_.configure(c, fds[0]);
|
||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
||||
decoded(ok ? 0 : -1, false);
|
||||
} else if (type == VDEC_CAPTURE && n == (ssize_t)sizeof(vdec_capture)) {
|
||||
vdec_capture c;
|
||||
memcpy(&c, buf, sizeof c);
|
||||
if (nfds == 1) decoder_.capture(c, fds[0]);
|
||||
else for (int i = 0; i < nfds; i++) close(fds[i]);
|
||||
} else if (type == VDEC_PACKET && n == (ssize_t)sizeof(vdec_packet)) {
|
||||
vdec_packet p;
|
||||
memcpy(&p, buf, sizeof p);
|
||||
bool frame = false;
|
||||
bool ok = decoder_.decode(p, &frame);
|
||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
||||
decoded(ok ? 0 : -1, frame);
|
||||
} else {
|
||||
LOG("unexpected message %u of %zd bytes; closing", type, n);
|
||||
for (int i = 0; i < nfds; i++) close(fds[i]);
|
||||
@@ -349,13 +117,7 @@ private:
|
||||
send(fd_, &d, sizeof d, MSG_NOSIGNAL);
|
||||
}
|
||||
|
||||
void decoded(int32_t status, bool frame) {
|
||||
vdec_result r = {VDEC_RESULT, status, frame ? 1u : 0u};
|
||||
send(fd_, &r, sizeof r, MSG_NOSIGNAL);
|
||||
}
|
||||
|
||||
void release() {
|
||||
decoder_.release();
|
||||
if (codec_) {
|
||||
AMediaCodec_stop(codec_);
|
||||
AMediaCodec_delete(codec_);
|
||||
@@ -530,7 +292,6 @@ private:
|
||||
int32_t dst_stride_ = 0, dst_rows_ = 0;
|
||||
std::vector<Mapping> inputs_, outputs_;
|
||||
std::vector<uint8_t> header_;
|
||||
Decoder decoder_;
|
||||
};
|
||||
|
||||
std::atomic<int> g_listener{-1};
|
||||
|
||||
@@ -207,7 +207,6 @@ struct surface {
|
||||
struct wl_resource *dmabuf;
|
||||
struct dmabuf_buffer *dmabuf_buf;
|
||||
struct wl_listener dmabuf_destroy;
|
||||
const void *last_dmabuf;
|
||||
int buf_w, buf_h, has_content;
|
||||
int buf_alpha;
|
||||
int opaque[4], pending_opaque[4], pending_opaque_set;
|
||||
@@ -262,26 +261,6 @@ static struct wl_event_source *g_render_idle, *g_frame_timer;
|
||||
|
||||
|
||||
static int g_dirty;
|
||||
static int64_t g_dirty_since_ns;
|
||||
volatile int g_render_on_commit = 1;
|
||||
static int64_t g_rendered_tick_ns;
|
||||
static int g_tick_held;
|
||||
static int64_t g_hold_missed_ns;
|
||||
#define HOLD_RETRY_NS 1000000000LL
|
||||
#define PACE_BUFFERS 32
|
||||
static struct {
|
||||
unsigned ticks, ticks_late_2ms, renders, commit_renders, null_attaches, reattaches, presented, replaced, undrawn, distinct;
|
||||
int64_t tick_late_ns, tick_late_max_ns, wait_ns, wait_max_ns;
|
||||
const void *buffers[PACE_BUFFERS];
|
||||
uint64_t game_frames_seen;
|
||||
} g_pace;
|
||||
|
||||
static void pace_note_buffer(const void *buffer) {
|
||||
for (unsigned i = 0; i < g_pace.distinct && i < PACE_BUFFERS; i++)
|
||||
if (g_pace.buffers[i] == buffer) return;
|
||||
if (g_pace.distinct < PACE_BUFFERS) g_pace.buffers[g_pace.distinct] = buffer;
|
||||
g_pace.distinct++;
|
||||
}
|
||||
static int64_t g_last_vsync_ns;
|
||||
static int64_t g_tick_vsync_ns;
|
||||
static int64_t g_refresh_ns = 16666667;
|
||||
@@ -289,7 +268,7 @@ static struct wl_event_source *g_fallback_timer;
|
||||
static int g_fallback_armed;
|
||||
|
||||
volatile int g_fps_limit;
|
||||
/* fps limit -1 (phone output, not mirrored): replaced buffers go back to the client at once instead of once per refresh. */
|
||||
/* fps limit -1 (Performance mode without a limit): replaced buffers go back to the client at once instead of once per refresh. */
|
||||
volatile int g_release_unpaced;
|
||||
|
||||
volatile int g_hide_shell;
|
||||
@@ -332,7 +311,6 @@ static struct {
|
||||
} g_perf;
|
||||
|
||||
static void schedule_render(void);
|
||||
static void on_commit_idle(void *data);
|
||||
|
||||
static int64_t now_ns(void) {
|
||||
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
@@ -780,9 +758,6 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
|
||||
static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) {
|
||||
const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b;
|
||||
if (!repeat) {
|
||||
if (!s->dmabuf && s->last_dmabuf == buffer) g_pace.reattaches++;
|
||||
s->last_dmabuf = buffer;
|
||||
pace_note_buffer(buffer);
|
||||
drop_dmabuf(s, 1);
|
||||
s->dmabuf = buffer;
|
||||
s->dmabuf_buf = b;
|
||||
@@ -944,15 +919,12 @@ static void feedback_resource_destroy(struct wl_resource *r) {
|
||||
wl_list_remove(wl_resource_get_link(r));
|
||||
}
|
||||
|
||||
static unsigned feedback_discard_all(struct wl_list *list) {
|
||||
static void feedback_discard_all(struct wl_list *list) {
|
||||
struct wl_resource *fb, *tmp;
|
||||
unsigned n = 0;
|
||||
wl_resource_for_each_safe(fb, tmp, list) {
|
||||
wp_presentation_feedback_send_discarded(fb);
|
||||
wl_resource_destroy(fb);
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static uint32_t nominal_refresh_ns(void) {
|
||||
@@ -981,7 +953,6 @@ static void feedback_present_all(struct wl_list *list, int64_t t) {
|
||||
nominal_refresh_ns(), 0, 0,
|
||||
WP_PRESENTATION_FEEDBACK_KIND_VSYNC);
|
||||
wl_resource_destroy(fb);
|
||||
g_pace.presented++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1148,9 +1119,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
struct wl_shm_buffer *shm = buffer && !db ? wl_shm_buffer_get(buffer) : NULL;
|
||||
uint8_t pixel[4];
|
||||
|
||||
g_pace.replaced += feedback_discard_all(&s->feedback);
|
||||
if (!buffer) g_pace.null_attaches++;
|
||||
else if (!db) s->last_dmabuf = NULL;
|
||||
feedback_discard_all(&s->feedback);
|
||||
|
||||
if (buffer) {
|
||||
wl_list_remove(&s->pending_buffer_destroy.link);
|
||||
@@ -2123,23 +2092,14 @@ void droiddeck_stream_frame(AHardwareBuffer *ahb) {
|
||||
unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); }
|
||||
|
||||
static void render_scene(void) {
|
||||
if (atomic_load(&g_stream_on)) { g_dirty_since_ns = 0; render_stream(); return; }
|
||||
if (atomic_load(&g_stream_on)) { render_stream(); return; }
|
||||
struct draw_list dl = {0};
|
||||
struct surface *s;
|
||||
int w, h;
|
||||
const int64_t t_scene = now_ns();
|
||||
int copy = 0;
|
||||
|
||||
if (g_dirty_since_ns) {
|
||||
const int64_t wait = t_scene - g_dirty_since_ns;
|
||||
g_pace.wait_ns += wait;
|
||||
if (wait > g_pace.wait_max_ns) g_pace.wait_max_ns = wait;
|
||||
g_pace.renders++;
|
||||
g_dirty_since_ns = 0;
|
||||
}
|
||||
g_dirty = 0;
|
||||
g_rendered_tick_ns = g_tick_vsync_ns;
|
||||
g_tick_held = 0;
|
||||
g_hud_fresh = 0;
|
||||
g_hdr_unimported = NULL;
|
||||
wl_list_for_each(s, &g_surfaces, link) s->drawn = 0;
|
||||
@@ -2279,7 +2239,7 @@ static void render_scene(void) {
|
||||
}
|
||||
wl_list_for_each(s, &g_surfaces, link) {
|
||||
if (s->drawn) feedback_present_all(&s->feedback, t);
|
||||
else g_pace.undrawn += feedback_discard_all(&s->feedback);
|
||||
else feedback_discard_all(&s->feedback);
|
||||
}
|
||||
fire_all_frames();
|
||||
} else {
|
||||
@@ -2304,25 +2264,10 @@ static int on_fallback_timer(void *data) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* A new frame is drawn when it arrives instead of at the next screen tick, at most once per refresh,
|
||||
while frames go straight back to the game (no compositor limit), without streaming or frame generation. */
|
||||
static int commit_renders_on(void) {
|
||||
return g_render_on_commit && g_release_unpaced && !atomic_load(&g_stream_on) && !vkp_framegen_active();
|
||||
}
|
||||
|
||||
static int render_on_commit(void) {
|
||||
return commit_renders_on() && !g_render_idle && g_rendered_tick_ns != g_tick_vsync_ns;
|
||||
}
|
||||
|
||||
static void schedule_render(void) {
|
||||
if (!g_dirty && !g_dirty_since_ns) g_dirty_since_ns = now_ns();
|
||||
g_dirty = 1;
|
||||
if (!g_display) return;
|
||||
if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) {
|
||||
if (render_on_commit())
|
||||
g_render_idle = wl_event_loop_add_idle(wl_display_get_event_loop(g_display), on_commit_idle, NULL);
|
||||
return;
|
||||
}
|
||||
if (g_last_vsync_ns && now_ns() - g_last_vsync_ns < 100000000LL) return;
|
||||
if (g_fallback_armed) return;
|
||||
if (!g_fallback_timer)
|
||||
g_fallback_timer = wl_event_loop_add_timer(wl_display_get_event_loop(g_display),
|
||||
@@ -2336,45 +2281,18 @@ static int scene_waits_for_game(int64_t now) {
|
||||
return g_hud_surface && !g_hud_fresh && now - g_hud_last_ns < 100000000LL && vkp_framegen_active();
|
||||
}
|
||||
|
||||
static void on_commit_idle(void *data) {
|
||||
g_render_idle = NULL;
|
||||
if (!g_dirty || !commit_renders_on() || g_rendered_tick_ns == g_tick_vsync_ns || scene_waits_for_game(now_ns())) return;
|
||||
g_pace.commit_renders++;
|
||||
render_scene();
|
||||
}
|
||||
|
||||
static void on_vsync(int64_t frame_time_ns) {
|
||||
int64_t now = now_ns();
|
||||
g_perf.ticks++;
|
||||
if (frame_time_ns > 0 && now >= frame_time_ns) {
|
||||
const int64_t late = now - frame_time_ns;
|
||||
g_pace.ticks++;
|
||||
g_pace.tick_late_ns += late;
|
||||
if (late > g_pace.tick_late_max_ns) g_pace.tick_late_max_ns = late;
|
||||
if (late > 2000000LL) g_pace.ticks_late_2ms++;
|
||||
}
|
||||
if (g_last_vsync_ns) {
|
||||
int64_t d = now - g_last_vsync_ns;
|
||||
if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8;
|
||||
}
|
||||
g_last_vsync_ns = now;
|
||||
g_tick_vsync_ns = frame_time_ns;
|
||||
int tick_change = 0;
|
||||
if (vkp_apply_window_request()) tick_change = 1;
|
||||
if (vkp_effects_sync()) tick_change = 1;
|
||||
if (vkp_cardboard_pose_changed()) tick_change = 1;
|
||||
if (tick_change) g_dirty = 1;
|
||||
/* A frame that arrived after this refresh was already drawn is left for the next arrival to draw;
|
||||
drawing it here would block that arrival too and keep every frame waiting for the tick. A client
|
||||
that draws again only after its frame callback sends no such arrival: once a held frame is still
|
||||
waiting at the next tick, the tick draws every frame for a second before holding one again. */
|
||||
if (g_tick_held && g_dirty) g_hold_missed_ns = now;
|
||||
g_tick_held = 0;
|
||||
if (!tick_change && commit_renders_on() && g_dirty_since_ns && now - g_dirty_since_ns < g_refresh_ns &&
|
||||
now - g_hold_missed_ns >= HOLD_RETRY_NS) {
|
||||
g_tick_held = 1;
|
||||
return;
|
||||
}
|
||||
if (vkp_apply_window_request()) g_dirty = 1;
|
||||
if (vkp_effects_sync()) g_dirty = 1;
|
||||
if (vkp_cardboard_pose_changed()) g_dirty = 1;
|
||||
if (g_dirty && !scene_waits_for_game(now)) render_scene();
|
||||
}
|
||||
|
||||
@@ -3478,24 +3396,6 @@ static int on_stats_timer(void *data) {
|
||||
#undef PERF_MS
|
||||
memset(&g_perf, 0, sizeof(g_perf));
|
||||
}
|
||||
const uint64_t game = g_game_frames - g_pace.game_frames_seen;
|
||||
if (g_pace.ticks || g_pace.renders || game || g_pace.reattaches || g_pace.null_attaches || g_pace.distinct ||
|
||||
g_pace.presented || g_pace.replaced || g_pace.undrawn) {
|
||||
droiddeck_log("pacing", "last 10 s: tick reaches compositor %.2f/%.2f ms late (%u ticks, %u over 2 ms) | "
|
||||
"new frame waits %.2f/%.2f ms to be drawn (%u scenes, %u on arrival) | %llu game frames, %u re-attached after an "
|
||||
"empty attach, %u empty attaches, %u distinct buffers | feedback %u shown, %u replaced before drawing, "
|
||||
"%u not drawn",
|
||||
g_pace.ticks ? (double)g_pace.tick_late_ns / 1e6 / g_pace.ticks : 0.0, (double)g_pace.tick_late_max_ns / 1e6,
|
||||
g_pace.ticks, g_pace.ticks_late_2ms,
|
||||
g_pace.renders ? (double)g_pace.wait_ns / 1e6 / g_pace.renders : 0.0, (double)g_pace.wait_max_ns / 1e6,
|
||||
g_pace.renders, g_pace.commit_renders, (unsigned long long)game, g_pace.reattaches, g_pace.null_attaches, g_pace.distinct,
|
||||
g_pace.presented, g_pace.replaced, g_pace.undrawn);
|
||||
}
|
||||
{
|
||||
const uint64_t seen = g_game_frames;
|
||||
memset(&g_pace, 0, sizeof(g_pace));
|
||||
g_pace.game_frames_seen = seen;
|
||||
}
|
||||
g_stat_frames = g_stat_dmabuf = g_stat_shm = 0;
|
||||
droiddeck_color_stats_tick();
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@ extern void droiddeck_wayland_output_resized(void);
|
||||
extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
|
||||
extern volatile int g_fps_limit;
|
||||
extern volatile int g_release_unpaced;
|
||||
extern volatile int g_render_on_commit;
|
||||
extern volatile int g_hide_shell;
|
||||
extern volatile int g_zero_copy;
|
||||
extern volatile unsigned g_zero_copy_last;
|
||||
@@ -588,12 +587,6 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv *
|
||||
free(s);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetRenderOnCommit(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
g_render_on_commit = on ? 1 : 0;
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "render on commit %s", on ? "on" : "off");
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) {
|
||||
g_fps_limit = fps > 0 ? fps : 0;
|
||||
|
||||
@@ -44,7 +44,6 @@ import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.ui.ComponentsPage
|
||||
import com.droiddeck.launcher.session.GameSaves
|
||||
import com.droiddeck.launcher.session.SessionLogShare
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SteamRepair
|
||||
import com.droiddeck.launcher.core.CpuCores
|
||||
@@ -53,7 +52,6 @@ import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import com.droiddeck.launcher.core.WifiDiscovery
|
||||
import com.droiddeck.launcher.core.SteamIntegration
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
||||
import com.droiddeck.launcher.ui.CoreRow
|
||||
import com.droiddeck.launcher.ui.PerformancePage
|
||||
@@ -93,17 +91,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private val components = ComponentsMenu(this, ui)
|
||||
private val decky = DeckyMenu(this, ui)
|
||||
private val updates = UpdatesMenu(this, ui)
|
||||
private val protons = ProtonMenu(this, ui) { !busy && flood == null && compatLaunch == null && pkgStage == null && components.compBusy == null }
|
||||
private val protons = ProtonMenu(this, ui) { !busy && flood == null && pkgStage == null && components.compBusy == null }
|
||||
|
||||
private var installed by mutableStateOf<String?>(null)
|
||||
private var flood by mutableStateOf<PendingFlood?>(null)
|
||||
private var floodProgress by androidx.compose.runtime.mutableFloatStateOf(0f)
|
||||
private class PendingFlood(val from: androidx.compose.ui.geometry.Rect, val intent: Intent)
|
||||
private class CompatLaunch(val intent: Intent, val loading: com.droiddeck.launcher.session.LoadingState, var menuInstall: Boolean)
|
||||
private var compatLaunch by mutableStateOf<CompatLaunch?>(null)
|
||||
private var compatFlood by mutableStateOf<androidx.compose.ui.graphics.Color?>(null)
|
||||
private var compatLaunchPoll: Runnable? = null
|
||||
private var compatLaunchVisible = false
|
||||
private var returning by mutableStateOf<ReturningFlood?>(null)
|
||||
private class ReturningFlood(val color: Int, val to: androidx.compose.ui.geometry.Rect?)
|
||||
private var ready by mutableStateOf(false)
|
||||
@@ -141,14 +134,9 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
|
||||
private var catalogLoading by mutableStateOf(false)
|
||||
private var packageRows by mutableStateOf<List<PackageRow>?>(null)
|
||||
private object PackageOperation {
|
||||
val id = mutableStateOf<String?>(null)
|
||||
val stage = mutableStateOf<String?>(null)
|
||||
val percent = mutableIntStateOf(-1)
|
||||
}
|
||||
private var pkgId by PackageOperation.id
|
||||
private var pkgStage by PackageOperation.stage
|
||||
private var pkgPercent by PackageOperation.percent
|
||||
private var pkgId by mutableStateOf<String?>(null)
|
||||
private var pkgStage by mutableStateOf<String?>(null)
|
||||
private var pkgPercent by mutableIntStateOf(-1)
|
||||
private var desktopInstalled by mutableStateOf(false)
|
||||
private var desktopPresent by mutableStateOf(false)
|
||||
private var battleNetInstalled by mutableStateOf(false)
|
||||
@@ -200,8 +188,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var wifiDiscoveryLocation by mutableStateOf(false)
|
||||
private var wifiDiscoveryAsked by mutableStateOf(false)
|
||||
private var wifiDiscoveryBlocked by mutableStateOf(false)
|
||||
private var integrationState by mutableStateOf(SteamIntegration.State())
|
||||
private var integrationFocus by mutableStateOf<SteamIntegration.Feature?>(null)
|
||||
private val wifiLocationReceiver = object : android.content.BroadcastReceiver() {
|
||||
override fun onReceive(context: android.content.Context?, intent: Intent?) {
|
||||
refreshWifiDiscovery()
|
||||
@@ -270,65 +256,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
}
|
||||
wifiDiscovery = SessionPrefs.wifiDiscoveryEnabled(this)
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
|
||||
private var shortcutsTried = false
|
||||
|
||||
private fun readIntegration() = SteamIntegration.read(this)
|
||||
.copy(locationBlocked = wifiDiscoveryBlocked, shortcutsTried = shortcutsTried)
|
||||
|
||||
private fun openIntegration(feature: SteamIntegration.Feature? = null) {
|
||||
SteamIntegration.dismissSuggestion(this)
|
||||
refreshWifiDiscovery()
|
||||
integrationState = readIntegration()
|
||||
integrationFocus = feature
|
||||
navRequest = "setup:integration"
|
||||
}
|
||||
|
||||
private fun readIntegrationIntent(incoming: Intent) {
|
||||
if (incoming.action != SteamIntegration.ACTION_SETUP) return
|
||||
openIntegration(incoming.getStringExtra(SteamIntegration.EXTRA_FEATURE)?.let {
|
||||
runCatching { SteamIntegration.Feature.valueOf(it) }.getOrNull()
|
||||
})
|
||||
}
|
||||
|
||||
private fun integrationSettings(intent: Intent, fallback: String = android.provider.Settings.ACTION_SETTINGS) {
|
||||
try { startActivity(intent) }
|
||||
catch (_: android.content.ActivityNotFoundException) { startActivity(Intent(fallback)) }
|
||||
catch (_: SecurityException) { startActivity(Intent(fallback)) }
|
||||
}
|
||||
|
||||
private fun configureIntegration(feature: SteamIntegration.Feature) {
|
||||
when (feature) {
|
||||
SteamIntegration.Feature.WIFI -> {
|
||||
if (wifiDiscovery && wifiDiscoveryPermission) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
} else if (wifiDiscoveryPermission) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, true)
|
||||
} else {
|
||||
SessionPrefs.setWifiDiscoveryAsked(this)
|
||||
wifiLocationPermission.launch(WifiDiscovery.permissions)
|
||||
}
|
||||
refreshWifiDiscovery()
|
||||
}
|
||||
SteamIntegration.Feature.BRIGHTNESS -> integrationSettings(SteamIntegration.brightnessSettings(this))
|
||||
SteamIntegration.Feature.HOME -> if (HomeApp.isDefault(this)) HomeApp.openSystemHomeSettings(this) else {
|
||||
HomeApp.setHomeScreenEnabled(this, true)
|
||||
refreshHomeAppState()
|
||||
manageHomeApp()
|
||||
}
|
||||
SteamIntegration.Feature.SHORTCUTS -> {
|
||||
if (!integrationState.shortcuts) shortcutsTried = true
|
||||
if (!HomeApp.isDefault(this)) configureIntegration(SteamIntegration.Feature.HOME)
|
||||
else integrationSettings(SteamIntegration.shortcutSettings(this), android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun openAppInfo() =
|
||||
integrationSettings(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")))
|
||||
|
||||
private fun openWifiDiscoverySettings() {
|
||||
if (!WifiDiscovery.permissionGranted(this)) {
|
||||
wifiPermissionSettings.launch(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
@@ -463,6 +392,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var theme by mutableStateOf("graphite")
|
||||
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
|
||||
private var hdrOn by mutableStateOf(false)
|
||||
private var performanceMode by mutableStateOf(false)
|
||||
private var upscaler by mutableStateOf(0)
|
||||
private var upscaleSharpness by mutableStateOf(75)
|
||||
private var hdrReason by mutableStateOf<String?>(null)
|
||||
@@ -485,8 +415,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
|
||||
private var runningLabel by mutableStateOf<String?>(null)
|
||||
private var logsEnabled by mutableStateOf(true)
|
||||
private var gameDebugLogsEnabled by mutableStateOf(false)
|
||||
private var gameDebugLogsNeedsRestart by mutableStateOf(false)
|
||||
private var vacDiagnostics by mutableStateOf(false)
|
||||
private var agentCommands by mutableStateOf(false)
|
||||
private var clearCachedApps by mutableStateOf(false)
|
||||
@@ -498,21 +426,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var homeScreenEnabled by mutableStateOf(false)
|
||||
private var defaultHomeLabel by mutableStateOf<String?>(null)
|
||||
private var androidApps by mutableStateOf<List<HomeApp.LaunchableApp>>(emptyList())
|
||||
private var androidAppsListing = 0
|
||||
private val packageCallback = object : android.content.pm.LauncherApps.Callback() {
|
||||
private fun changed() {
|
||||
refreshAndroidApps()
|
||||
if (HomeWidgets.providers != null) HomeWidgets.refreshProviders(this@FrontEndActivity)
|
||||
}
|
||||
override fun onPackageRemoved(packageName: String, user: android.os.UserHandle) = changed()
|
||||
override fun onPackageAdded(packageName: String, user: android.os.UserHandle) = changed()
|
||||
override fun onPackageChanged(packageName: String, user: android.os.UserHandle) = changed()
|
||||
override fun onPackagesAvailable(packageNames: Array<out String>, user: android.os.UserHandle, replacing: Boolean) = changed()
|
||||
override fun onPackagesUnavailable(packageNames: Array<out String>, user: android.os.UserHandle, replacing: Boolean) = changed()
|
||||
override fun onShortcutsChanged(packageName: String, shortcuts: MutableList<android.content.pm.ShortcutInfo>, user: android.os.UserHandle) {
|
||||
if (homeAppSelected) HomePins.refresh(this@FrontEndActivity)
|
||||
}
|
||||
}
|
||||
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
|
||||
private lateinit var displayManager: DisplayManager
|
||||
private val secondScreenDisplayListener = object : DisplayManager.DisplayListener {
|
||||
@@ -526,19 +439,16 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun startActivity(intent: Intent?) {
|
||||
val compat = protons.protonBusyId != null || ProtonExtras.installInProgress
|
||||
if (intent?.component?.className == SessionActivity::class.java.name) {
|
||||
if (compatLaunch != null) return
|
||||
when {
|
||||
busy || LinuxRuntimeInstaller.isBusy() -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
SessionState.installing != null && !SessionState.running -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
protons.protonBusyId != null || ProtonExtras.installInProgress -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_proton_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
compat -> Unit
|
||||
pkgStage != null -> {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
@@ -553,26 +463,17 @@ class FrontEndActivity : ComponentActivity() {
|
||||
return
|
||||
}
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
if (compat) {
|
||||
waitForCompat(intent)
|
||||
return
|
||||
}
|
||||
}
|
||||
super.startActivity(intent)
|
||||
if (intent?.component?.className == SessionActivity::class.java.name) overridePendingTransition(R.anim.session_rise, R.anim.session_hold)
|
||||
}
|
||||
|
||||
private fun launchFlooded(f: PendingFlood) {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) ||
|
||||
protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy() || protons.protonBusyId != null ||
|
||||
ProtonExtras.installInProgress || pkgStage != null) {
|
||||
flood = null
|
||||
floodProgress = 0f
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
if (!busy && !LinuxRuntimeInstaller.isBusy() && !(SessionState.installing != null && !SessionState.running) &&
|
||||
(protons.protonBusyId != null || ProtonExtras.installInProgress)) {
|
||||
compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal
|
||||
waitForCompat(f.intent)
|
||||
}
|
||||
return
|
||||
}
|
||||
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
|
||||
@@ -580,72 +481,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
overridePendingTransition(0, 0)
|
||||
}
|
||||
|
||||
private fun waitForCompat(next: Intent, menuInstall: Boolean = protons.protonBusyId != null) {
|
||||
if (compatLaunch != null) return
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.take()
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
val waiting = CompatLaunch(Intent(next), com.droiddeck.launcher.session.LoadingState(this), menuInstall)
|
||||
compatLaunch = waiting
|
||||
val poll = object : Runnable {
|
||||
override fun run() {
|
||||
if (isDestroyed || isFinishing || compatLaunch !== waiting) return
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress) {
|
||||
waiting.menuInstall = waiting.menuInstall || protons.protonBusyId != null
|
||||
val percent = if (protons.protonBusyId != null) protons.protonPercent else -1
|
||||
val stage = protons.protonStage ?: getString(R.string.load_compat_wait)
|
||||
waiting.loading.say(if (percent >= 0) getString(R.string.load_compat_progress, stage, percent) else stage,
|
||||
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
|
||||
waiting.loading.percent = percent
|
||||
waiting.loading.tick()
|
||||
ui.postDelayed(this, 250)
|
||||
return
|
||||
}
|
||||
if (!compatLaunchVisible) { ui.postDelayed(this, 250); return }
|
||||
val problem = protons.protonProblem.takeIf { waiting.menuInstall }
|
||||
if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) || pkgStage != null)) {
|
||||
waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime),
|
||||
com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true)
|
||||
waiting.loading.percent = if (pkgStage != null) pkgPercent else percent
|
||||
waiting.loading.tick()
|
||||
ui.postDelayed(this, 250)
|
||||
return
|
||||
}
|
||||
compatLaunchPoll = null
|
||||
if (problem != null) waiting.loading.showEnded(problem)
|
||||
else {
|
||||
compatLaunch = null
|
||||
startActivity(waiting.intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
compatLaunchPoll = poll
|
||||
poll.run()
|
||||
}
|
||||
|
||||
private fun cancelCompatLaunch() {
|
||||
compatLaunchPoll?.let(ui::removeCallbacks)
|
||||
compatLaunchPoll = null
|
||||
compatLaunch = null
|
||||
compatFlood = null
|
||||
}
|
||||
|
||||
private fun restoreCompatLaunch(state: Bundle) {
|
||||
savedIntent(state, KEY_COMPAT_LAUNCH)?.let { next ->
|
||||
val problem = state.getString(KEY_COMPAT_PROBLEM)
|
||||
if (problem == null) waitForCompat(next, state.getBoolean(KEY_COMPAT_MENU_INSTALL))
|
||||
else compatLaunch = CompatLaunch(next,
|
||||
com.droiddeck.launcher.session.LoadingState(this).apply { showEnded(problem) }, false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveCompatLaunch(state: Bundle) {
|
||||
compatLaunch?.let {
|
||||
state.putParcelable(KEY_COMPAT_LAUNCH, it.intent)
|
||||
state.putBoolean(KEY_COMPAT_MENU_INSTALL, it.menuInstall)
|
||||
if (it.loading.ended) state.putString(KEY_COMPAT_PROBLEM, it.loading.step)
|
||||
}
|
||||
}
|
||||
|
||||
private var shortcutPicker by mutableStateOf(false)
|
||||
private var shortcutLibraryScanning by mutableStateOf(false)
|
||||
@Volatile private var libraryScanGeneration = 0
|
||||
@@ -707,7 +542,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false): Boolean {
|
||||
if (pkgStage != null) {
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
@@ -819,7 +654,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
android.widget.Toast.makeText(this, R.string.epic_client_uninstalling, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
if (pkgStage != null) {
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
@@ -927,7 +762,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
if (savedInstanceState == null) readIntegrationIntent(intent)
|
||||
readGameIntent(intent)
|
||||
gameSyncFolder = GameFileSync.folder(this)
|
||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||
@@ -982,7 +816,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
|
||||
offlineAccount = offlineAccount, offline = offline,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
||||
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
|
||||
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
|
||||
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
|
||||
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
|
||||
@@ -995,8 +828,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
isHomeApp = homeAppSelected,
|
||||
homeScreenEnabled = homeScreenEnabled,
|
||||
defaultHomeLabel = defaultHomeLabel,
|
||||
integration = integrationState,
|
||||
integrationFocus = integrationFocus,
|
||||
androidApps = androidApps,
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
packages = packageRows,
|
||||
@@ -1139,21 +970,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
.putExtra(com.droiddeck.launcher.files.FileManagerActivity.EXTRA_START_DIR, dir.absolutePath))
|
||||
},
|
||||
onLogs = {
|
||||
val changed = SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
|
||||
if (!changed) android.widget.Toast.makeText(
|
||||
this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
|
||||
).show()
|
||||
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
|
||||
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
|
||||
},
|
||||
onGameDebugLogs = {
|
||||
val changed = SessionPrefs.setGameDebugLogsEnabled(this, !SessionPrefs.gameDebugLogsEnabled(this))
|
||||
if (!changed) android.widget.Toast.makeText(
|
||||
this, R.string.setup_logging_update_failed, android.widget.Toast.LENGTH_LONG,
|
||||
).show()
|
||||
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
|
||||
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
|
||||
},
|
||||
onVacDiagnostics = {
|
||||
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
|
||||
@@ -1249,14 +1067,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
downloadProxy = DownloadSource.proxyHostPort(this)
|
||||
},
|
||||
onHomeApp = { manageHomeApp() },
|
||||
onSteamIntegration = ::openIntegration,
|
||||
onIntegration = { integrationFocus = null; configureIntegration(it) },
|
||||
onIntegrationAppInfo = ::openAppInfo,
|
||||
onIntegrationLocation = ::openWifiDiscoverySettings,
|
||||
onDismissIntegration = {
|
||||
SteamIntegration.dismissSuggestion(this)
|
||||
integrationState = readIntegration()
|
||||
},
|
||||
onHomeScreen = { on ->
|
||||
HomeApp.setHomeScreenEnabled(this, on)
|
||||
refreshHomeAppState()
|
||||
@@ -1310,12 +1120,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
onDismissPhantomGate = { showPhantomGate = false },
|
||||
onShowPhantomGate = {
|
||||
refreshPhantomStatus()
|
||||
showPhantomGate = true
|
||||
},
|
||||
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
|
||||
onStartPairingGuide = { displayId -> PairingGuideActivity.start(this, displayId) },
|
||||
onOpenNotificationSettings = {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
|
||||
@@ -1411,23 +1216,12 @@ class FrontEndActivity : ComponentActivity() {
|
||||
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
|
||||
}
|
||||
}
|
||||
androidx.activity.compose.BackHandler(compatLaunch != null) { cancelCompatLaunch() }
|
||||
compatLaunch?.loading?.let { loading ->
|
||||
if (!loading.ended) com.droiddeck.launcher.ui.VeilRing()
|
||||
com.droiddeck.launcher.ui.LoadingOverlay(
|
||||
loading.step, loading.percent, loading.elapsed, getString(R.string.load_compat_hint), loading.ended,
|
||||
loading.topic, loading.readable, title = getString(R.string.load_compat_title),
|
||||
onCancel = ::cancelCompatLaunch, onClose = ::cancelCompatLaunch,
|
||||
flood = compatFlood, onFlooded = { compatFlood = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
|
||||
else {
|
||||
restoreCompatLaunch(savedInstanceState)
|
||||
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
|
||||
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
|
||||
}
|
||||
@@ -1456,10 +1250,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
if (intent.action == SteamIntegration.ACTION_SETUP) {
|
||||
readIntegrationIntent(intent)
|
||||
return
|
||||
}
|
||||
readGameIntent(intent)
|
||||
refresh()
|
||||
startSteamAtStartupIfEnabled()
|
||||
@@ -1518,14 +1308,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (compatLaunch != null) {
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
|
||||
if (event.action == KeyEvent.ACTION_UP) cancelCompatLaunch()
|
||||
return true
|
||||
}
|
||||
if (!compatLaunch!!.loading.ended && event.keyCode !in listOf(
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) return true
|
||||
}
|
||||
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
|
||||
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
@@ -1542,20 +1324,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
|
||||
if (compatLaunch != null && !compatLaunch!!.loading.ended &&
|
||||
com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return true
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
compatLaunchVisible = false
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
compatLaunchVisible = true
|
||||
orientation = SessionPrefs.orientation(this)
|
||||
launcherOrientation = com.droiddeck.launcher.core.AppUiPrefs.orientation(this)
|
||||
requestedOrientation = launcherOrientation
|
||||
@@ -1604,20 +1374,10 @@ class FrontEndActivity : ComponentActivity() {
|
||||
})
|
||||
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
|
||||
refreshSecondScreenDisplays()
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).registerCallback(packageCallback, ui)
|
||||
HomeWidgets.startListening(this)
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) return
|
||||
@Suppress("DEPRECATION")
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
saveCompatLaunch(outState)
|
||||
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
|
||||
switchingTo?.let {
|
||||
outState.putParcelable(KEY_SWITCHING_TO, it)
|
||||
@@ -1630,7 +1390,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
else @Suppress("DEPRECATION") state.getParcelable(key)
|
||||
|
||||
override fun onDestroy() {
|
||||
cancelCompatLaunch()
|
||||
updates.unregister()
|
||||
super.onDestroy()
|
||||
}
|
||||
@@ -1638,8 +1397,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
override fun onStop() {
|
||||
unregisterReceiver(wifiLocationReceiver)
|
||||
unregisterReceiver(mediaReceiver)
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
|
||||
HomeWidgets.stopListening(this)
|
||||
ui.removeCallbacks(mediaRefresh)
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = null
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
|
||||
@@ -1655,22 +1412,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
|
||||
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
|
||||
defaultHomeLabel = HomeApp.defaultLabel(this)
|
||||
refreshAndroidApps()
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
|
||||
private fun refreshAndroidApps() {
|
||||
if (!homeAppSelected) {
|
||||
++androidAppsListing
|
||||
androidApps = emptyList()
|
||||
return
|
||||
}
|
||||
val seq = ++androidAppsListing
|
||||
HomePins.refresh(this)
|
||||
Thread({
|
||||
val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList())
|
||||
ui.post { if (seq == androidAppsListing) androidApps = apps }
|
||||
}, "home-apps").start()
|
||||
androidApps = if (homeAppSelected) HomeApp.launchableApps(this) else emptyList()
|
||||
}
|
||||
|
||||
private fun refreshSecondScreenDisplays() {
|
||||
@@ -1852,7 +1594,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
private fun openBattleNet(args: List<String> = emptyList()) {
|
||||
if (pkgStage != null) {
|
||||
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
@@ -1960,7 +1702,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
ModeSettings(
|
||||
mode = mode, resolution = resolution,
|
||||
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
|
||||
hdr = hdrOn, hdrReason = hdrReason,
|
||||
hdr = hdrOn, hdrReason = hdrReason, performanceMode = performanceMode,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
gpuDrivers = drivers.summary(),
|
||||
touchMode = touchMode,
|
||||
@@ -1994,7 +1736,11 @@ class FrontEndActivity : ComponentActivity() {
|
||||
bootMovieCustomName = bootMovieCustomName,
|
||||
bootMovieImporting = bootMovieImporting,
|
||||
bootMovieProgress = bootMovieProgress,
|
||||
integration = if (mode == SessionService.MODE_STEAM) integrationState else null,
|
||||
wifiDiscovery = if (mode == SessionService.MODE_STEAM) wifiDiscovery else null,
|
||||
wifiDiscoveryPermission = wifiDiscoveryPermission,
|
||||
wifiDiscoveryLocation = wifiDiscoveryLocation,
|
||||
wifiDiscoveryAsked = wifiDiscoveryAsked,
|
||||
wifiDiscoveryBlocked = wifiDiscoveryBlocked,
|
||||
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
|
||||
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyLatest else null,
|
||||
deckyBranch = decky.deckyBranch,
|
||||
@@ -2003,12 +1749,25 @@ class FrontEndActivity : ComponentActivity() {
|
||||
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
|
||||
),
|
||||
ModeSettingsActions(
|
||||
onIntegration = ::configureIntegration,
|
||||
onIntegrationAppInfo = ::openAppInfo,
|
||||
onIntegrationLocation = ::openWifiDiscoverySettings,
|
||||
onWifiDiscovery = { on ->
|
||||
if (!on) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, false)
|
||||
refreshWifiDiscovery()
|
||||
} else if (WifiDiscovery.permissionGranted(this)) {
|
||||
SessionPrefs.setWifiDiscoveryEnabled(this, true)
|
||||
refreshWifiDiscovery()
|
||||
} else if (wifiDiscoveryBlocked) {
|
||||
openWifiDiscoverySettings()
|
||||
} else {
|
||||
SessionPrefs.setWifiDiscoveryAsked(this)
|
||||
wifiLocationPermission.launch(WifiDiscovery.permissions)
|
||||
}
|
||||
},
|
||||
onWifiDiscoverySettings = { openWifiDiscoverySettings() },
|
||||
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value },
|
||||
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
|
||||
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
|
||||
onPerformanceMode = { on -> SessionPrefs.setPerformanceMode(this, mode, on); performanceMode = on },
|
||||
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
|
||||
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
|
||||
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
|
||||
@@ -2259,6 +2018,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
|
||||
loadBootMovie()
|
||||
hdrOn = SessionPrefs.hdr(this, mode)
|
||||
performanceMode = SessionPrefs.performanceMode(this, mode)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
|
||||
@@ -2328,10 +2088,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
refreshPhantomStatus()
|
||||
}
|
||||
|
||||
private fun gameDebugLogsNeedsRestart(): Boolean =
|
||||
SessionPrefs.logsEnabled(this) && SessionPrefs.gameDebugLogsEnabled(this) &&
|
||||
!SessionPaths.currentSessionLogsRetained(this)
|
||||
|
||||
private fun refresh() {
|
||||
// Until the scan finishes, the other client's games would launch in this one.
|
||||
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
|
||||
@@ -2353,8 +2109,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
frameGenLabel = FrameGen.label(this)
|
||||
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
|
||||
logsEnabled = SessionPrefs.logsEnabled(this)
|
||||
gameDebugLogsEnabled = SessionPrefs.gameDebugLogsEnabled(this)
|
||||
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
|
||||
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
|
||||
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
|
||||
clearCachedApps = SessionPrefs.clearCachedApps(this)
|
||||
@@ -2441,10 +2195,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy()) return false
|
||||
if (SessionState.installing != null && !SessionState.running) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
}
|
||||
if (com.droiddeck.launcher.storage.StorageState.cleaning) {
|
||||
android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show()
|
||||
return false
|
||||
@@ -2566,9 +2316,6 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private const val SESSION_SWITCH_WAIT_MS = 30_000L
|
||||
private const val SESSION_SWITCH_POLL_MS = 250L
|
||||
private const val KEY_PENDING_SWITCH = "pending_switch"
|
||||
private const val KEY_COMPAT_LAUNCH = "compat_launch"
|
||||
private const val KEY_COMPAT_MENU_INSTALL = "compat_menu_install"
|
||||
private const val KEY_COMPAT_PROBLEM = "compat_problem"
|
||||
private const val KEY_SWITCHING_TO = "switching_to"
|
||||
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
|
||||
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
|
||||
|
||||
@@ -6,41 +6,20 @@ import android.graphics.Bitmap
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.content.pm.LauncherApps
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.graphics.Rect
|
||||
import android.os.Process
|
||||
import android.os.UserHandle
|
||||
import android.os.UserManager
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
object HomeApp {
|
||||
private const val ICON_DP = 72
|
||||
|
||||
data class LaunchableApp(
|
||||
val label: String,
|
||||
val packageName: String,
|
||||
val className: String,
|
||||
val icon: Bitmap?,
|
||||
val system: Boolean = false,
|
||||
val game: Boolean = false,
|
||||
val installedAt: Long = 0L,
|
||||
val updatedAt: Long = 0L,
|
||||
val user: UserHandle? = null,
|
||||
val userSerial: Long = 0L,
|
||||
) {
|
||||
val component get() = ComponentName(packageName, className)
|
||||
val key get() = "$packageName/$className" + if (userSerial != 0L) "#$userSerial" else ""
|
||||
val work get() = userSerial != 0L
|
||||
}
|
||||
)
|
||||
|
||||
fun isHomeScreenEnabled(context: Context): Boolean =
|
||||
context.packageManager.getComponentEnabledSetting(ComponentName(context, HomeActivity::class.java)) ==
|
||||
@@ -90,79 +69,33 @@ object HomeApp {
|
||||
fun settingsIntent(): Intent = Intent(Settings.ACTION_HOME_SETTINGS)
|
||||
|
||||
fun launchableApps(context: Context): List<LaunchableApp> {
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
val users = context.getSystemService(UserManager::class.java)
|
||||
val pm = context.packageManager
|
||||
val own = Process.myUserHandle()
|
||||
val iconPx = (ICON_DP * context.resources.displayMetrics.density).roundToInt()
|
||||
val apps = users.userProfiles.flatMap { user ->
|
||||
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
|
||||
runCatching { launcher.getActivityList(null, user) }.getOrDefault(emptyList()).mapNotNull { info ->
|
||||
val component = info.componentName
|
||||
if (component.packageName == context.packageName && user == own) return@mapNotNull null
|
||||
val label = info.label?.toString()?.trim().orEmpty().ifEmpty { component.packageName }
|
||||
val icon = runCatching { info.getBadgedIcon(0).toBitmap(iconPx, iconPx) }.getOrNull()
|
||||
val app = info.applicationInfo
|
||||
val updated = if (user == own) runCatching { pm.getPackageInfo(component.packageName, 0).lastUpdateTime }.getOrNull() else null
|
||||
@Suppress("DEPRECATION")
|
||||
val game = app.category == ApplicationInfo.CATEGORY_GAME || app.flags and ApplicationInfo.FLAG_IS_GAME != 0
|
||||
LaunchableApp(
|
||||
label, component.packageName, component.className, icon,
|
||||
system = app.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0,
|
||||
game = game,
|
||||
installedAt = info.firstInstallTime,
|
||||
updatedAt = updated ?: info.firstInstallTime,
|
||||
user = user,
|
||||
userSerial = serial,
|
||||
)
|
||||
val launch = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
val apps = pm.queryIntentActivities(launch, 0)
|
||||
.asSequence()
|
||||
.mapNotNull { result ->
|
||||
val activity = result.activityInfo ?: return@mapNotNull null
|
||||
if (!activity.exported || activity.packageName == context.packageName) return@mapNotNull null
|
||||
val label = result.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { activity.packageName }
|
||||
val icon = runCatching { result.loadIcon(pm).toBitmap(48, 48) }.getOrNull()
|
||||
LaunchableApp(label, activity.packageName, activity.name, icon)
|
||||
}
|
||||
.distinctBy { it.packageName }
|
||||
.toList()
|
||||
return apps.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
}
|
||||
|
||||
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))
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (displayId == null) {
|
||||
context.startActivity(intent)
|
||||
return
|
||||
}
|
||||
return apps.distinctBy { it.key }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
}
|
||||
|
||||
fun launch(context: Context, app: LaunchableApp, displayId: Int? = null, bounds: Rect? = null) {
|
||||
val options = displayId?.let { ActivityOptions.makeBasic().setLaunchDisplayId(it).toBundle() }
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
launcher.startMainActivity(app.component, app.user ?: Process.myUserHandle(), bounds, options)
|
||||
}
|
||||
|
||||
fun canUseShortcuts(context: Context): Boolean =
|
||||
runCatching { context.getSystemService(LauncherApps::class.java).hasShortcutHostPermission() }.getOrDefault(false)
|
||||
|
||||
fun shortcuts(context: Context, app: LaunchableApp): List<ShortcutInfo> {
|
||||
if (!canUseShortcuts(context)) return emptyList()
|
||||
val query = LauncherApps.ShortcutQuery()
|
||||
.setPackage(app.packageName)
|
||||
.setActivity(app.component)
|
||||
.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC or LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST)
|
||||
return runCatching { context.getSystemService(LauncherApps::class.java).getShortcuts(query, app.user ?: Process.myUserHandle()) }
|
||||
.getOrNull().orEmpty()
|
||||
.filter { it.isEnabled }
|
||||
.sortedWith(compareBy<ShortcutInfo> { if (it.isDeclaredInManifest) 0 else 1 }.thenBy { it.rank })
|
||||
.take(5)
|
||||
}
|
||||
|
||||
fun shortcutIcon(context: Context, info: ShortcutInfo, px: Int = (ICON_DP * context.resources.displayMetrics.density).roundToInt()): Bitmap? = runCatching {
|
||||
context.getSystemService(LauncherApps::class.java)
|
||||
.getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
|
||||
}.getOrNull()
|
||||
|
||||
fun startShortcut(context: Context, info: ShortcutInfo) {
|
||||
context.getSystemService(LauncherApps::class.java).startShortcut(info, null, null)
|
||||
}
|
||||
|
||||
fun openAppInfo(context: Context, app: LaunchableApp) {
|
||||
context.getSystemService(LauncherApps::class.java)
|
||||
.startAppDetailsActivity(app.component, app.user ?: Process.myUserHandle(), null, null)
|
||||
}
|
||||
|
||||
fun canUninstall(app: LaunchableApp): Boolean = !app.system && !app.work
|
||||
|
||||
fun uninstall(context: Context, app: LaunchableApp) {
|
||||
context.startActivity(
|
||||
Intent(Intent.ACTION_DELETE, Uri.fromParts("package", app.packageName, null))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
val options = ActivityOptions.makeBasic().setLaunchDisplayId(displayId)
|
||||
context.startActivity(intent, options.toBundle())
|
||||
}
|
||||
|
||||
fun isActiveSteamSession(): Boolean =
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.UUID
|
||||
|
||||
object HomeFolders {
|
||||
data class Folder(val id: String, val name: String, val apps: List<String>)
|
||||
|
||||
private const val PREFS = "home_launcher"
|
||||
private const val KEY = "folders"
|
||||
|
||||
var folders by mutableStateOf<List<Folder>>(emptyList())
|
||||
private set
|
||||
private var loaded = false
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
|
||||
folders = runCatching {
|
||||
val array = JSONArray(raw)
|
||||
(0 until array.length()).map { i ->
|
||||
val o = array.getJSONObject(i)
|
||||
val apps = o.getJSONArray("apps")
|
||||
Folder(o.getString("id"), o.getString("name"), (0 until apps.length()).map { apps.getString(it) })
|
||||
}
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
fun create(context: Context, name: String, appKey: String): Folder {
|
||||
val folder = Folder(UUID.randomUUID().toString(), name, listOf(appKey))
|
||||
update(context, without(appKey) + folder)
|
||||
return folder
|
||||
}
|
||||
|
||||
fun add(context: Context, folderId: String, appKey: String) =
|
||||
update(context, without(appKey).map { if (it.id == folderId) it.copy(apps = it.apps + appKey) else it })
|
||||
|
||||
fun remove(context: Context, appKey: String) = update(context, without(appKey))
|
||||
|
||||
fun rename(context: Context, folderId: String, name: String) =
|
||||
update(context, folders.map { if (it.id == folderId) it.copy(name = name) else it })
|
||||
|
||||
fun delete(context: Context, folderId: String) = update(context, folders.filterNot { it.id == folderId })
|
||||
|
||||
fun migrateMembers(context: Context, keyFor: (String) -> String?) {
|
||||
if (folders.none { f -> f.apps.any { '/' !in it } }) return
|
||||
update(context, folders.map { f -> f.copy(apps = f.apps.map { if ('/' in it) it else keyFor(it) ?: it }.distinct()) })
|
||||
}
|
||||
|
||||
private fun without(appKey: String): List<Folder> =
|
||||
folders.map { it.copy(apps = it.apps - appKey) }.filter { it.apps.isNotEmpty() }
|
||||
|
||||
private fun update(context: Context, next: List<Folder>) {
|
||||
folders = next
|
||||
val array = JSONArray()
|
||||
for (f in next) array.put(JSONObject().put("id", f.id).put("name", f.name).put("apps", JSONArray(f.apps)))
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
object HomeHidden {
|
||||
private const val PREFS = "home_launcher"
|
||||
private const val KEY = "hidden"
|
||||
|
||||
var keys by mutableStateOf<Set<String>>(emptySet())
|
||||
private set
|
||||
private var loaded = false
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
keys = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getStringSet(KEY, emptySet()).orEmpty().toSet()
|
||||
}
|
||||
|
||||
fun set(context: Context, key: String, hidden: Boolean) {
|
||||
keys = if (hidden) keys + key else keys - key
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putStringSet(KEY, keys).apply()
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.LauncherApps
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.Process
|
||||
import android.os.UserManager
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
/** Shortcuts other apps asked to put on the home screen. The system keeps the pinned set per launcher. */
|
||||
object HomePins {
|
||||
class Pinned(val info: ShortcutInfo, val icon: Bitmap?, val appLabel: String, val userSerial: Long) {
|
||||
val key get() = "pin:${info.`package`}/${info.id}" + if (userSerial != 0L) "#$userSerial" else ""
|
||||
val label get() = info.shortLabel?.toString()?.trim().orEmpty().ifEmpty { appLabel }
|
||||
val work get() = userSerial != 0L
|
||||
}
|
||||
|
||||
var pinned by mutableStateOf<List<Pinned>>(emptyList())
|
||||
private set
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private var listing = 0
|
||||
|
||||
fun refresh(context: Context) {
|
||||
val app = context.applicationContext
|
||||
val seq = ++listing
|
||||
Thread({
|
||||
val list = runCatching { load(app) }.getOrDefault(emptyList())
|
||||
main.post { if (seq == listing) pinned = list }
|
||||
}, "home-pins").start()
|
||||
}
|
||||
|
||||
private fun load(context: Context): List<Pinned> {
|
||||
if (!HomeApp.canUseShortcuts(context)) return emptyList()
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
val users = context.getSystemService(UserManager::class.java)
|
||||
val pm = context.packageManager
|
||||
val own = Process.myUserHandle()
|
||||
val query = LauncherApps.ShortcutQuery().setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
|
||||
return users.userProfiles.flatMap { user ->
|
||||
val serial = if (user == own) 0L else users.getSerialNumberForUser(user)
|
||||
runCatching { launcher.getShortcuts(query, user) }.getOrNull().orEmpty()
|
||||
.filter { it.isEnabled && it.isPinned }
|
||||
.map { info ->
|
||||
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.`package`, 0)).toString() }
|
||||
.getOrDefault(info.`package`)
|
||||
Pinned(info, HomeApp.shortcutIcon(context, info), appLabel, serial)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun accept(context: Context, request: LauncherApps.PinItemRequest): Boolean {
|
||||
val ok = runCatching { request.isValid && request.accept() }.getOrDefault(false)
|
||||
if (ok) refresh(context)
|
||||
return ok
|
||||
}
|
||||
|
||||
fun unpin(context: Context, pinned: Pinned) {
|
||||
val info = pinned.info
|
||||
val launcher = context.getSystemService(LauncherApps::class.java)
|
||||
val query = LauncherApps.ShortcutQuery().setPackage(info.`package`).setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED)
|
||||
val unpinned = runCatching {
|
||||
val current = checkNotNull(launcher.getShortcuts(query, info.userHandle))
|
||||
val keep = current.map { it.id } - info.id
|
||||
launcher.pinShortcuts(info.`package`, keep, info.userHandle)
|
||||
}.isSuccess
|
||||
if (!unpinned) return
|
||||
listing++
|
||||
this.pinned = this.pinned.filterNot { it.key == pinned.key }
|
||||
}
|
||||
}
|
||||
@@ -1,317 +0,0 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.Activity
|
||||
import android.appwidget.AppWidgetHost
|
||||
import android.appwidget.AppWidgetHostView
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProviderInfo
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.LauncherApps
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.SizeF
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewConfiguration
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
object HomeWidgets {
|
||||
data class Placed(val id: Int, val widthDp: Int, val heightDp: Int)
|
||||
|
||||
data class Provider(
|
||||
val info: AppWidgetProviderInfo,
|
||||
val label: String,
|
||||
val appLabel: String,
|
||||
val preview: Bitmap?,
|
||||
val widthDp: Int,
|
||||
val heightDp: Int,
|
||||
)
|
||||
|
||||
private const val HOST_ID = 0x0DDE
|
||||
private const val PREFS = "home_launcher"
|
||||
private const val KEY = "widgets"
|
||||
private const val REQUEST_BIND = 0x0DD1
|
||||
private const val REQUEST_CONFIGURE = 0x0DD2
|
||||
private const val REQUEST_RECONFIGURE = 0x0DD3
|
||||
const val MIN_WIDTH_DP = 96
|
||||
const val MIN_HEIGHT_DP = 56
|
||||
|
||||
var widgets by mutableStateOf<List<Placed>>(emptyList())
|
||||
private set
|
||||
var providers by mutableStateOf<List<Provider>?>(null)
|
||||
private set
|
||||
private var loaded = false
|
||||
private var host: Host? = null
|
||||
private var pending: AppWidgetProviderInfo? = null
|
||||
private var pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
private var pinRequest: LauncherApps.PinItemRequest? = null
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
private class Host(context: Context) : AppWidgetHost(context, HOST_ID) {
|
||||
override fun onCreateView(context: Context, appWidgetId: Int, appWidget: AppWidgetProviderInfo?): AppWidgetHostView =
|
||||
HomeWidgetView(context)
|
||||
}
|
||||
|
||||
class HomeWidgetView(context: Context) : AppWidgetHostView(context) {
|
||||
var onLongPress: (() -> Unit)? = null
|
||||
private var fired = false
|
||||
private var downX = 0f
|
||||
private var downY = 0f
|
||||
private val slop = ViewConfiguration.get(context).scaledTouchSlop
|
||||
private val longPress = Runnable {
|
||||
fired = true
|
||||
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
|
||||
onLongPress?.invoke()
|
||||
}
|
||||
|
||||
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
|
||||
when (ev.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
fired = false
|
||||
downX = ev.x
|
||||
downY = ev.y
|
||||
postDelayed(longPress, ViewConfiguration.getLongPressTimeout().toLong())
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> if (hypot(ev.x - downX, ev.y - downY) > slop) removeCallbacks(longPress)
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_DOWN -> removeCallbacks(longPress)
|
||||
}
|
||||
return fired
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (fired) {
|
||||
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) fired = false
|
||||
return true
|
||||
}
|
||||
return super.onTouchEvent(event)
|
||||
}
|
||||
}
|
||||
|
||||
private fun host(context: Context): Host = host ?: Host(context.applicationContext).also { host = it }
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val raw = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null) ?: return
|
||||
val manager = AppWidgetManager.getInstance(context)
|
||||
val parsed = runCatching {
|
||||
val array = JSONArray(raw)
|
||||
(0 until array.length()).map { i ->
|
||||
val o = array.getJSONObject(i)
|
||||
Placed(o.getInt("id"), o.getInt("w"), o.getInt("h"))
|
||||
}
|
||||
}.getOrDefault(emptyList())
|
||||
val live = parsed.filter { manager.getAppWidgetInfo(it.id) != null }
|
||||
parsed.filterNot { it in live }.forEach { host(context).deleteAppWidgetId(it.id) }
|
||||
widgets = live
|
||||
if (live.size != parsed.size) save(context)
|
||||
}
|
||||
|
||||
fun startListening(context: Context) {
|
||||
load(context)
|
||||
runCatching { host(context).startListening() }
|
||||
}
|
||||
|
||||
fun stopListening(context: Context) {
|
||||
runCatching { host(context).stopListening() }
|
||||
}
|
||||
|
||||
fun info(context: Context, id: Int): AppWidgetProviderInfo? = AppWidgetManager.getInstance(context).getAppWidgetInfo(id)
|
||||
|
||||
fun createView(context: Context, id: Int): HomeWidgetView? {
|
||||
val info = info(context, id) ?: return null
|
||||
return host(context).createView(context, id, info) as? HomeWidgetView
|
||||
}
|
||||
|
||||
fun applySize(view: AppWidgetHostView, widthDp: Int, heightDp: Int) {
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
view.updateAppWidgetSize(Bundle(), listOf(SizeF(widthDp.toFloat(), heightDp.toFloat())))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
view.updateAppWidgetSize(null, widthDp, heightDp, widthDp, heightDp)
|
||||
}
|
||||
}
|
||||
|
||||
fun loadProviders(context: Context) {
|
||||
if (providers != null) return
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
val pm = app.packageManager
|
||||
val manager = AppWidgetManager.getInstance(app)
|
||||
val dpi = app.resources.displayMetrics.densityDpi
|
||||
val list = manager.installedProviders.mapNotNull { info ->
|
||||
runCatching {
|
||||
val appLabel = runCatching { pm.getApplicationLabel(pm.getApplicationInfo(info.provider.packageName, 0)).toString() }
|
||||
.getOrDefault(info.provider.packageName)
|
||||
val drawable = info.loadPreviewImage(app, dpi) ?: info.loadIcon(app, dpi)
|
||||
val preview = drawable?.let { d ->
|
||||
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
|
||||
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
|
||||
val scale = minOf(1f, 360f / maxOf(w, h))
|
||||
d.toBitmap((w * scale).roundToInt().coerceAtLeast(1), (h * scale).roundToInt().coerceAtLeast(1))
|
||||
}
|
||||
val (w, h) = defaultSize(app, info)
|
||||
Provider(info, info.loadLabel(pm)?.toString()?.trim().orEmpty().ifEmpty { appLabel }, appLabel, preview, w, h)
|
||||
}.getOrNull()
|
||||
}.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, Provider::appLabel).thenBy(String.CASE_INSENSITIVE_ORDER, Provider::label))
|
||||
main.post { providers = list }
|
||||
}, "widget-providers").start()
|
||||
}
|
||||
|
||||
fun refreshProviders(context: Context) {
|
||||
providers = null
|
||||
loadProviders(context)
|
||||
}
|
||||
|
||||
private fun defaultSize(context: Context, info: AppWidgetProviderInfo): Pair<Int, Int> {
|
||||
val density = context.resources.displayMetrics.density
|
||||
var w = (info.minWidth / density).roundToInt()
|
||||
var h = (info.minHeight / density).roundToInt()
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
if (info.targetCellWidth > 0) w = maxOf(w, info.targetCellWidth * 80)
|
||||
if (info.targetCellHeight > 0) h = maxOf(h, info.targetCellHeight * 80)
|
||||
}
|
||||
return w.coerceIn(160, 560) to h.coerceIn(MIN_HEIGHT_DP, 360)
|
||||
}
|
||||
|
||||
fun minSize(context: Context, id: Int): Pair<Int, Int> {
|
||||
val info = info(context, id) ?: return MIN_WIDTH_DP to MIN_HEIGHT_DP
|
||||
val density = context.resources.displayMetrics.density
|
||||
val w = (if (info.minResizeWidth > 0) info.minResizeWidth else info.minWidth) / density
|
||||
val h = (if (info.minResizeHeight > 0) info.minResizeHeight else info.minHeight) / density
|
||||
return w.roundToInt().coerceAtLeast(MIN_WIDTH_DP) to h.roundToInt().coerceAtLeast(MIN_HEIGHT_DP)
|
||||
}
|
||||
|
||||
fun add(activity: Activity, provider: Provider) {
|
||||
if (pendingId == AppWidgetManager.INVALID_APPWIDGET_ID) add(activity, provider.info, null)
|
||||
}
|
||||
|
||||
/** Places a widget another app asked for; its own app has already configured it. */
|
||||
fun addPinned(activity: Activity, request: LauncherApps.PinItemRequest): Boolean {
|
||||
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) return false
|
||||
val info = request.getAppWidgetProviderInfo(activity) ?: return false
|
||||
load(activity)
|
||||
add(activity, info, request)
|
||||
return pending != null
|
||||
}
|
||||
|
||||
private fun add(activity: Activity, info: AppWidgetProviderInfo, request: LauncherApps.PinItemRequest?) {
|
||||
val h = host(activity)
|
||||
val id = h.allocateAppWidgetId()
|
||||
pending = info
|
||||
pendingId = id
|
||||
pinRequest = request
|
||||
val manager = AppWidgetManager.getInstance(activity)
|
||||
val bound = runCatching { manager.bindAppWidgetIdIfAllowed(id, info.profile, info.provider, null) }.getOrDefault(false)
|
||||
if (bound) {
|
||||
bound(activity, id, info)
|
||||
return
|
||||
}
|
||||
val bind = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, info.profile)
|
||||
@Suppress("DEPRECATION")
|
||||
runCatching { activity.startActivityForResult(bind, REQUEST_BIND) }.onFailure { abandon(activity) }
|
||||
}
|
||||
|
||||
private fun bound(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
|
||||
val request = pinRequest
|
||||
if (request == null) {
|
||||
configure(activity, id, info)
|
||||
return
|
||||
}
|
||||
val accepted = runCatching { request.isValid && request.accept(Bundle().apply { putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, id) }) }
|
||||
.getOrDefault(false)
|
||||
if (accepted) place(activity, id, info) else abandon(activity)
|
||||
}
|
||||
|
||||
private fun configure(activity: Activity, id: Int, info: AppWidgetProviderInfo) {
|
||||
val optional = Build.VERSION.SDK_INT >= 31 &&
|
||||
info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_CONFIGURATION_OPTIONAL != 0
|
||||
if (info.configure == null || optional) {
|
||||
place(activity, id, info)
|
||||
return
|
||||
}
|
||||
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_CONFIGURE, null) }
|
||||
.onFailure { place(activity, id, info) }
|
||||
}
|
||||
|
||||
fun canReconfigure(context: Context, id: Int): Boolean {
|
||||
val info = info(context, id) ?: return false
|
||||
if (info.configure == null) return false
|
||||
return Build.VERSION.SDK_INT < 28 || info.widgetFeatures and AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE != 0
|
||||
}
|
||||
|
||||
fun reconfigure(activity: Activity, id: Int) {
|
||||
runCatching { host(activity).startAppWidgetConfigureActivityForResult(activity, id, 0, REQUEST_RECONFIGURE, null) }
|
||||
}
|
||||
|
||||
fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int): Boolean {
|
||||
when (requestCode) {
|
||||
REQUEST_BIND -> {
|
||||
val info = pending
|
||||
if (resultCode == Activity.RESULT_OK && info != null) bound(activity, pendingId, info) else abandon(activity)
|
||||
}
|
||||
REQUEST_CONFIGURE -> {
|
||||
val info = pending
|
||||
if (resultCode == Activity.RESULT_OK && info != null) place(activity, pendingId, info) else abandon(activity)
|
||||
}
|
||||
REQUEST_RECONFIGURE -> Unit
|
||||
else -> return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun abandon(context: Context) {
|
||||
if (pendingId != AppWidgetManager.INVALID_APPWIDGET_ID) host(context).deleteAppWidgetId(pendingId)
|
||||
pending = null
|
||||
pinRequest = null
|
||||
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
}
|
||||
|
||||
private fun place(context: Context, id: Int, info: AppWidgetProviderInfo) {
|
||||
val (w, h) = defaultSize(context, info)
|
||||
pending = null
|
||||
pinRequest = null
|
||||
pendingId = AppWidgetManager.INVALID_APPWIDGET_ID
|
||||
widgets = widgets + Placed(id, w, h)
|
||||
save(context)
|
||||
}
|
||||
|
||||
fun resize(context: Context, id: Int, widthDp: Int, heightDp: Int) {
|
||||
widgets = widgets.map { if (it.id == id) it.copy(widthDp = widthDp, heightDp = heightDp) else it }
|
||||
save(context)
|
||||
}
|
||||
|
||||
fun move(context: Context, id: Int, by: Int) {
|
||||
val i = widgets.indexOfFirst { it.id == id }
|
||||
val j = i + by
|
||||
if (i < 0 || j !in widgets.indices) return
|
||||
widgets = widgets.toMutableList().apply { add(j, removeAt(i)) }
|
||||
save(context)
|
||||
}
|
||||
|
||||
fun remove(context: Context, id: Int) {
|
||||
host(context).deleteAppWidgetId(id)
|
||||
widgets = widgets.filterNot { it.id == id }
|
||||
save(context)
|
||||
}
|
||||
|
||||
private fun save(context: Context) {
|
||||
val array = JSONArray()
|
||||
for (w in widgets) array.put(JSONObject().put("id", w.id).put("w", w.widthDp).put("h", w.heightDp))
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, array.toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -1,328 +0,0 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.app.ActivityOptions
|
||||
import android.app.AppOpsManager
|
||||
import android.app.PictureInPictureParams
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Process
|
||||
import android.provider.Settings
|
||||
import android.util.Rational
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.animation.core.LinearEasing
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.core.AppLanguage
|
||||
import com.droiddeck.launcher.core.GlobalSettings
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService
|
||||
import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.LocalPalette
|
||||
import com.droiddeck.launcher.ui.PrimaryButton
|
||||
import com.droiddeck.launcher.ui.SecondaryButton
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
class PairingGuideActivity : ComponentActivity() {
|
||||
enum class Step { BUILD_NUMBER, WIRELESS_DEBUGGING, PAIR, CODE, WORKING, DONE, FAILED }
|
||||
|
||||
private var settingsDisplay: Int? = null
|
||||
private var inPip by mutableStateOf(false)
|
||||
private var launchPending = false
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
||||
setContent { DroidDeckTheme { Guide() } }
|
||||
launchPending = savedInstanceState == null
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
settingsDisplay = intent.getIntExtra(EXTRA_DISPLAY, -1).takeIf { it >= 0 }
|
||||
launchPending = true
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (!launchPending) return
|
||||
if (inPip || settingsDisplay != null) {
|
||||
launchSettings()
|
||||
return
|
||||
}
|
||||
enterPip()
|
||||
if (!inPip) launchSettings()
|
||||
}
|
||||
|
||||
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
|
||||
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
|
||||
inPip = isInPictureInPictureMode
|
||||
if (isInPictureInPictureMode && launchPending) launchSettings()
|
||||
}
|
||||
|
||||
private fun launchSettings() {
|
||||
launchPending = false
|
||||
openSettings(stepFor(this, WirelessAdbPairingService.stage.value))
|
||||
}
|
||||
|
||||
private fun enterPip() {
|
||||
inPip = runCatching {
|
||||
enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(4, 3)).build())
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
private fun openSettings(step: Step) {
|
||||
val intent = if (step == Step.BUILD_NUMBER) {
|
||||
Intent(Settings.ACTION_DEVICE_INFO_SETTINGS).putExtra(HIGHLIGHT_KEY, "build_number")
|
||||
} else {
|
||||
Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS).putExtra(HIGHLIGHT_KEY, "toggle_adb_wireless")
|
||||
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val display = settingsDisplay
|
||||
runCatching {
|
||||
if (display == null) startActivity(intent)
|
||||
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
|
||||
}.onFailure {
|
||||
runCatching { startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun returnToApp() {
|
||||
startActivity(Intent(this, FrontEndActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
|
||||
finish()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Guide() {
|
||||
val stage by WirelessAdbPairingService.stage.collectAsState()
|
||||
val settingsState by produceState(SettingsState.read(this)) {
|
||||
while (true) {
|
||||
value = SettingsState.read(this@PairingGuideActivity)
|
||||
delay(500)
|
||||
}
|
||||
}
|
||||
val step = stepFor(settingsState, stage)
|
||||
var previous by remember { mutableStateOf(step) }
|
||||
LaunchedEffect(step) {
|
||||
if (previous == Step.BUILD_NUMBER && step == Step.WIRELESS_DEBUGGING) openSettings(step)
|
||||
previous = step
|
||||
when (step) {
|
||||
Step.DONE -> { delay(1_500); returnToApp() }
|
||||
Step.FAILED -> { delay(3_000); returnToApp() }
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
LaunchedEffect(stage) { if (stage == Stage.Idle) finish() }
|
||||
BackHandler(enabled = !inPip && settingsDisplay == null) { enterPip() }
|
||||
|
||||
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {
|
||||
if (inPip) CompactStep(step, stage)
|
||||
else FullGuide(step, stage)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CompactStep(step: Step, stage: Stage) {
|
||||
Column(Modifier.fillMaxSize().padding(10.dp), verticalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(
|
||||
instruction(step, stage), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onBackground, maxLines = 3, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
StepVisual(step, compact = true)
|
||||
StepDots(step)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FullGuide(step: Step, stage: Stage) {
|
||||
Column(
|
||||
Modifier.widthIn(max = 520.dp).fillMaxWidth().padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.gate_title), style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text(instruction(step, stage), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground)
|
||||
StepVisual(step, compact = false)
|
||||
StepDots(step)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
if (step == Step.DONE || step == Step.FAILED) {
|
||||
PrimaryButton(stringResource(R.string.common_back), onClick = ::returnToApp)
|
||||
} else {
|
||||
PrimaryButton(stringResource(R.string.gate_open_dev), onClick = {
|
||||
if (settingsDisplay == null) enterPip()
|
||||
openSettings(step)
|
||||
})
|
||||
SecondaryButton(stringResource(R.string.common_cancel), onClick = {
|
||||
WirelessAdbPairingService.cancel(this@PairingGuideActivity)
|
||||
returnToApp()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun instruction(step: Step, stage: Stage): String = when (step) {
|
||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_build_number)
|
||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_wireless)
|
||||
Step.PAIR -> stringResource(R.string.pairguide_pair)
|
||||
Step.CODE -> (stage as? Stage.CodeNeeded)?.error ?: stringResource(R.string.gate_step3)
|
||||
Step.WORKING -> (stage as? Stage.Working)?.step ?: stringResource(R.string.adbpair_title_working)
|
||||
Step.DONE -> stringResource(R.string.adbpair_title_done)
|
||||
Step.FAILED -> (stage as? Stage.Failed)?.error ?: stringResource(R.string.adbpair_title_failed)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StepVisual(step: Step, compact: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val accent = LocalPalette.current.signal
|
||||
val pulse = rememberInfiniteTransition(label = "guidePulse")
|
||||
val beat by pulse.animateFloat(0f, 1f, infiniteRepeatable(tween(900, easing = LinearEasing), RepeatMode.Restart), label = "beat")
|
||||
val label = when (step) {
|
||||
Step.BUILD_NUMBER -> stringResource(R.string.pairguide_row_build_number)
|
||||
Step.WIRELESS_DEBUGGING -> stringResource(R.string.pairguide_row_wireless)
|
||||
Step.PAIR -> stringResource(R.string.pairguide_row_pair)
|
||||
Step.CODE -> stringResource(R.string.adbpair_enter_code)
|
||||
Step.WORKING, Step.DONE, Step.FAILED -> return
|
||||
}
|
||||
val rowHeight = if (compact) 34.dp else 56.dp
|
||||
Row(
|
||||
Modifier.fillMaxWidth().height(rowHeight).background(colors.surfaceVariant, RoundedCornerShape(10.dp))
|
||||
.border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(10.dp)).padding(horizontal = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(label, style = if (compact) MaterialTheme.typography.labelMedium else MaterialTheme.typography.bodyLarge,
|
||||
color = colors.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
when (step) {
|
||||
Step.WIRELESS_DEBUGGING -> Toggle(on = beat > 0.5f, accent = accent, compact = compact)
|
||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (step == Step.BUILD_NUMBER) Text("×7", style = MaterialTheme.typography.labelLarge, color = accent)
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Box(Modifier.size(if (compact) 18.dp else 26.dp).scale(0.6f + beat * 0.8f).alpha(1f - beat)
|
||||
.background(accent, CircleShape))
|
||||
Box(Modifier.size(if (compact) 8.dp else 12.dp).background(accent, CircleShape))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Toggle(on: Boolean, accent: Color, compact: Boolean) {
|
||||
val width = if (compact) 26.dp else 40.dp
|
||||
val knob = if (compact) 12.dp else 18.dp
|
||||
Box(
|
||||
Modifier.width(width).height(knob + 4.dp)
|
||||
.background(if (on) accent.copy(alpha = 0.6f) else MaterialTheme.colorScheme.outline, CircleShape).padding(2.dp),
|
||||
contentAlignment = if (on) Alignment.CenterEnd else Alignment.CenterStart,
|
||||
) { Box(Modifier.size(knob).background(Color.White, CircleShape)) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StepDots(step: Step) {
|
||||
val accent = LocalPalette.current.signal
|
||||
val shown = listOf(Step.BUILD_NUMBER, Step.WIRELESS_DEBUGGING, Step.PAIR, Step.CODE)
|
||||
val at = shown.indexOf(step).takeIf { it >= 0 } ?: shown.size
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(5.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
shown.forEachIndexed { index, _ ->
|
||||
Box(Modifier.size(if (index == at) 8.dp else 6.dp)
|
||||
.background(if (index <= at) accent else MaterialTheme.colorScheme.outline, CircleShape))
|
||||
}
|
||||
Spacer(Modifier.width(2.dp))
|
||||
}
|
||||
}
|
||||
|
||||
private data class SettingsState(val developerOptions: Boolean, val wirelessDebugging: Boolean) {
|
||||
companion object {
|
||||
fun read(context: Context) = SettingsState(
|
||||
GlobalSettings.developerOptionsOn(context),
|
||||
GlobalSettings.wirelessDebuggingOn(context),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val EXTRA_DISPLAY = "settingsDisplay"
|
||||
private const val HIGHLIGHT_KEY = ":settings:fragment_args_key"
|
||||
|
||||
private fun stepFor(context: Context, stage: Stage) = stepFor(SettingsState.read(context), stage)
|
||||
|
||||
private fun stepFor(settings: SettingsState, stage: Stage): Step = when (stage) {
|
||||
is Stage.Working -> Step.WORKING
|
||||
Stage.Done -> Step.DONE
|
||||
is Stage.Failed -> Step.FAILED
|
||||
is Stage.CodeNeeded -> Step.CODE
|
||||
else -> when {
|
||||
!settings.developerOptions -> Step.BUILD_NUMBER
|
||||
!settings.wirelessDebugging -> Step.WIRELESS_DEBUGGING
|
||||
else -> Step.PAIR
|
||||
}
|
||||
}
|
||||
|
||||
fun canFloat(context: Context): Boolean {
|
||||
if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false
|
||||
val ops = context.getSystemService(AppOpsManager::class.java) ?: return true
|
||||
val mode = if (Build.VERSION.SDK_INT >= 29) {
|
||||
ops.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
ops.checkOpNoThrow(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, Process.myUid(), context.packageName)
|
||||
}
|
||||
return mode == AppOpsManager.MODE_ALLOWED
|
||||
}
|
||||
|
||||
fun start(context: Context, settingsDisplay: Int?): Boolean {
|
||||
if (settingsDisplay == null && !canFloat(context)) return false
|
||||
context.startActivity(Intent(context, PairingGuideActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
.apply { if (settingsDisplay != null) putExtra(EXTRA_DISPLAY, settingsDisplay) })
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Intent
|
||||
import android.content.pm.LauncherApps
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import com.droiddeck.launcher.core.AppUiPrefs
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.PinRequestPrompt
|
||||
|
||||
class PinRequestActivity : ComponentActivity() {
|
||||
override fun attachBaseContext(newBase: android.content.Context) {
|
||||
super.attachBaseContext(newBase)
|
||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val request = runCatching { getSystemService(LauncherApps::class.java).getPinItemRequest(intent) }.getOrNull()
|
||||
if (request == null || !request.isValid) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val prompt = when (request.requestType) {
|
||||
LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT -> request.shortcutInfo?.let { info ->
|
||||
val appLabel = appLabel(info.`package`)
|
||||
Triple(info.shortLabel?.toString().orEmpty().ifEmpty { appLabel }, appLabel, HomeApp.shortcutIcon(this, info))
|
||||
}
|
||||
LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET -> request.getAppWidgetProviderInfo(this)?.let { info ->
|
||||
val appLabel = appLabel(info.provider.packageName)
|
||||
val dpi = resources.displayMetrics.densityDpi
|
||||
val icon = runCatching { (info.loadPreviewImage(this, dpi) ?: info.loadIcon(this, dpi))?.let(::scaled) }.getOrNull()
|
||||
Triple(info.loadLabel(packageManager)?.toString().orEmpty().ifEmpty { appLabel }, appLabel, icon)
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
if (prompt == null) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
val (label, appLabel, icon) = prompt
|
||||
val widget = request.requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_APPWIDGET
|
||||
setContent {
|
||||
DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
|
||||
PinRequestPrompt(
|
||||
label = label, appLabel = appLabel, icon = icon, wide = widget,
|
||||
onAdd = {
|
||||
if (!widget) {
|
||||
HomePins.accept(this, request)
|
||||
finish()
|
||||
} else if (!HomeWidgets.addPinned(this, request)) finish()
|
||||
},
|
||||
onCancel = { finish() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
if (HomeWidgets.onActivityResult(this, requestCode, resultCode)) {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
}
|
||||
|
||||
private fun appLabel(packageName: String): String =
|
||||
runCatching { packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, 0)).toString() }
|
||||
.getOrDefault(packageName)
|
||||
|
||||
private fun scaled(d: android.graphics.drawable.Drawable): Bitmap {
|
||||
val w = d.intrinsicWidth.takeIf { it > 0 } ?: 192
|
||||
val h = d.intrinsicHeight.takeIf { it > 0 } ?: 192
|
||||
val k = minOf(1f, 480f / maxOf(w, h))
|
||||
return d.toBitmap((w * k).toInt().coerceAtLeast(1), (h * k).toInt().coerceAtLeast(1))
|
||||
}
|
||||
}
|
||||
@@ -20,19 +20,10 @@ internal class ProtonMenu(
|
||||
private val ui: Handler,
|
||||
private val idle: () -> Boolean = { true },
|
||||
) {
|
||||
// Install workers and their results outlive the activity that starts them.
|
||||
private object Operation {
|
||||
val rows = mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
val busyId = mutableStateOf<String?>(null)
|
||||
val stage = mutableStateOf<String?>(null)
|
||||
val percent = mutableIntStateOf(-1)
|
||||
val problem = mutableStateOf<String?>(null)
|
||||
}
|
||||
var protonRows by Operation.rows
|
||||
var protonBusyId by Operation.busyId
|
||||
var protonStage by Operation.stage
|
||||
var protonPercent by Operation.percent
|
||||
var protonProblem by Operation.problem
|
||||
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
var protonBusyId by mutableStateOf<String?>(null)
|
||||
var protonStage by mutableStateOf<String?>(null)
|
||||
var protonPercent by mutableIntStateOf(-1)
|
||||
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
||||
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
|
||||
@@ -42,7 +33,6 @@ internal class ProtonMenu(
|
||||
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return
|
||||
ProtonExtras.unqueue(activity, tool)
|
||||
protonBusyId = id
|
||||
protonProblem = null
|
||||
protonStage = activity.getString(R.string.store_starting)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
@@ -53,7 +43,6 @@ internal class ProtonMenu(
|
||||
}.getOrElse { it.message ?: it.javaClass.simpleName }
|
||||
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
|
||||
ui.post {
|
||||
protonProblem = problem
|
||||
protonBusyId = null
|
||||
protonStage = null
|
||||
protonPercent = -1
|
||||
@@ -71,7 +60,6 @@ internal class ProtonMenu(
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
if (protonBusyId != null || SessionState.running) return
|
||||
protonBusyId = id
|
||||
protonProblem = null
|
||||
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
@@ -110,7 +98,6 @@ internal class ProtonMenu(
|
||||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
|
||||
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
|
||||
protonBusyId = ProtonExtras.OWN
|
||||
protonProblem = null
|
||||
Thread({
|
||||
ProtonExtras.tidy(activity)
|
||||
val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
|
||||
|
||||
@@ -9,7 +9,6 @@ import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Environment
|
||||
import android.database.ContentObserver
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
@@ -68,7 +67,6 @@ import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import com.droiddeck.launcher.gpu.Lossless
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.input.EvdevKeys
|
||||
import com.droiddeck.launcher.input.HomeGuideInput
|
||||
import com.droiddeck.launcher.input.InputSpace
|
||||
import com.droiddeck.launcher.input.KeyboardHost
|
||||
import com.droiddeck.launcher.input.ControllerPrefs
|
||||
@@ -262,8 +260,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private val backQamInput = com.droiddeck.launcher.input.BackQamInput(
|
||||
setPressed = { padBridge?.setBackQamPressed(it) },
|
||||
onTap = { performBackAction(double = it) },
|
||||
doubleTapMs = { backDoubleTapMs.toLong() },
|
||||
onCancel = { padBridge?.cancelBackQam() },
|
||||
)
|
||||
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
|
||||
private var drawerDirectionDownTime = 0L
|
||||
@@ -326,7 +322,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
|
||||
private var drawerControllerActive by mutableStateOf(false)
|
||||
private var backActionsInverted by mutableStateOf(false)
|
||||
private var backDoubleTapMs by mutableStateOf(500)
|
||||
private var lowLatency by mutableStateOf(true)
|
||||
private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
|
||||
private var pcKeyboardOpen by mutableStateOf(false)
|
||||
@@ -356,7 +351,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var glassesOutputActive by mutableStateOf(false)
|
||||
private var pausedFrame by mutableStateOf<com.droiddeck.launcher.ui.PausedFrame?>(null)
|
||||
private var pausedFrameWanted = false
|
||||
private var pauseAnimated by mutableStateOf(false)
|
||||
private var trackingRecovery by mutableStateOf<TrackingRecovery?>(null)
|
||||
private var glasses3dForVr = false
|
||||
private var ended = false
|
||||
@@ -435,14 +429,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
// A higher refresh rate allowed in Android's settings does not change the display while this window
|
||||
// still asks for a lower mode, so the mode is chosen again when the setting changes.
|
||||
private val refreshSettingObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
|
||||
override fun onChange(selfChange: Boolean) {
|
||||
applyOutputPacing()
|
||||
}
|
||||
}
|
||||
|
||||
private fun followPanelRefresh(displayId: Int) {
|
||||
if (!CompositorHost.isStarted) return
|
||||
val output = glassesScreen?.display
|
||||
@@ -489,13 +475,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
// A cancelled install keeps its thread until the download stops; a new launch would reuse its stop flag and close itself.
|
||||
if (savedInstanceState == null && SessionState.installing != null && !SessionState.running) {
|
||||
runtimeRemovalBlocked = true
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
finish()
|
||||
return
|
||||
}
|
||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||
@@ -516,6 +495,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
if (!SessionState.running) {
|
||||
val prefMode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
|
||||
SessionState.performanceMode = SessionPrefs.performanceMode(this, prefMode)
|
||||
}
|
||||
applyOutputPacing()
|
||||
if (!SessionState.running) SessionState.followScreen = followChoice()
|
||||
applyFollowOrientation(resources.configuration)
|
||||
@@ -546,7 +529,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
bridge.setSelectSteam(ControllerPrefs.read(this).selectSteam)
|
||||
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
|
||||
padBridge = bridge
|
||||
bridge.setOnChordInput(backQamInput::onChordInput)
|
||||
SessionState.padBridge = bridge
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
val vr = com.droiddeck.launcher.input.JoyConVr(this, File(filesDir, ".wayland-rt/${com.droiddeck.launcher.input.JoyConVr.FILE}")) { taken, released ->
|
||||
@@ -571,18 +553,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
uiHandler.removeCallbacks(cursorHide)
|
||||
cursorVisible = false
|
||||
}
|
||||
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { controls ->
|
||||
controls.onTouchMiss = miss@{ event ->
|
||||
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
|
||||
event.offsetLocation(controls.left - surfaceView.left.toFloat(), controls.top - surfaceView.top.toFloat())
|
||||
onTouchEvent(event)
|
||||
}
|
||||
root.addView(controls)
|
||||
}
|
||||
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) }
|
||||
screenKeysShown = com.droiddeck.launcher.input.ControllerPrefs.screenKeysShown(this)
|
||||
screenKeys = ScreenKeys(this) { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) }.also { keys ->
|
||||
keys.onTouchMiss = miss@{ event ->
|
||||
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
|
||||
if (routedTouchMode == SessionPrefs.TOUCH_GESTURES &&
|
||||
!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
|
||||
event.offsetLocation(keys.left - surfaceView.left.toFloat(), keys.top - surfaceView.top.toFloat())
|
||||
onTouchEvent(event)
|
||||
}
|
||||
@@ -607,7 +583,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
// game surface and on-screen buttons, in either finger-down order.
|
||||
root.isMotionEventSplittingEnabled = true
|
||||
surfaceView.setOnTouchListener { _, event ->
|
||||
if (!event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
if (routedTouchMode != SessionPrefs.TOUCH_GESTURES) {
|
||||
gestureTouchStreamGate.reset()
|
||||
false
|
||||
} else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) {
|
||||
false
|
||||
@@ -802,7 +779,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
|
||||
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
|
||||
backQamInput.cancel()
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
|
||||
cancelTouchGestures()
|
||||
screenKeys?.stopEditing()
|
||||
}
|
||||
@@ -1043,11 +1019,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
padType = id
|
||||
},
|
||||
backActionsInverted = backActionsInverted,
|
||||
backDoubleTapMs = backDoubleTapMs,
|
||||
onBackDoubleTapMs = { ms ->
|
||||
SessionPrefs.setBackDoubleTapMs(this@SessionActivity, ms)
|
||||
backDoubleTapMs = ms
|
||||
},
|
||||
onBackActionsInverted = { inverted ->
|
||||
SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted)
|
||||
backActionsInverted = inverted
|
||||
@@ -1114,7 +1085,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this@SessionActivity),
|
||||
pipAutoEnter = pipAutoEnter,
|
||||
onPip = { pip.enter() },
|
||||
onPause = ::pauseNow,
|
||||
onPipAutoEnter = { on ->
|
||||
SessionPrefs.setPipAutoEnter(this@SessionActivity, on)
|
||||
pipAutoEnter = on
|
||||
@@ -1184,22 +1154,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
com.droiddeck.launcher.ui.AchievementNotificationOverlay()
|
||||
// Auto and Native resume on their own as the session comes back; only a failed resume needs the button.
|
||||
val autoResume = suspendPolicy == SessionPrefs.SUSPEND_AUTO || suspendPolicy == SessionPrefs.SUSPEND_NATIVE
|
||||
LaunchedEffect(SessionState.manualPause, SessionState.suspended) {
|
||||
if (!SessionState.manualPause && !SessionState.suspended) pauseAnimated = false
|
||||
}
|
||||
SessionPausedOverlay(
|
||||
suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed || SessionState.manualPause),
|
||||
suspended = SessionState.suspended && (!autoResume || SessionState.resumeFailed),
|
||||
engaged = SessionState.resumeRequested || SessionState.resuming,
|
||||
failures = SessionState.resumeFailures,
|
||||
frame = pausedFrame,
|
||||
animateIn = pauseAnimated,
|
||||
title = pausedTitle(),
|
||||
onResume = { SessionService.resume(this@SessionActivity) },
|
||||
onFrameNeeded = ::requestPausedFrame,
|
||||
onHidden = {
|
||||
pausedFrame = null
|
||||
pausedFrameWanted = false
|
||||
pauseAnimated = false
|
||||
},
|
||||
)
|
||||
if (leaving) com.droiddeck.launcher.ui.FloodSpread(
|
||||
@@ -1332,7 +1297,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
performBackAction(double = false)
|
||||
}
|
||||
pendingBackAction = pending
|
||||
uiHandler.postDelayed(pending, backDoubleTapMs.toLong())
|
||||
uiHandler.postDelayed(pending, 500L)
|
||||
}
|
||||
|
||||
private fun performBackAction(double: Boolean) {
|
||||
@@ -1345,8 +1310,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (incoming?.action != SessionService.ACTION_HOME_GUIDE) return
|
||||
incoming.action = null
|
||||
setIntent(incoming)
|
||||
if (SessionState.suspended) SessionService.resume(this)
|
||||
else if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
|
||||
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) sendSteamGuide()
|
||||
}
|
||||
|
||||
|
||||
@@ -1667,21 +1631,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
|
||||
lowLatency = SessionPrefs.lowLatency(this)
|
||||
padType = SessionPrefs.steamController(this)
|
||||
}
|
||||
|
||||
|
||||
private var localInstalling = false
|
||||
private val installingRuntime get() = localInstalling || SessionState.installing != null
|
||||
@Volatile private var installingRuntime = false
|
||||
private var repairOffered by mutableStateOf(false)
|
||||
|
||||
private fun installThenStart(runtime: Boolean, desktop: Boolean, proton: Boolean = false, resume: Boolean = false) {
|
||||
if (SessionState.stopRequested) return
|
||||
val worker = Any()
|
||||
activeInstallWorker = worker
|
||||
localInstalling = true
|
||||
installingRuntime = true
|
||||
SessionState.installing = if (runtime) "runtime" else if (resume) "package" else if (desktop) "desktop" else "proton"
|
||||
SessionEvents.transition(
|
||||
SessionPhase.INSTALLING_RUNTIME,
|
||||
@@ -1699,39 +1659,30 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (problem == null) SessionEvents.record("runtime.ready") else failedComponent = "runtime"
|
||||
}
|
||||
if (problem == null && resume && !SessionState.stopRequested) {
|
||||
if (activeInstallWorker === worker) SessionState.installing = "package"
|
||||
SessionState.installing = "package"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "package.resuming", mapOf("component" to "package"))
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
problem = try {
|
||||
com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, cancellation, progressAsIs())
|
||||
?.let { getString(R.string.session_package_resume_failed, it) }
|
||||
} finally {
|
||||
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||
}
|
||||
problem = com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, progressAsIs())
|
||||
?.let { getString(R.string.session_package_resume_failed, it) }
|
||||
if (problem == null) SessionEvents.record("package.ready") else failedComponent = "package"
|
||||
}
|
||||
if (problem == null && desktop && !SessionState.stopRequested) {
|
||||
if (activeInstallWorker === worker) SessionState.installing = "desktop"
|
||||
SessionState.installing = "desktop"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "desktop.installing", mapOf("component" to "desktop"))
|
||||
problem = installDesktop()
|
||||
if (problem == null) SessionEvents.record("desktop.ready") else failedComponent = "desktop"
|
||||
}
|
||||
if (problem == null && proton && !SessionState.stopRequested) {
|
||||
if (activeInstallWorker === worker) SessionState.installing = "proton"
|
||||
SessionState.installing = "proton"
|
||||
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "proton.installing", mapOf("component" to "proton"))
|
||||
val protonProblem = installProton()
|
||||
if (protonProblem == null) SessionEvents.record("proton.ready")
|
||||
else SessionEvents.record("proton.skipped", mapOf("reason" to protonProblem))
|
||||
}
|
||||
uiHandler.post {
|
||||
localInstalling = false
|
||||
if (activeInstallWorker === worker) {
|
||||
activeInstallWorker = null
|
||||
SessionState.installing = null
|
||||
}
|
||||
installingRuntime = false
|
||||
SessionState.installing = null
|
||||
if (SessionState.stopRequested) {
|
||||
if (activeInstallWorker == null) SessionState.stopRequested = false
|
||||
SessionState.stopRequested = false
|
||||
SessionEvents.transition(SessionPhase.IDLE, "session.cancelled")
|
||||
collectStartArtifacts("session start cancelled")
|
||||
finish()
|
||||
@@ -1809,29 +1760,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun installDesktop(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.say(getString(DESKTOP_LINES.downloading), DESKTOP_LINES.topic, readable = true) }
|
||||
val entry = com.droiddeck.launcher.runtime.DesktopCatalog.desktopEntry(this)
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
return try {
|
||||
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry, cancellation,
|
||||
progressFor(DESKTOP_LINES, entry.size / 1_000_000))
|
||||
problem?.let { getString(R.string.session_desktop_install_failed, it) }
|
||||
} finally {
|
||||
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||
}
|
||||
val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry,
|
||||
progressFor(DESKTOP_LINES, entry.size / 1_000_000))
|
||||
return problem?.let { getString(R.string.session_desktop_install_failed, it) }
|
||||
}
|
||||
|
||||
private fun installProton(): String? {
|
||||
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
|
||||
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
|
||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
return try {
|
||||
val entry = catalog.fetch(catalog.STEAM_SEED_URL, cancellation)?.firstOrNull { it.id == catalog.PROTON_SEED_ID }
|
||||
?: return if (cancellation.asBoolean) "cancelled" else "catalog unreachable"
|
||||
catalog.install(this, entry, cancellation, progressFor(PROTON_LINES, entry.size / 1_000_000))
|
||||
} finally {
|
||||
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||
}
|
||||
val entry = catalog.fetch(catalog.STEAM_SEED_URL)?.firstOrNull { it.id == catalog.PROTON_SEED_ID }
|
||||
?: return "catalog unreachable"
|
||||
return catalog.install(this, entry, progressFor(PROTON_LINES, entry.size / 1_000_000))
|
||||
}
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
@@ -2044,7 +1983,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private fun mirrorRefreshLimit(): Int =
|
||||
GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null)
|
||||
|
||||
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(mirrorRefreshLimit())
|
||||
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit(
|
||||
mirrorRefreshLimit(), SessionState.performanceMode,
|
||||
)
|
||||
|
||||
private fun applyOutputPacing() {
|
||||
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit()))
|
||||
@@ -2171,7 +2112,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun releasePads() {
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
|
||||
backQamInput.cancel()
|
||||
padBridge?.releaseAll()
|
||||
joyConVr?.releaseButtons()
|
||||
@@ -2230,17 +2170,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (line.contains(FEX_MISSING)) fexMissing = true
|
||||
}
|
||||
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
|
||||
val launchFailure = com.droiddeck.launcher.session.SessionLaunchFailure.find(text.lineSequence())
|
||||
if (steamSetup != null) {
|
||||
val message = getString(if (steamSetup.download) R.string.session_end_steam_download else R.string.session_end_steam_setup)
|
||||
EndHint(listOfNotNull(message, steamSetup.curlError).joinToString("\n"))
|
||||
} else if (launchFailure == com.droiddeck.launcher.session.SessionLaunchFailure.STEAM_ILLEGAL_INSTRUCTION) {
|
||||
val message = getString(R.string.session_end_steam_sigill)
|
||||
val fallback = if (SessionState.steamClientArch == "arm64") getString(R.string.session_end_steam_try_x64) else null
|
||||
EndHint(listOfNotNull(message, fallback).joinToString("\n"))
|
||||
} else if (launchFailure == com.droiddeck.launcher.session.SessionLaunchFailure.VULKAN_DEVICE_MISSING) {
|
||||
val adreno = com.droiddeck.launcher.gpu.GpuInfo.detect().family != com.droiddeck.launcher.gpu.GpuInfo.Family.NOT_ADRENO
|
||||
EndHint(getString(if (adreno) R.string.session_end_vulkan_device else R.string.session_end_gpu_unsupported))
|
||||
} else if (fexMissing) {
|
||||
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
|
||||
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
|
||||
@@ -2256,20 +2188,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
|
||||
val steamVolume =
|
||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
|
||||
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
|
||||
!pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
|
||||
!gestureSettingsOpen && !screenKeyTextFocus && window.decorView.hasWindowFocus()
|
||||
if (steamVolume) {
|
||||
val audio = getSystemService(android.media.AudioManager::class.java)
|
||||
if (com.droiddeck.launcher.input.SteamVolumeKeys.dispatch(event, !audio.isVolumeFixed) { direction ->
|
||||
audio.adjustStreamVolume(android.media.AudioManager.STREAM_MUSIC, direction, 0)
|
||||
}) return true
|
||||
}
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE ->
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
}
|
||||
val backToQam = !pipUi && !screenKeyTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
|
||||
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
|
||||
@@ -2336,7 +2256,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
return true
|
||||
}
|
||||
val resumeKey = event.keyCode == KeyEvent.KEYCODE_BUTTON_A || event.keyCode == KeyEvent.KEYCODE_BUTTON_START ||
|
||||
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || HomeGuideInput.isHome(event.keyCode)
|
||||
event.keyCode == KeyEvent.KEYCODE_BUTTON_MODE || event.keyCode == KeyEvent.KEYCODE_HOME
|
||||
val resumeKeyId = event.deviceId to event.keyCode
|
||||
if (fromController && resumeKey && (SessionState.suspended || resumeKeyId in resumeKeysDown)) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
@@ -2407,7 +2327,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (pipUi) return true
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
|
||||
drawerControllerActive = false
|
||||
gestureTouchStreamGate.reset()
|
||||
}
|
||||
return super.dispatchTouchEvent(event)
|
||||
}
|
||||
@@ -3058,11 +2977,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
uiHandler.postDelayed({ updateOnScreenControls() }, 700)
|
||||
}
|
||||
view.onStyle = { screenKeys?.refreshAppearance() }
|
||||
view.onTouchMiss = miss@{ event ->
|
||||
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
|
||||
event.offsetLocation(view.left - surfaceView.left.toFloat(), view.top - surfaceView.top.toFloat())
|
||||
onTouchEvent(event)
|
||||
}
|
||||
root.addView(view, root.indexOfChild(onScreenControls) + 1)
|
||||
steamTouchControls = view
|
||||
steamTouchAvailable = true
|
||||
@@ -3152,10 +3066,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
// The frozen game cannot draw again, so the paused overlay shows a copy taken while the surface still holds its frame.
|
||||
private fun capturePausedFrame(manual: Boolean = false) {
|
||||
private fun capturePausedFrame() {
|
||||
if (!SessionState.running || pipUi || isInPictureInPictureMode || glassesOutputActive) return
|
||||
if (SessionState.suspended && pausedFrame != null) return
|
||||
if ((suspendPolicy == SessionPrefs.SUSPEND_NEVER && !manual && !SessionState.manualPause) || !::surfaceView.isInitialized) return
|
||||
if (suspendPolicy == SessionPrefs.SUSPEND_NEVER || !::surfaceView.isInitialized) return
|
||||
if (surfaceView.holder.surface?.isValid != true) return
|
||||
val width = surfaceView.width
|
||||
val height = surfaceView.height
|
||||
@@ -3187,15 +3101,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
private fun pauseNow() {
|
||||
if (!SessionState.running || SessionState.suspended) return
|
||||
pauseAnimated = true
|
||||
drawerOpen = false
|
||||
pausedFrame = null
|
||||
capturePausedFrame(manual = true)
|
||||
SessionService.pause(this)
|
||||
}
|
||||
|
||||
// Sessions that froze from picture-in-picture, or before onPause could copy a frame, have none; the
|
||||
// compositor shows the frozen frame again once its output is back, so copy it from there.
|
||||
private fun requestPausedFrame() {
|
||||
@@ -3282,9 +3187,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
started = true
|
||||
refreshActivityDisplayId()
|
||||
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
|
||||
for (name in arrayOf("peak_refresh_rate", "min_refresh_rate")) {
|
||||
contentResolver.registerContentObserver(android.provider.Settings.System.getUriFor(name), false, refreshSettingObserver)
|
||||
}
|
||||
refreshSecondScreenDisplays()
|
||||
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
startedScreens++
|
||||
@@ -3299,7 +3201,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
started = false
|
||||
updateHandCamera()
|
||||
displayManager.unregisterDisplayListener(displayListener)
|
||||
contentResolver.unregisterContentObserver(refreshSettingObserver)
|
||||
closeSecondScreen(reset = false)
|
||||
startedScreens = (startedScreens - 1).coerceAtLeast(0)
|
||||
updateGlassesScreen()
|
||||
@@ -3355,15 +3256,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onScreenControls?.reload()
|
||||
controllerSettings = ControllerPrefs.read(this)
|
||||
resumed = true
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this,
|
||||
enabled = {
|
||||
resumed && window.decorView.hasWindowFocus() && !ended && !drawerOpen && !pcKeyboardOpen &&
|
||||
!achievementsOpen && !gestureSettingsOpen && !pipUi && SessionState.running && !SessionState.suspended &&
|
||||
SessionState.mode == SessionService.MODE_STEAM && padBridge != null
|
||||
},
|
||||
setPressed = { padBridge?.setHomeGuidePressed(it) },
|
||||
onCancel = { padBridge?.cancelHomeGuide() },
|
||||
)
|
||||
updatePointerCapture()
|
||||
if (!pipUi) sessionClipboard.start()
|
||||
updatePadMotion()
|
||||
@@ -3375,7 +3267,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
|
||||
if (runtimeRemovalBlocked) { super.onPause(); return }
|
||||
backQamInput.cancel()
|
||||
capturePausedFrame()
|
||||
@@ -3761,7 +3652,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (!hasFocus) com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
|
||||
if (!hasFocus) backQamInput.cancel()
|
||||
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
|
||||
if (runtimeRemovalBlocked) return
|
||||
@@ -3810,7 +3700,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
|
||||
backQamInput.cancel()
|
||||
steamVrRecovery.close()
|
||||
uiHandler.removeCallbacks(steamTouchRetry)
|
||||
@@ -3907,7 +3796,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private const val PAUSED_FRAME_REDRAW_MS = 150L
|
||||
private const val TAG = "SessionActivity"
|
||||
private var startedScreens = 0
|
||||
@Volatile private var activeInstallWorker: Any? = null
|
||||
private const val FEX_MISSING = "droiddeck-fex: x86 Linux programs need"
|
||||
private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION
|
||||
private const val CURSOR_PAD_HOLD_MS = 1200L
|
||||
|
||||
@@ -29,11 +29,6 @@ import java.util.Locale
|
||||
object DeviceReport {
|
||||
private const val TAG = "DeviceReport"
|
||||
|
||||
internal fun cpuFeaturesSummary(cpuInfo: String): String = cpuInfo.lineSequence()
|
||||
.filter { it.substringBefore(':').trim() == "Features" }
|
||||
.map { it.substringAfter(':').trim().split(Regex("\\s+")).filter(String::isNotEmpty).joinToString(" ") }
|
||||
.filter(String::isNotEmpty).distinct().joinToString(" | ").ifEmpty { "not reported" }
|
||||
|
||||
fun write(context: Context, target: File, mode: String) {
|
||||
try {
|
||||
target.writeText(build(context, mode))
|
||||
@@ -146,7 +141,6 @@ object DeviceReport {
|
||||
|
||||
h("CPU and memory")
|
||||
k("Cores", CpuCores.all.size)
|
||||
k("CPU features", cpuFeaturesSummary(FileUtils.readString(File("/proc/cpuinfo")).orEmpty()))
|
||||
b.append("Core ceilings ")
|
||||
b.append(CpuCores.all.joinToString(", ") { c ->
|
||||
"cpu$c " + (CpuCores.maxGhz(c)?.let { String.format(Locale.US, "%.2f GHz", it) } ?: "?")
|
||||
|
||||
@@ -16,83 +16,20 @@ import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public final class Downloader {
|
||||
private static final String TAG = "Downloader";
|
||||
private static final int CONNECT_TIMEOUT_MS = 10_000;
|
||||
private static final int STALL_TIMEOUT_MS = 15_000;
|
||||
private static final int HTTP_RANGE_NOT_SATISFIABLE = 416;
|
||||
private static final java.util.concurrent.ExecutorService CANCEL_EXECUTOR =
|
||||
java.util.concurrent.Executors.newCachedThreadPool(r -> {
|
||||
Thread thread = new Thread(r, "download-cancel");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
private Downloader() {}
|
||||
|
||||
public static final class Cancellation implements java.util.function.BooleanSupplier {
|
||||
private final AtomicBoolean cancelled = new AtomicBoolean();
|
||||
private final AtomicReference<HttpURLConnection> connection = new AtomicReference<>();
|
||||
private final AtomicReference<InputStream> input = new AtomicReference<>();
|
||||
private final java.util.function.BooleanSupplier external;
|
||||
|
||||
public Cancellation() { this(null); }
|
||||
public Cancellation(java.util.function.BooleanSupplier external) { this.external = external; }
|
||||
|
||||
public void cancel() {
|
||||
cancelled.set(true);
|
||||
HttpURLConnection active = connection.get();
|
||||
if (active != null) disconnectAsync(active);
|
||||
InputStream activeInput = input.get();
|
||||
if (activeInput != null) closeAsync(activeInput);
|
||||
}
|
||||
|
||||
private static void disconnectAsync(HttpURLConnection active) {
|
||||
CANCEL_EXECUTOR.execute(() -> {
|
||||
try { active.disconnect(); } catch (RuntimeException ignored) { }
|
||||
});
|
||||
}
|
||||
|
||||
private static void closeAsync(InputStream active) {
|
||||
CANCEL_EXECUTOR.execute(() -> {
|
||||
try { active.close(); } catch (IOException ignored) { }
|
||||
});
|
||||
}
|
||||
|
||||
@Override public boolean getAsBoolean() {
|
||||
return cancelled.get() || (external != null && external.getAsBoolean());
|
||||
}
|
||||
|
||||
private void attach(HttpURLConnection active) {
|
||||
connection.set(active);
|
||||
if (getAsBoolean()) disconnectAsync(active);
|
||||
}
|
||||
|
||||
private void detach(HttpURLConnection active) { connection.compareAndSet(active, null); }
|
||||
|
||||
private void attach(InputStream active) {
|
||||
input.set(active);
|
||||
if (getAsBoolean()) closeAsync(active);
|
||||
}
|
||||
|
||||
private void detach(InputStream active) { input.compareAndSet(active, null); }
|
||||
}
|
||||
|
||||
public static String downloadString(String url) {
|
||||
return downloadString(url, null);
|
||||
}
|
||||
|
||||
public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) {
|
||||
List<String> sources = DownloadSource.INSTANCE.candidates(url);
|
||||
for (int i = 0; i < sources.size(); i++) {
|
||||
if (isCancelled(cancelled)) return null;
|
||||
if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i));
|
||||
Fetch fetch = fetch(sources.get(i), cancelled);
|
||||
// A cancelled fetch says nothing about the source, so it must not count as a failure.
|
||||
if (isCancelled(cancelled)) return null;
|
||||
Fetch fetch = fetch(sources.get(i));
|
||||
if (fetch.body != null) {
|
||||
DownloadSource.INSTANCE.succeeded(sources.get(i));
|
||||
return fetch.body;
|
||||
@@ -116,52 +53,30 @@ public final class Downloader {
|
||||
/** Verify each candidate before accepting it, so a bad mirror can fall back. */
|
||||
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
return downloadFile(url, destination, resume, expectedSha256, null, progress);
|
||||
}
|
||||
|
||||
/** {@code cancelled} is polled while bytes arrive; a cancel stops at once and leaves the partial file for the caller. */
|
||||
public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256,
|
||||
java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}"))
|
||||
throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters");
|
||||
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, cancelled, progress);
|
||||
return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, progress);
|
||||
}
|
||||
|
||||
/** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */
|
||||
static List<String> sources(String url, String expectedSha256) {
|
||||
return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url);
|
||||
|
||||
}
|
||||
|
||||
// Package-private for the local multi-source HTTP test.
|
||||
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
|
||||
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
||||
return downloadCandidates(original, sources, destination, resume, expectedSha256, null, progress);
|
||||
}
|
||||
|
||||
static boolean downloadCandidates(String original, List<String> sources, File destination, boolean resume,
|
||||
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
Identity identity = loadIdentity(destination, resume, expectedSha256);
|
||||
for (int i = 0; i < sources.size(); i++) {
|
||||
String source = sources.get(i);
|
||||
if (isCancelled(cancelled)) return false;
|
||||
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
|
||||
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, cancelled, progress);
|
||||
// A cancel is not a source failure: no other mirror, and no DownloadSource.failed().
|
||||
if (outcome == Outcome.CANCELLED) return false;
|
||||
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, progress);
|
||||
if (outcome == Outcome.DONE) {
|
||||
if (expectedSha256 != null) {
|
||||
String actualSha256 = Hashes.sha256(destination);
|
||||
if (isCancelled(cancelled)) return false;
|
||||
if (!expectedSha256.equalsIgnoreCase(actualSha256)) {
|
||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||
if (!discardPartial(destination, identity)) return false;
|
||||
continue;
|
||||
}
|
||||
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) {
|
||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||
if (!discardPartial(destination, identity)) return false;
|
||||
continue;
|
||||
}
|
||||
if (isCancelled(cancelled)) return false;
|
||||
resumeFile(destination).delete();
|
||||
DownloadSource.INSTANCE.succeeded(source);
|
||||
if (progress != null) progress.accept(1f);
|
||||
@@ -173,11 +88,7 @@ public final class Downloader {
|
||||
return false;
|
||||
}
|
||||
|
||||
private enum Outcome { DONE, RETRY, FATAL, CANCELLED }
|
||||
|
||||
private static boolean isCancelled(java.util.function.BooleanSupplier cancelled) {
|
||||
return cancelled != null && cancelled.getAsBoolean();
|
||||
}
|
||||
private enum Outcome { DONE, RETRY, FATAL }
|
||||
|
||||
private static final class Identity {
|
||||
private String source;
|
||||
@@ -245,9 +156,7 @@ public final class Downloader {
|
||||
}
|
||||
|
||||
private static Outcome attempt(String url, File destination, boolean resume, Identity identity,
|
||||
String expectedSha256, java.util.function.BooleanSupplier cancelled,
|
||||
java.util.function.Consumer<Float> progress) {
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
||||
HttpURLConnection connection = null;
|
||||
long have = resume && destination.isFile() ? destination.length() : 0;
|
||||
try {
|
||||
@@ -257,7 +166,6 @@ public final class Downloader {
|
||||
have = 0;
|
||||
}
|
||||
connection = open(url, STALL_TIMEOUT_MS);
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(connection);
|
||||
if (have > 0) {
|
||||
connection.setRequestProperty("Range", "bytes=" + have + "-");
|
||||
connection.setRequestProperty("If-Range", identity.etag);
|
||||
@@ -266,7 +174,7 @@ public final class Downloader {
|
||||
if (have > 0 && code == HTTP_RANGE_NOT_SATISFIABLE) {
|
||||
connection.disconnect();
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||
}
|
||||
if (code / 100 != 2) {
|
||||
Log.w(TAG, url + " -> HTTP " + code);
|
||||
@@ -277,13 +185,13 @@ public final class Downloader {
|
||||
if (appending && !rangeStartsAt(connection.getHeaderField("Content-Range"), have)) {
|
||||
connection.disconnect();
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||
}
|
||||
String etag = connection.getHeaderField("ETag");
|
||||
if (have > 0 && appending && (!strongETag(etag) || !etag.equals(identity.etag))) {
|
||||
connection.disconnect();
|
||||
if (!discardPartial(destination, identity)) return Outcome.RETRY;
|
||||
return attempt(url, destination, false, identity, expectedSha256, cancelled, progress);
|
||||
return attempt(url, destination, false, identity, expectedSha256, progress);
|
||||
}
|
||||
if (!appending && have > 0) {
|
||||
// If-Range may legitimately return full 200 when representation changed.
|
||||
@@ -300,36 +208,26 @@ public final class Downloader {
|
||||
identity.etag = strongETag(etag) ? etag : null;
|
||||
saveIdentity(destination, identity, expectedSha256);
|
||||
long written = have;
|
||||
InputStream input = connection.getInputStream();
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(input);
|
||||
try (InputStream in = new BufferedInputStream(input, 1 << 16);
|
||||
try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16);
|
||||
OutputStream out = new FileOutputStream(destination, appending)) {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
long lastReport = 0;
|
||||
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) {
|
||||
out.write(buffer, 0, read);
|
||||
written += read;
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
if (progress != null && written - lastReport > (1 << 20)) {
|
||||
lastReport = written;
|
||||
progress.accept(total > 0 ? written / (float) total : -1f);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input);
|
||||
}
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
if (total > 0 && written < total) return Outcome.RETRY;
|
||||
return Outcome.DONE;
|
||||
} catch (Exception e) {
|
||||
if (isCancelled(cancelled)) return Outcome.CANCELLED;
|
||||
Log.w(TAG, "download " + url, e);
|
||||
return Outcome.RETRY;
|
||||
} finally {
|
||||
if (connection != null) {
|
||||
if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(connection);
|
||||
connection.disconnect();
|
||||
}
|
||||
if (connection != null) connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,15 +256,9 @@ public final class Downloader {
|
||||
}
|
||||
|
||||
private static Fetch fetch(String url) {
|
||||
return fetch(url, null);
|
||||
}
|
||||
|
||||
private static Fetch fetch(String url, java.util.function.BooleanSupplier cancelled) {
|
||||
HttpURLConnection connection = null;
|
||||
Cancellation token = cancelled instanceof Cancellation ? (Cancellation) cancelled : null;
|
||||
try {
|
||||
connection = open(url, STALL_TIMEOUT_MS);
|
||||
if (token != null) token.attach(connection);
|
||||
int code = connection.getResponseCode();
|
||||
if (code / 100 != 2) {
|
||||
Log.w(TAG, url + " -> HTTP " + code);
|
||||
@@ -378,14 +270,10 @@ public final class Downloader {
|
||||
return new Fetch(new String(out.toByteArray(), StandardCharsets.UTF_8), false);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (isCancelled(cancelled)) return new Fetch(null, false);
|
||||
Log.w(TAG, "GET " + url, e);
|
||||
return new Fetch(null, false);
|
||||
} finally {
|
||||
if (connection != null) {
|
||||
if (token != null) token.detach(connection);
|
||||
connection.disconnect();
|
||||
}
|
||||
if (connection != null) connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
|
||||
object GlobalSettings {
|
||||
// Settings.Global caches values in-process and misses deletions made over adb; ask the provider directly.
|
||||
fun read(context: Context, name: String): String? {
|
||||
val uri = Uri.withAppendedPath(Settings.Global.CONTENT_URI, name)
|
||||
context.contentResolver.query(uri, arrayOf(Settings.NameValueTable.VALUE), null, null, null)?.use { cursor ->
|
||||
return if (cursor.moveToFirst()) cursor.getString(0) else null
|
||||
}
|
||||
return Settings.Global.getString(context.contentResolver, name)
|
||||
}
|
||||
|
||||
fun isOn(context: Context, name: String): Boolean =
|
||||
runCatching { read(context, name)?.trim() == "1" }.getOrDefault(false)
|
||||
|
||||
fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED)
|
||||
|
||||
// Settings.Global.ADB_WIFI_ENABLED is hidden; the key is stable since Android 11.
|
||||
fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled")
|
||||
}
|
||||
@@ -1,59 +1,21 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
object LogRedactor {
|
||||
internal const val MAX_LINE_LENGTH = 64 * 1024
|
||||
internal const val OVERSIZED_LINE = "<oversized log line withheld>"
|
||||
|
||||
private data class MatcherKey(val pattern: String, val options: Set<RegexOption>)
|
||||
|
||||
private class MatcherCache : LinkedHashMap<MatcherKey, java.util.regex.Matcher>(32, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<MatcherKey, java.util.regex.Matcher>?): Boolean =
|
||||
size > 32
|
||||
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
|
||||
private val HIDL_SHARED_LIBRARY = Regex(
|
||||
"(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" +
|
||||
"(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so"
|
||||
)
|
||||
private val hidlMatcher = object : ThreadLocal<java.util.regex.Matcher>() {
|
||||
override fun initialValue(): java.util.regex.Matcher = HIDL_SHARED_LIBRARY.toPattern().matcher("")
|
||||
}
|
||||
|
||||
// Android matchers own native state, so reuse them instead of creating one for every log line.
|
||||
private val matchers = object : ThreadLocal<MatcherCache>() {
|
||||
override fun initialValue(): MatcherCache = MatcherCache()
|
||||
}
|
||||
|
||||
private fun <T> withMatcher(
|
||||
regex: Regex,
|
||||
input: CharSequence,
|
||||
action: (java.util.regex.Matcher) -> T,
|
||||
): T {
|
||||
val key = MatcherKey(regex.pattern, regex.options)
|
||||
val matcher = matchers.get()!!.getOrPut(key) { regex.toPattern().matcher("") }
|
||||
return try {
|
||||
action(matcher.reset(input))
|
||||
} finally {
|
||||
matcher.reset("")
|
||||
}
|
||||
}
|
||||
|
||||
private fun replaceMatches(input: String, regex: Regex, replacement: String): String =
|
||||
replaceMatches(input, regex) { replacement }
|
||||
|
||||
private fun replaceMatches(
|
||||
input: String,
|
||||
regex: Regex,
|
||||
replacement: (java.util.regex.Matcher) -> String,
|
||||
): String = withMatcher(regex, input) { matcher ->
|
||||
if (!matcher.find()) return@withMatcher input
|
||||
val out = StringBuffer(input.length)
|
||||
do {
|
||||
matcher.appendReplacement(out, java.util.regex.Matcher.quoteReplacement(replacement(matcher)))
|
||||
} while (matcher.find())
|
||||
matcher.appendTail(out)
|
||||
out.toString()
|
||||
}
|
||||
|
||||
private fun matchesEntire(input: String, regex: Regex): Boolean =
|
||||
withMatcher(regex, input) { it.matches() }
|
||||
|
||||
private fun isHidlLoaderDiagnostic(input: String, match: java.util.regex.Matcher): Boolean {
|
||||
if (!matchesEntire(match.group(), HIDL_SHARED_LIBRARY)) return false
|
||||
val start = match.start()
|
||||
val end = match.end()
|
||||
private fun isHidlLoaderDiagnostic(input: String, match: MatchResult): Boolean {
|
||||
val matcher = hidlMatcher.get()!!
|
||||
val isLibrary = try { matcher.reset(match.value).matches() } finally { matcher.reset("") }
|
||||
if (!isLibrary) return false
|
||||
val start = match.range.first
|
||||
val end = match.range.last + 1
|
||||
val prefix = "library \""
|
||||
val suffix = "\" not found"
|
||||
val earliestQuote = (start - 4096).coerceAtLeast(0)
|
||||
@@ -77,12 +39,6 @@ object LogRedactor {
|
||||
(suffixEnd == input.length || !(input[suffixEnd].isLetterOrDigit() || input[suffixEnd] == '_'))
|
||||
}
|
||||
|
||||
private val EMAIL = Regex("[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}")
|
||||
private val HIDL_SHARED_LIBRARY = Regex(
|
||||
"(?:android\\.(?:hardware|frameworks|hidl|system)|vendor\\.[A-Za-z0-9_]+\\.hardware)" +
|
||||
"(?:\\.[A-Za-z0-9_]+)+@[0-9]+\\.[0-9]+(?:-[A-Za-z0-9_]+)*\\.so"
|
||||
)
|
||||
|
||||
private val JWT_LABELLED = Regex("(?i)(\\bJWT[\\s=:]+)(\\d{8,})")
|
||||
private val JWT_BASE64 = Regex("ey[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}\\.[A-Za-z0-9_\\-]{6,}")
|
||||
private val GUID = Regex("\\b[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\\b")
|
||||
@@ -155,7 +111,6 @@ object LogRedactor {
|
||||
java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"),
|
||||
java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"),
|
||||
)
|
||||
matchers.remove()
|
||||
}
|
||||
|
||||
@Volatile
|
||||
@@ -223,8 +178,8 @@ object LogRedactor {
|
||||
}
|
||||
|
||||
fun describeAddresses(text: String): String {
|
||||
var out = replaceMatches(text, IPV6) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() }
|
||||
out = replaceMatches(out, IPV4) { m -> kind(m.group())?.let { "<$it>" } ?: m.group() }
|
||||
var out = IPV6.replace(text) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
|
||||
out = IPV4.replace(out) { m -> kind(m.value)?.let { "<$it>" } ?: m.value }
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -249,28 +204,23 @@ object LogRedactor {
|
||||
"(?<![\\d.])(?:10\\.\\d{1,3}|192\\.168|172\\.(?:1[6-9]|2\\d|3[01])|169\\.254)\\.\\d{1,3}\\.\\d{1,3}(?!\\.?\\d)"
|
||||
)
|
||||
|
||||
fun scrubTo(
|
||||
src: java.io.File,
|
||||
out: java.io.Writer,
|
||||
shouldStop: () -> Boolean = { false },
|
||||
): Boolean = scrubLines(src, out, ::redact, shouldStop)
|
||||
fun scrubTo(src: java.io.File, out: java.io.Writer) {
|
||||
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
|
||||
}
|
||||
|
||||
fun redactForShare(line: String): String {
|
||||
if (line.isEmpty()) return line
|
||||
if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE
|
||||
return try {
|
||||
val out = SecretScrub.scrub(redact(line), SecretScrub.Urls.KEEP_PATH, "<redacted:token>")
|
||||
replaceMatches(out, LAN_IPV4, "<lan-address>")
|
||||
LAN_IPV4.replace(out, "<lan-address>")
|
||||
} catch (t: Throwable) {
|
||||
"<redaction failed; line withheld>"
|
||||
}
|
||||
}
|
||||
|
||||
fun scrubForShare(
|
||||
src: java.io.File,
|
||||
out: java.io.Writer,
|
||||
shouldStop: () -> Boolean = { false },
|
||||
): Boolean {
|
||||
private const val SHARE_LINE_MAX = 64 * 1024
|
||||
|
||||
fun scrubForShare(src: java.io.File, out: java.io.Writer) {
|
||||
src.inputStream().buffered().use { input ->
|
||||
input.mark(2)
|
||||
val first = input.read()
|
||||
@@ -278,30 +228,27 @@ object LogRedactor {
|
||||
input.reset()
|
||||
if ((first == 0xff && second == 0xfe) || (first == 0xfe && second == 0xff)) {
|
||||
out.write("<unsupported encoding; file withheld>\n")
|
||||
return true
|
||||
return
|
||||
}
|
||||
val decoder = Charsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
|
||||
java.io.InputStreamReader(input, decoder).use { reader ->
|
||||
val buffer = CharArray(8192)
|
||||
val line = StringBuilder(4096)
|
||||
var withheld: String? = null
|
||||
val line = StringBuilder()
|
||||
var withheld = false
|
||||
var afterCr = false
|
||||
fun emit() {
|
||||
out.write(withheld ?: redactForShare(line.toString()))
|
||||
out.write(if (withheld) "<unsupported or oversized line withheld>" else redactForShare(line.toString()))
|
||||
out.write("\n")
|
||||
line.setLength(0)
|
||||
withheld = null
|
||||
withheld = false
|
||||
}
|
||||
try {
|
||||
while (true) {
|
||||
if (shouldStop()) return false
|
||||
val size = reader.read(buffer)
|
||||
if (size < 0) break
|
||||
if (shouldStop()) return false
|
||||
for (i in 0 until size) {
|
||||
if (shouldStop()) return false
|
||||
val ch = buffer[i]
|
||||
if (afterCr) {
|
||||
afterCr = false
|
||||
@@ -310,79 +257,23 @@ object LogRedactor {
|
||||
if (ch == '\r' || ch == '\n') {
|
||||
emit()
|
||||
afterCr = ch == '\r'
|
||||
} else if (withheld == null) {
|
||||
if (ch == '\u0000' || line.length == MAX_LINE_LENGTH) {
|
||||
withheld = if (ch == '\u0000') "<unsupported or oversized line withheld>" else OVERSIZED_LINE
|
||||
} else if (!withheld) {
|
||||
// Splitting a line can separate a credential from its label.
|
||||
if (ch == '\u0000' || line.length == SHARE_LINE_MAX) {
|
||||
withheld = true
|
||||
line.setLength(0)
|
||||
} else line.append(ch)
|
||||
} else {
|
||||
line.append(ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (withheld != null || line.isNotEmpty()) emit()
|
||||
if (withheld || line.isNotEmpty()) emit()
|
||||
} catch (_: java.nio.charset.CharacterCodingException) {
|
||||
out.write("<unsupported encoding; file withheld>\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
private fun scrubLines(
|
||||
src: java.io.File,
|
||||
out: java.io.Writer,
|
||||
scrub: (String) -> String,
|
||||
shouldStop: () -> Boolean,
|
||||
): Boolean {
|
||||
src.bufferedReader().use { input ->
|
||||
val chunk = CharArray(8192)
|
||||
val line = StringBuilder(4096)
|
||||
var oversized = false
|
||||
var pendingContent = false
|
||||
var pendingCarriageReturn = false
|
||||
|
||||
fun emit() {
|
||||
out.write(if (oversized) OVERSIZED_LINE else scrub(line.toString()))
|
||||
out.write("\n")
|
||||
line.setLength(0)
|
||||
oversized = false
|
||||
pendingContent = false
|
||||
}
|
||||
|
||||
while (true) {
|
||||
if (shouldStop()) return false
|
||||
val count = input.read(chunk)
|
||||
if (count < 0) break
|
||||
if (shouldStop()) return false
|
||||
for (i in 0 until count) {
|
||||
val char = chunk[i]
|
||||
if (pendingCarriageReturn) {
|
||||
emit()
|
||||
pendingCarriageReturn = false
|
||||
if (char == '\n') continue
|
||||
}
|
||||
when (char) {
|
||||
'\r' -> pendingCarriageReturn = true
|
||||
'\n' -> emit()
|
||||
else -> {
|
||||
pendingContent = true
|
||||
if (!oversized) {
|
||||
if (line.length < MAX_LINE_LENGTH) line.append(char)
|
||||
else {
|
||||
line.setLength(0)
|
||||
oversized = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pendingCarriageReturn || pendingContent) {
|
||||
if (shouldStop()) return false
|
||||
emit()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun quoted(value: String): String {
|
||||
@@ -424,51 +315,45 @@ object LogRedactor {
|
||||
|
||||
fun redact(line: String): String {
|
||||
if (line.isEmpty()) return line
|
||||
if (line.length > MAX_LINE_LENGTH) return OVERSIZED_LINE
|
||||
return try {
|
||||
val out = Line(line)
|
||||
if (out.has("mac")) out.set(replaceMatches(out.text, MAC_FIELD) { "${it.group(1)}<redacted:mac>" })
|
||||
if (out.holds(':', 5) || out.holds('-', 5)) out.set(replaceMatches(out.text, MAC, "<redacted:mac>"))
|
||||
if (out.has("serial", "android")) out.set(replaceMatches(out.text, DEVICE_IDENTIFIER) {
|
||||
val value = it.group(2)
|
||||
if (out.has("mac")) out.set(MAC_FIELD.replace(out.text) { "${it.groupValues[1]}<redacted:mac>" })
|
||||
if (out.holds(':', 5) || out.holds('-', 5)) out.set(MAC.replace(out.text, "<redacted:mac>"))
|
||||
if (out.has("serial", "android")) out.set(DEVICE_IDENTIFIER.replace(out.text) {
|
||||
val value = it.groupValues[2]
|
||||
val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty()
|
||||
"${it.group(1)}${quote}<redacted:serial>${quote}"
|
||||
"${it.groupValues[1]}${quote}<redacted:serial>${quote}"
|
||||
})
|
||||
if (out.holds('-', 4)) out.set(replaceMatches(out.text, GUID, "<redacted:guid>"))
|
||||
if (out.has("jwt")) out.set(replaceMatches(out.text, JWT_LABELLED) { "${it.group(1)}<redacted:jwt>" })
|
||||
if ("ey" in out.text) out.set(replaceMatches(out.text, JWT_BASE64, "<redacted:jwt>"))
|
||||
if (out.holds('-', 4)) out.set(GUID.replace(out.text, "<redacted:guid>"))
|
||||
if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}<redacted:jwt>" })
|
||||
if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "<redacted:jwt>"))
|
||||
if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) {
|
||||
out.set(replaceMatches(out.text, SECRET_KV) {
|
||||
val quote = it.group(2).orEmpty()
|
||||
"${it.group(1)}${quote}<redacted:token>${quote}"
|
||||
})
|
||||
|
||||
out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>${it.groupValues[2]}" })
|
||||
}
|
||||
if (out.has("guard", "factor", "2fa")) out.set(replaceMatches(out.text, GUARD_CODE) { "${it.group(1)}<redacted:code>" })
|
||||
if (out.hasRun(32, ::isHex)) out.set(replaceMatches(out.text, WEBAPI_KEY, "<redacted:key>"))
|
||||
if ("76561" in out.text) out.set(replaceMatches(out.text, STEAMID64) { "${it.group(1)}********${it.group(3)}" })
|
||||
if ("[U:1:" in out.text) out.set(replaceMatches(out.text, STEAMID3) { m ->
|
||||
val id = m.group(1)
|
||||
if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}<redacted:code>" })
|
||||
if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "<redacted:key>"))
|
||||
if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" })
|
||||
if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m ->
|
||||
val id = m.groupValues[1]
|
||||
"[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]"
|
||||
})
|
||||
if (out.has("external")) out.set(replaceMatches(out.text, EXTERNAL_ADDR) { "${it.group(1)}<redacted:ip>" })
|
||||
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "<redacted:ip>"))
|
||||
if (out.has("onloginstatechange")) out.set(replaceMatches(out.text, LOGIN_STATE) { "${it.group(1)}<redacted:account>" })
|
||||
if ("OnLoginUsersChanged " in out.text) out.set(replaceMatches(out.text, LOGIN_USERS) { "${it.group(1)}<redacted:account>" })
|
||||
if (out.has("external")) out.set(EXTERNAL_ADDR.replace(out.text) { "${it.groupValues[1]}<redacted:ip>" })
|
||||
for (r in own) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:ip>"))
|
||||
if (out.has("onloginstatechange")) out.set(LOGIN_STATE.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
|
||||
if ("OnLoginUsersChanged " in out.text) out.set(LOGIN_USERS.replace(out.text) { "${it.groupValues[1]}<redacted:account>" })
|
||||
if (out.has("account", "user")) {
|
||||
out.set(replaceMatches(out.text, ACCOUNT_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" })
|
||||
out.set(ACCOUNT_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
|
||||
}
|
||||
if (out.has("login")) out.set(replaceMatches(out.text, LOGIN_KV) { "${it.group(1)}${it.group(2)}${quoted(it.group(3))}" })
|
||||
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(replaceMatches(out.text, r.regex, "<redacted:account>"))
|
||||
if ('@' in out.text) out.set(replaceMatches(out.text, EMAIL) { m ->
|
||||
m.group().takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "<redacted:email>"
|
||||
|
||||
if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" })
|
||||
for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "<redacted:account>"))
|
||||
if ('@' in out.text) out.set(EMAIL.replace(out.text) { m ->
|
||||
m.value.takeIf { isHidlLoaderDiagnostic(out.text, m) } ?: "<redacted:email>"
|
||||
})
|
||||
if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) {
|
||||
out.set(replaceMatches(out.text, RESIDUAL) { "${it.group(1)}=<redacted:token>" })
|
||||
out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=<redacted:token>" })
|
||||
}
|
||||
if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) {
|
||||
out.set(replaceMatches(out.text, LONG_TOKEN, "<redacted:token>"))
|
||||
out.set(LONG_TOKEN.replace(out.text, "<redacted:token>"))
|
||||
}
|
||||
out.text
|
||||
} catch (t: Throwable) {
|
||||
|
||||
@@ -60,14 +60,14 @@ object PhantomProcessLimit {
|
||||
if (usesDeviceConfig(sdk)) {
|
||||
val off = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(PREF_ANDROID_12_OFF, false)
|
||||
val global = try {
|
||||
GlobalSettings.read(context, SETTING)
|
||||
Settings.Global.getString(context.contentResolver, SETTING)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
return android12Status(off, global, systemProperty(OVERRIDE_PROPERTY))
|
||||
}
|
||||
val global = try {
|
||||
GlobalSettings.read(context, SETTING)
|
||||
Settings.Global.getString(context.contentResolver, SETTING)
|
||||
} catch (_: Exception) {
|
||||
return PhantomProcessStatus.UNREADABLE
|
||||
}
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.accessibilityservice.AccessibilityServiceInfo
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import android.view.accessibility.AccessibilityManager
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.input.HomeButtonService
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
object SteamIntegration {
|
||||
const val ACTION_SETUP = "com.droiddeck.launcher.STEAM_INTEGRATION"
|
||||
const val EXTRA_FEATURE = "integration_feature"
|
||||
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
|
||||
|
||||
data class State(
|
||||
val wifi: Boolean = false,
|
||||
val locationPermission: Boolean = false,
|
||||
val locationOn: Boolean = false,
|
||||
val locationBlocked: Boolean = false,
|
||||
val brightness: Boolean = false,
|
||||
val home: Boolean = false,
|
||||
val shortcuts: Boolean = false,
|
||||
val shortcutsRestricted: Boolean = false,
|
||||
val shortcutsTried: Boolean = false,
|
||||
val suggested: Boolean = true,
|
||||
)
|
||||
|
||||
fun read(context: Context) = State(
|
||||
wifi = SessionPrefs.wifiDiscoveryEnabled(context),
|
||||
locationPermission = WifiDiscovery.permissionGranted(context),
|
||||
locationOn = WifiDiscovery.locationEnabled(context),
|
||||
brightness = Settings.System.canWrite(context),
|
||||
home = HomeApp.isDefault(context),
|
||||
shortcuts = context.getSystemService(AccessibilityManager::class.java)
|
||||
.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK).any {
|
||||
val service = it.resolveInfo.serviceInfo
|
||||
ComponentName(service.packageName, service.name) == ComponentName(context, HomeButtonService::class.java)
|
||||
},
|
||||
shortcutsRestricted = restrictedSettings(context),
|
||||
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
|
||||
)
|
||||
|
||||
// Android 13+ blocks accessibility services for sideloaded APKs until the user allows restricted settings in App info.
|
||||
// MODE_DEFAULT is inconclusive on Android 15, so only an explicit denial counts here.
|
||||
private fun restrictedSettings(context: Context): Boolean {
|
||||
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
|
||||
val mode = runCatching {
|
||||
context.getSystemService(android.app.AppOpsManager::class.java)
|
||||
.unsafeCheckOpNoThrow("android:access_restricted_settings", android.os.Process.myUid(), context.packageName)
|
||||
}.getOrDefault(android.app.AppOpsManager.MODE_ALLOWED)
|
||||
return mode == android.app.AppOpsManager.MODE_ERRORED || mode == android.app.AppOpsManager.MODE_IGNORED
|
||||
}
|
||||
|
||||
fun dismissSuggestion(context: Context) {
|
||||
SessionPrefs.sessionPrefs(context).edit().putBoolean("steam_integration_seen", true).apply()
|
||||
}
|
||||
|
||||
fun brightnessSettings(context: Context) = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
|
||||
Uri.parse("package:${context.packageName}"))
|
||||
|
||||
// ACCESSIBILITY_DETAILS_SETTINGS is restricted to system apps; the fragment args key highlights our entry in the list.
|
||||
fun shortcutSettings(context: Context): Intent {
|
||||
val service = ComponentName(context, HomeButtonService::class.java).flattenToString()
|
||||
return Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
|
||||
.putExtra(":settings:fragment_args_key", service)
|
||||
.putExtra(":settings:show_fragment_args", android.os.Bundle().apply { putString(":settings:fragment_args_key", service) })
|
||||
}
|
||||
}
|
||||
@@ -184,15 +184,12 @@ class WirelessAdbPairingService : Service() {
|
||||
setSound(null, null)
|
||||
enableVibration(false)
|
||||
})
|
||||
manager?.createNotificationChannel(NotificationChannel(PROGRESS_CHANNEL_ID, getString(R.string.adbpair_progress_channel_name),
|
||||
NotificationManager.IMPORTANCE_LOW).apply { setShowBadge(false) })
|
||||
val open = PendingIntent.getActivity(this, 0,
|
||||
Intent(this, FrontEndActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
||||
PendingIntent.FLAG_IMMUTABLE)
|
||||
val cancel = PendingIntent.getService(this, 1,
|
||||
Intent(this, WirelessAdbPairingService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
|
||||
val quiet = stage == Stage.Waiting || stage == Stage.Idle || stage is Stage.Working
|
||||
val builder = Notification.Builder(this, if (quiet) PROGRESS_CHANNEL_ID else CHANNEL_ID)
|
||||
val builder = Notification.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentIntent(open)
|
||||
.setShowWhen(false)
|
||||
@@ -242,7 +239,6 @@ class WirelessAdbPairingService : Service() {
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "wireless-adb-pairing"
|
||||
private const val PROGRESS_CHANNEL_ID = "wireless-adb-pairing-progress"
|
||||
private const val NOTIFICATION_ID = 3
|
||||
private const val PAIRING_TYPE = "_adb-tls-pairing._tcp"
|
||||
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
|
||||
|
||||
@@ -22,7 +22,6 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
@@ -48,16 +47,10 @@ public final class TurnipDriver {
|
||||
|
||||
private final Context context;
|
||||
private final File contentDir;
|
||||
private final Supplier<GpuInfo> gpuDetector;
|
||||
|
||||
public TurnipDriver(Context context) {
|
||||
this(context, GpuInfo.Companion::detect);
|
||||
}
|
||||
|
||||
TurnipDriver(Context context, Supplier<GpuInfo> gpuDetector) {
|
||||
this.context = context;
|
||||
this.contentDir = new File(context.getFilesDir(), "graphics_driver");
|
||||
this.gpuDetector = gpuDetector;
|
||||
}
|
||||
|
||||
public String driverPath(String driverId) {
|
||||
@@ -291,12 +284,7 @@ public final class TurnipDriver {
|
||||
}
|
||||
String quest = QuestExperimental.INSTANCE.defaultAndroidDriver();
|
||||
if (quest != null) return quest;
|
||||
GpuInfo gpu = gpuDetector.get();
|
||||
if (gpu.getFamily() == GpuInfo.Family.NOT_ADRENO) {
|
||||
Log.i(TAG, "not an Adreno GPU; leaving the display driver to the system");
|
||||
return null;
|
||||
}
|
||||
int model = gpu.getModel();
|
||||
int model = GpuInfo.Companion.detect().getModel();
|
||||
Log.i(TAG, "gpu model: " + (model == 0 ? "unknown" : model));
|
||||
return chooseByModel(model, android.os.Build.VERSION.SDK_INT);
|
||||
}
|
||||
|
||||
@@ -4,8 +4,7 @@ import android.view.KeyEvent
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
|
||||
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit,
|
||||
private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {}) {
|
||||
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit) {
|
||||
private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false)
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val presses = mutableMapOf<Int, Press>()
|
||||
@@ -18,18 +17,6 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
|
||||
tapPending = false
|
||||
}
|
||||
|
||||
fun onChordInput() {
|
||||
if (presses.isEmpty()) return
|
||||
val alreadyHeld = presses.values.any { it.held }
|
||||
presses.values.forEach {
|
||||
handler.removeCallbacks(it.hold)
|
||||
it.held = true
|
||||
it.used = true
|
||||
}
|
||||
cancelTap()
|
||||
if (!alreadyHeld) setPressed(true)
|
||||
}
|
||||
|
||||
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
|
||||
if (!enabled) cancel()
|
||||
if (event.keyCode != KeyEvent.KEYCODE_BACK) return false
|
||||
@@ -61,7 +48,7 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
|
||||
if (press.held && presses.values.none { it.held }) setPressed(false)
|
||||
if (!press.used && !event.isCanceled) {
|
||||
if (tapPending) { cancelTap(); onTap(true) }
|
||||
else { tapPending = true; handler.postDelayed(singleTap, doubleTapMs()) }
|
||||
else { tapPending = true; handler.postDelayed(singleTap, 500) }
|
||||
} else if (event.isCanceled) cancelTap()
|
||||
}
|
||||
press != null || wasCancelled || enabled
|
||||
@@ -76,7 +63,6 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
|
||||
presses.values.forEach { handler.removeCallbacks(it.hold) }
|
||||
cancelled.addAll(presses.keys)
|
||||
presses.clear()
|
||||
onCancel()
|
||||
if (wasHeld) setPressed(false)
|
||||
}
|
||||
|
||||
@@ -85,9 +71,6 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
|
||||
val press = presses.remove(device) ?: return
|
||||
handler.removeCallbacks(press.hold)
|
||||
cancelTap()
|
||||
if (press.held && presses.values.none { it.held }) {
|
||||
onCancel()
|
||||
setPressed(false)
|
||||
}
|
||||
if (press.held && presses.values.none { it.held }) setPressed(false)
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import android.view.MotionEvent
|
||||
|
||||
/** Keeps split Android touch targets from restarting one shared gesture recognizer. */
|
||||
internal class GestureTouchStreamGate {
|
||||
enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS }
|
||||
enum class Source { SURFACE, SCREEN_KEYS }
|
||||
|
||||
private var owner: Source? = null
|
||||
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.hardware.input.InputManager
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.KeyEvent
|
||||
import android.view.accessibility.AccessibilityEvent
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
|
||||
object HomeButtonShortcuts {
|
||||
private var owner: Any? = null
|
||||
private var enabled: () -> Boolean = { false }
|
||||
private var setPressed: (Boolean) -> Unit = {}
|
||||
private var onCancel: () -> Unit = {}
|
||||
private val input = HomeGuideInput({ setPressed(it) }, { onCancel() })
|
||||
|
||||
fun attach(owner: Any, enabled: () -> Boolean, setPressed: (Boolean) -> Unit, onCancel: () -> Unit) {
|
||||
input.cancel()
|
||||
this.owner = owner
|
||||
this.enabled = enabled
|
||||
this.setPressed = setPressed
|
||||
this.onCancel = onCancel
|
||||
}
|
||||
|
||||
fun cancel(owner: Any) { if (this.owner === owner) input.cancel() }
|
||||
|
||||
fun detach(owner: Any) {
|
||||
if (this.owner !== owner) return
|
||||
input.cancel()
|
||||
this.owner = null
|
||||
enabled = { false }
|
||||
setPressed = {}
|
||||
onCancel = {}
|
||||
}
|
||||
|
||||
fun onKeyEvent(context: Context, event: KeyEvent): Boolean {
|
||||
// AYN maps its system-assistant key (gpio-keys KEY_F24) to HOME too; only the pad's Home is Guide.
|
||||
if (!HomeGuideInput.isHome(event.keyCode) || !PadBridge.isControllerKeyEvent(event)) return false
|
||||
return input.onKeyEvent(event, enabled() && HomeApp.isDefault(context))
|
||||
}
|
||||
|
||||
fun release() = input.cancel()
|
||||
fun onDeviceRemoved(device: Int) = input.onDeviceRemoved(device)
|
||||
}
|
||||
|
||||
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
|
||||
override fun onServiceConnected() {
|
||||
getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper()))
|
||||
}
|
||||
|
||||
override fun onKeyEvent(event: KeyEvent) = HomeButtonShortcuts.onKeyEvent(this, event)
|
||||
override fun onAccessibilityEvent(event: AccessibilityEvent?) {}
|
||||
override fun onInterrupt() { HomeButtonShortcuts.release() }
|
||||
override fun onInputDeviceAdded(deviceId: Int) {}
|
||||
override fun onInputDeviceChanged(deviceId: Int) {}
|
||||
override fun onInputDeviceRemoved(deviceId: Int) { HomeButtonShortcuts.onDeviceRemoved(deviceId) }
|
||||
|
||||
override fun onUnbind(intent: Intent?): Boolean {
|
||||
HomeButtonShortcuts.release()
|
||||
return super.onUnbind(intent)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
HomeButtonShortcuts.release()
|
||||
getSystemService(InputManager::class.java).unregisterInputDeviceListener(this)
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.KeyEvent
|
||||
|
||||
class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCancel: () -> Unit = {}) {
|
||||
private val presses = mutableSetOf<Int>()
|
||||
private val cancelled = mutableSetOf<Int>()
|
||||
|
||||
fun onKeyEvent(event: KeyEvent, enabled: Boolean): Boolean {
|
||||
if (!isHome(event.keyCode)) return false
|
||||
if (!enabled) cancel()
|
||||
val device = event.deviceId
|
||||
return when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> {
|
||||
if (event.repeatCount > 0) return device in presses || device in cancelled
|
||||
cancelled.remove(device)
|
||||
if (!enabled || event.isCanceled) return false
|
||||
if (presses.add(device) && presses.size == 1) setPressed(true)
|
||||
true
|
||||
}
|
||||
KeyEvent.ACTION_UP -> {
|
||||
val owned = presses.remove(device)
|
||||
val wasCancelled = cancelled.remove(device)
|
||||
if (owned && presses.isEmpty()) setPressed(false)
|
||||
owned || wasCancelled
|
||||
}
|
||||
else -> device in presses || device in cancelled
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
val held = presses.isNotEmpty()
|
||||
cancelled.addAll(presses)
|
||||
presses.clear()
|
||||
if (held) { onCancel(); setPressed(false) }
|
||||
}
|
||||
|
||||
fun onDeviceRemoved(device: Int) {
|
||||
cancelled.remove(device)
|
||||
if (presses.remove(device) && presses.isEmpty()) { onCancel(); setPressed(false) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
// The Retroid Nova pad falls back to Generic.kl, which maps its Home scan code to MOVE_HOME.
|
||||
fun isHome(keyCode: Int) = keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MOVE_HOME
|
||||
}
|
||||
}
|
||||
@@ -96,8 +96,6 @@ class OnScreenControls(
|
||||
private var quickHidden = false
|
||||
private var quickPressedBy = -1
|
||||
private var keyboardPressedBy = -1
|
||||
private var forwardedPointerBits = 0
|
||||
var onTouchMiss: ((MotionEvent) -> Unit)? = null
|
||||
private var settings = ControllerPrefs.read(context)
|
||||
private var snap = settings.snap
|
||||
private var safe = Rect()
|
||||
@@ -517,9 +515,6 @@ class OnScreenControls(
|
||||
val index = event.actionIndex
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0
|
||||
if (event.actionMasked == MotionEvent.ACTION_POINTER_DOWN && forwardMiss(event, x, y)) return true
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN && keyboardContains(x, y)) {
|
||||
keyboardPressedBy = event.getPointerId(index)
|
||||
invalidate()
|
||||
@@ -547,13 +542,11 @@ class OnScreenControls(
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
if (keyboardPressedBy != -1) return true
|
||||
if (quickPressedBy != -1) return true
|
||||
var changed = false
|
||||
for (index in 0 until event.pointerCount) {
|
||||
val pointer = event.getPointerId(index)
|
||||
if (forwardedPointerBits and (1 shl pointer) != 0) continue
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
|
||||
@@ -575,16 +568,10 @@ class OnScreenControls(
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
val pointer = event.getPointerId(event.actionIndex)
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
if (event.actionMasked == MotionEvent.ACTION_CANCEL) {
|
||||
forwardedPointerBits = 0
|
||||
releaseAll()
|
||||
return true
|
||||
}
|
||||
if (forwardedPointerBits and (1 shl pointer) != 0) {
|
||||
forwardedPointerBits = forwardedPointerBits and (1 shl pointer).inv()
|
||||
return true
|
||||
}
|
||||
if (keyboardPressedBy == pointer) {
|
||||
val tapped = event.actionMasked == MotionEvent.ACTION_UP && keyboardContains(event.x, event.y)
|
||||
keyboardPressedBy = -1
|
||||
@@ -617,23 +604,6 @@ class OnScreenControls(
|
||||
return false
|
||||
}
|
||||
|
||||
private fun forwardMiss(event: MotionEvent, x: Float, y: Float): Boolean {
|
||||
if (onTouchMiss == null || keyboardPressedBy != -1 || quickPressedBy != -1) return false
|
||||
if (!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null) return false
|
||||
forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(event.actionIndex))
|
||||
forwardPointers(event, forwardedPointerBits)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
|
||||
val split = event.pointerSubset(pointerIdBits) ?: return
|
||||
try {
|
||||
onTouchMiss?.invoke(split)
|
||||
} finally {
|
||||
split.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun onEditTouch(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
|
||||
@@ -53,7 +53,6 @@ public final class PadBridge {
|
||||
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
|
||||
private final PadState[] playerStates = new PadState[SLOTS];
|
||||
private final PadState effectiveState = new PadState();
|
||||
private final PadState homeGuideReport = new PadState();
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private boolean open;
|
||||
private volatile boolean selectSteam;
|
||||
@@ -63,20 +62,12 @@ public final class PadBridge {
|
||||
private boolean systemGuidePressed;
|
||||
private boolean systemQamPressed;
|
||||
private boolean backQamPressed;
|
||||
private boolean homeGuidePressed;
|
||||
private int homeGuideSlot = -1;
|
||||
private final PadState lastBackQamReport = new PadState();
|
||||
private final PadState lastWrittenReport = new PadState();
|
||||
private boolean backQamAxesBlocked;
|
||||
private final java.util.Set<Runnable> backQamWrites = new java.util.HashSet<>();
|
||||
private long backQamDelayMs, backQamWriteAt;
|
||||
private boolean qamChordActive;
|
||||
private int chordButton = -1;
|
||||
private boolean chordButtonPressed;
|
||||
private boolean qamTapPressed;
|
||||
private int qamChordGeneration;
|
||||
private volatile Runnable onPlayerInput;
|
||||
private Runnable onChordInput;
|
||||
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
|
||||
private static final long STATS_WINDOW_MS = 10_000;
|
||||
@@ -139,8 +130,6 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
private void resetBuiltin() {
|
||||
homeGuidePressed = false;
|
||||
clearBackQamWrites();
|
||||
routedTouch.clear();
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
@@ -163,9 +152,6 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
homeGuidePressed = false;
|
||||
homeGuideSlot = -1;
|
||||
clearBackQamWrites();
|
||||
releaseBackPaddles();
|
||||
activeControllerId = NO_CONTROLLER;
|
||||
for (int slot = 0; slot < SLOTS; slot++) {
|
||||
@@ -232,7 +218,6 @@ public final class PadBridge {
|
||||
case KeyEvent.KEYCODE_BACK:
|
||||
case KeyEvent.KEYCODE_MENU:
|
||||
case KeyEvent.KEYCODE_HOME:
|
||||
case KeyEvent.KEYCODE_MOVE_HOME:
|
||||
if (!isFromController(device)) return false;
|
||||
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|
||||
|| device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC
|
||||
@@ -291,14 +276,6 @@ public final class PadBridge {
|
||||
onPlayerInput = listener;
|
||||
}
|
||||
|
||||
public synchronized void setOnChordInput(Runnable listener) {
|
||||
onChordInput = listener;
|
||||
}
|
||||
|
||||
private void noteChordInput(int slot) {
|
||||
if (slot == 0 && onChordInput != null) onChordInput.run();
|
||||
}
|
||||
|
||||
private void notePlayerInput() {
|
||||
Runnable listener = onPlayerInput;
|
||||
if (listener == null || !playerInputPosted.compareAndSet(false, true)) return;
|
||||
@@ -333,8 +310,7 @@ public final class PadBridge {
|
||||
case KeyEvent.KEYCODE_BUTTON_THUMBL: pad.press(8, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_THUMBR: pad.press(9, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_MODE:
|
||||
case KeyEvent.KEYCODE_HOME:
|
||||
case KeyEvent.KEYCODE_MOVE_HOME: pad.press(PadState.GUIDE, pressed); break;
|
||||
case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break;
|
||||
case KeyEvent.KEYCODE_BUTTON_Z:
|
||||
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed);
|
||||
break;
|
||||
@@ -350,7 +326,6 @@ public final class PadBridge {
|
||||
default: return false;
|
||||
}
|
||||
noteDevice(event.getDevice(), slot);
|
||||
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
|
||||
if (pressed) notePlayerInput();
|
||||
statButtons++;
|
||||
scheduleStats();
|
||||
@@ -380,7 +355,6 @@ public final class PadBridge {
|
||||
pad.rightX = x;
|
||||
pad.rightY = y;
|
||||
}
|
||||
if (x != 0f || y != 0f) noteChordInput(slot);
|
||||
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
|
||||
publish(slot);
|
||||
return true;
|
||||
@@ -411,8 +385,6 @@ public final class PadBridge {
|
||||
pad.up = hatY < -0.5f;
|
||||
pad.down = hatY > 0.5f;
|
||||
}
|
||||
if (pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|
||||
|| lt > 0f || rt > 0f || pad.up || pad.right || pad.down || pad.left) noteChordInput(slot);
|
||||
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|
||||
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
|
||||
notePlayerInput();
|
||||
@@ -489,9 +461,6 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public synchronized void releaseAll() {
|
||||
homeGuidePressed = false;
|
||||
homeGuideSlot = -1;
|
||||
clearBackQamWrites();
|
||||
routedTouch.clear();
|
||||
backQamPressed = false;
|
||||
releaseBackPaddles();
|
||||
@@ -518,142 +487,13 @@ public final class PadBridge {
|
||||
return builtinPad && nativeQam();
|
||||
}
|
||||
|
||||
public synchronized void setHomeGuidePressed(boolean pressed) {
|
||||
int slot = pressed ? firstPlayerSlot() : homeGuideSlot;
|
||||
if (slot > 0) {
|
||||
homeGuideSlot = pressed ? slot : -1;
|
||||
publish(slot);
|
||||
return;
|
||||
}
|
||||
if (homeGuidePressed == pressed) return;
|
||||
homeGuidePressed = pressed;
|
||||
updateHeldModifier(PadState.GUIDE, pressed);
|
||||
}
|
||||
|
||||
public synchronized void cancelHomeGuide() {
|
||||
int slot = homeGuideSlot;
|
||||
if (slot > 0) {
|
||||
homeGuideSlot = -1;
|
||||
publish(slot);
|
||||
}
|
||||
if (!homeGuidePressed) return;
|
||||
clearBackQamWrites();
|
||||
homeGuidePressed = false;
|
||||
state.clear();
|
||||
publish();
|
||||
}
|
||||
|
||||
public synchronized void setBackQamPressed(boolean pressed) {
|
||||
if (pressed && !canHoldQam()) return;
|
||||
if (backQamPressed == pressed) return;
|
||||
backQamPressed = pressed;
|
||||
updateHeldModifier(PadState.QAM, pressed);
|
||||
}
|
||||
|
||||
private void updateHeldModifier(int button, boolean pressed) {
|
||||
if (pressed && (open || start())) {
|
||||
backQamAxesBlocked = false;
|
||||
long now = android.os.SystemClock.uptimeMillis();
|
||||
long modifierAt = Math.max(now, backQamWriteAt);
|
||||
backQamDelayMs = modifierAt - now + QAM_GUIDE_LEAD_MIN_MS;
|
||||
PadState modifier = new PadState();
|
||||
modifier.copyFrom(lastBackQamReport);
|
||||
modifier.press(button, true);
|
||||
writeBackQamReport(modifier, modifierAt);
|
||||
}
|
||||
if (!pressed && !backQamPressed && !homeGuidePressed) {
|
||||
backQamAxesBlocked = hasAxes(state);
|
||||
if (!backQamWrites.isEmpty()) {
|
||||
PadState neutral = new PadState();
|
||||
neutral.copyFrom(lastWrittenReport);
|
||||
clearAxes(neutral);
|
||||
writer.writePad(neutral);
|
||||
lastWrittenReport.copyFrom(neutral);
|
||||
}
|
||||
}
|
||||
publish();
|
||||
}
|
||||
|
||||
public synchronized void cancelBackQam() {
|
||||
if (!backQamPressed && backQamWrites.isEmpty()) return;
|
||||
clearBackQamWrites();
|
||||
backQamPressed = false;
|
||||
state.clear();
|
||||
publish();
|
||||
}
|
||||
|
||||
private void clearBackQamWrites() {
|
||||
for (Runnable pending : backQamWrites) mainHandler.removeCallbacks(pending);
|
||||
backQamWrites.clear();
|
||||
backQamDelayMs = backQamWriteAt = 0;
|
||||
lastBackQamReport.clear();
|
||||
lastWrittenReport.clear();
|
||||
backQamAxesBlocked = false;
|
||||
}
|
||||
|
||||
private void writeBackQamReport(PadState report, long at) {
|
||||
lastBackQamReport.copyFrom(report);
|
||||
if (backQamWrites.isEmpty() && at <= android.os.SystemClock.uptimeMillis()) {
|
||||
writeReport(report, false);
|
||||
return;
|
||||
}
|
||||
PadState queued = new PadState();
|
||||
queued.copyFrom(report);
|
||||
Runnable pending = new Runnable() {
|
||||
@Override public void run() {
|
||||
synchronized (PadBridge.this) {
|
||||
if (!backQamWrites.remove(this)) return;
|
||||
writeReport(queued, true);
|
||||
if (backQamWrites.isEmpty() && !hasButtons(lastBackQamReport)) backQamDelayMs = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
backQamWrites.add(pending);
|
||||
backQamWriteAt = at;
|
||||
mainHandler.postAtTime(pending, at);
|
||||
}
|
||||
|
||||
private void writePad(PadState report) {
|
||||
if (backQamAxesBlocked && !hasAxes(state)) backQamAxesBlocked = false;
|
||||
long at = android.os.SystemClock.uptimeMillis();
|
||||
// Steam must see the modifier before a partner; preserve quick press/release pairs in order.
|
||||
if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs;
|
||||
writeBackQamReport(report, at);
|
||||
}
|
||||
|
||||
private static boolean hasAxes(PadState pad) {
|
||||
return pad.leftX != 0f || pad.leftY != 0f || pad.rightX != 0f || pad.rightY != 0f
|
||||
|| pad.leftTrigger != 0f || pad.rightTrigger != 0f;
|
||||
}
|
||||
|
||||
private static void clearAxes(PadState pad) {
|
||||
pad.leftX = pad.leftY = pad.rightX = pad.rightY = pad.leftTrigger = pad.rightTrigger = 0f;
|
||||
}
|
||||
|
||||
private static boolean hasButtons(PadState pad) {
|
||||
for (int i = 0; i < 10; i++) if (pad.isDown(i)) return true;
|
||||
return pad.isDown(PadState.GUIDE) || pad.up || pad.right || pad.down || pad.left;
|
||||
}
|
||||
|
||||
private void writeReport(PadState report, boolean queued) {
|
||||
if (!queued && !backQamAxesBlocked) {
|
||||
lastWrittenReport.copyFrom(report);
|
||||
writer.writePad(report);
|
||||
return;
|
||||
}
|
||||
PadState live = new PadState();
|
||||
live.copyFrom(report);
|
||||
if (queued) {
|
||||
live.leftX = state.leftX; live.leftY = state.leftY;
|
||||
live.rightX = state.rightX; live.rightY = state.rightY;
|
||||
live.leftTrigger = state.leftTrigger; live.rightTrigger = state.rightTrigger;
|
||||
}
|
||||
boolean held = (backQamPressed && report.isDown(PadState.QAM)) || (homeGuidePressed && report.isDown(PadState.GUIDE));
|
||||
if ((queued && !held) || backQamAxesBlocked) clearAxes(live);
|
||||
lastWrittenReport.copyFrom(live);
|
||||
writer.writePad(live);
|
||||
}
|
||||
|
||||
public synchronized void triggerQam() {
|
||||
if (!builtinPad) return;
|
||||
if (!nativeQam()) {
|
||||
@@ -732,9 +572,7 @@ public final class PadBridge {
|
||||
slotJoyCons.set(slot * 2 + side, id);
|
||||
slotJoyCons.set(slot * 2 + 1 - side, owner.getId());
|
||||
if (slot == firstPlayerSlot()) releaseBackPaddles();
|
||||
if (slot == 0) clearBackQamWrites();
|
||||
stateFor(slot).clear();
|
||||
if (slot == 0) publish();
|
||||
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1));
|
||||
return slot;
|
||||
}
|
||||
@@ -769,7 +607,6 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
private void leave(int slot, int id) {
|
||||
if (slot == 0) clearBackQamWrites();
|
||||
if (partners[slot] == NO_CONTROLLER) {
|
||||
free(slot);
|
||||
return;
|
||||
@@ -796,7 +633,6 @@ public final class PadBridge {
|
||||
partners[slot] = NO_CONTROLLER;
|
||||
clearJoyCons(slot);
|
||||
slotControllers.set(slot, NO_CONTROLLER);
|
||||
if (slot == homeGuideSlot) homeGuideSlot = -1;
|
||||
if (slot == firstPlayerSlot()) releaseBackPaddles();
|
||||
if (slot == 0) {
|
||||
state.clear();
|
||||
@@ -853,13 +689,7 @@ public final class PadBridge {
|
||||
}
|
||||
playerWriters[slot] = player;
|
||||
}
|
||||
PadState report = playerStates[slot];
|
||||
if (slot == homeGuideSlot) {
|
||||
homeGuideReport.copyFrom(report);
|
||||
homeGuideReport.press(PadState.GUIDE, true);
|
||||
report = homeGuideReport;
|
||||
}
|
||||
player.writePad(report);
|
||||
player.writePad(playerStates[slot]);
|
||||
}
|
||||
|
||||
private void publish() {
|
||||
@@ -868,17 +698,17 @@ public final class PadBridge {
|
||||
statDropped++;
|
||||
return;
|
||||
}
|
||||
boolean guide = systemGuidePressed || qamChordActive || homeGuidePressed;
|
||||
boolean guide = systemGuidePressed || qamChordActive;
|
||||
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed || backQamPressed);
|
||||
if (!guide && !qam) {
|
||||
writePad(state);
|
||||
writer.writePad(state);
|
||||
return;
|
||||
}
|
||||
effectiveState.copyFrom(state);
|
||||
if (guide) effectiveState.press(PadState.GUIDE, true);
|
||||
if (qam) effectiveState.press(PadState.QAM, true);
|
||||
if (chordButtonPressed) effectiveState.press(chordButton, true);
|
||||
writePad(effectiveState);
|
||||
writer.writePad(effectiveState);
|
||||
}
|
||||
|
||||
public static boolean wiredXboxLayout(MotionEvent event) {
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.MotionEvent
|
||||
|
||||
internal fun MotionEvent.pointerSubset(pointerIdBits: Int): MotionEvent? {
|
||||
val indices = (0 until pointerCount).filter { index ->
|
||||
pointerIdBits and (1 shl getPointerId(index)) != 0
|
||||
}
|
||||
if (indices.isEmpty()) return null
|
||||
val splitIndex = indices.indexOf(actionIndex)
|
||||
val splitAction = when (actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> if (splitIndex >= 0) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_POINTER_DOWN -> if (splitIndex >= 0) {
|
||||
if (indices.size == 1) MotionEvent.ACTION_DOWN
|
||||
else MotionEvent.ACTION_POINTER_DOWN or (splitIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
} else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_UP -> if (splitIndex >= 0) MotionEvent.ACTION_UP else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_POINTER_UP -> if (splitIndex >= 0) {
|
||||
if (indices.size == 1) MotionEvent.ACTION_UP
|
||||
else MotionEvent.ACTION_POINTER_UP or (splitIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
} else MotionEvent.ACTION_MOVE
|
||||
else -> action
|
||||
}
|
||||
val properties = Array(indices.size) { MotionEvent.PointerProperties() }
|
||||
val coordinates = Array(indices.size) { MotionEvent.PointerCoords() }
|
||||
indices.forEachIndexed { target, index ->
|
||||
getPointerProperties(index, properties[target])
|
||||
getPointerCoords(index, coordinates[target])
|
||||
}
|
||||
return MotionEvent.obtain(
|
||||
downTime, eventTime, splitAction, indices.size, properties, coordinates,
|
||||
metaState, buttonState, xPrecision, yPrecision,
|
||||
deviceId, edgeFlags, source, flags,
|
||||
)
|
||||
}
|
||||
@@ -926,7 +926,35 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
|
||||
}
|
||||
|
||||
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
|
||||
val split = event.pointerSubset(pointerIdBits) ?: return
|
||||
val indices = (0 until event.pointerCount).filter { index ->
|
||||
pointerIdBits and (1 shl event.getPointerId(index)) != 0
|
||||
}
|
||||
if (indices.isEmpty()) return
|
||||
val actionIndex = indices.indexOf(event.actionIndex)
|
||||
val action = when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> if (actionIndex >= 0) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_POINTER_DOWN -> if (actionIndex >= 0) {
|
||||
if (indices.size == 1) MotionEvent.ACTION_DOWN
|
||||
else MotionEvent.ACTION_POINTER_DOWN or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
} else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_UP -> if (actionIndex >= 0) MotionEvent.ACTION_UP else MotionEvent.ACTION_MOVE
|
||||
MotionEvent.ACTION_POINTER_UP -> if (actionIndex >= 0) {
|
||||
if (indices.size == 1) MotionEvent.ACTION_UP
|
||||
else MotionEvent.ACTION_POINTER_UP or (actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
} else MotionEvent.ACTION_MOVE
|
||||
else -> event.action
|
||||
}
|
||||
val properties = Array(indices.size) { MotionEvent.PointerProperties() }
|
||||
val coordinates = Array(indices.size) { MotionEvent.PointerCoords() }
|
||||
indices.forEachIndexed { target, source ->
|
||||
event.getPointerProperties(source, properties[target])
|
||||
event.getPointerCoords(source, coordinates[target])
|
||||
}
|
||||
val split = MotionEvent.obtain(
|
||||
event.downTime, event.eventTime, action, indices.size, properties, coordinates,
|
||||
event.metaState, event.buttonState, event.xPrecision, event.yPrecision,
|
||||
event.deviceId, event.edgeFlags, event.source, event.flags,
|
||||
)
|
||||
try {
|
||||
onTouchMiss?.invoke(split)
|
||||
} finally {
|
||||
|
||||
@@ -103,8 +103,6 @@ class SteamTouchControls(
|
||||
|
||||
private class Finger(val element: Element?, var x: Float, var y: Float, val toolbar: Int = -1)
|
||||
private val fingers = HashMap<Int, Finger>()
|
||||
private var forwardedPointerBits = 0
|
||||
var onTouchMiss: ((MotionEvent) -> Unit)? = null
|
||||
|
||||
private var editing = false
|
||||
private var editElements: MutableList<Element> = mutableListOf()
|
||||
@@ -631,17 +629,7 @@ class SteamTouchControls(
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
val x = event.getX(index)
|
||||
val y = event.getY(index)
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0
|
||||
val e = hit(live(), x, y)
|
||||
if (e == null) {
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) return false
|
||||
if (onTouchMiss != null) {
|
||||
forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(index))
|
||||
forwardPointers(event, forwardedPointerBits)
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
val e = hit(live(), x, y) ?: return event.actionMasked == MotionEvent.ACTION_POINTER_DOWN
|
||||
fingers[event.getPointerId(index)] = Finger(e, x, y)
|
||||
if (feedback) performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
requestUnbufferedDispatch(event)
|
||||
@@ -649,7 +637,6 @@ class SteamTouchControls(
|
||||
return true
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
for (i in 0 until event.pointerCount) {
|
||||
val f = fingers[event.getPointerId(i)] ?: continue
|
||||
f.x = event.getX(i)
|
||||
@@ -668,14 +655,12 @@ class SteamTouchControls(
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
val id = event.getPointerId(index)
|
||||
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
|
||||
forwardedPointerBits = if (event.actionMasked == MotionEvent.ACTION_CANCEL) 0 else forwardedPointerBits and (1 shl id).inv()
|
||||
val f = fingers.remove(id)
|
||||
if (event.actionMasked == MotionEvent.ACTION_CANCEL) fingers.clear()
|
||||
val e = f?.element
|
||||
if (event.actionMasked != MotionEvent.ACTION_CANCEL && e != null && reach(e, event.getX(index), event.getY(index)) <= 1.3f) {
|
||||
when (e.type) {
|
||||
SteamTouchConfig.THUMB -> { cancelForwarded(event); openMenu() }
|
||||
SteamTouchConfig.THUMB -> openMenu()
|
||||
SteamTouchConfig.KEYBOARD -> onKeyboard()
|
||||
SteamTouchConfig.PASTE -> onPaste()
|
||||
}
|
||||
@@ -688,25 +673,6 @@ class SteamTouchControls(
|
||||
}
|
||||
|
||||
|
||||
private fun cancelForwarded(event: MotionEvent) {
|
||||
val split = event.pointerSubset(forwardedPointerBits).also { forwardedPointerBits = 0 } ?: return
|
||||
split.action = MotionEvent.ACTION_CANCEL
|
||||
try {
|
||||
onTouchMiss?.invoke(split)
|
||||
} finally {
|
||||
split.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
|
||||
val split = event.pointerSubset(pointerIdBits) ?: return
|
||||
try {
|
||||
onTouchMiss?.invoke(split)
|
||||
} finally {
|
||||
split.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
val isEditing get() = editing
|
||||
|
||||
fun startEditing() {
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.media.AudioManager
|
||||
import android.view.KeyEvent
|
||||
|
||||
/** Use Steam's PulseAudio bridge for feedback instead of requesting Android's volume UI. */
|
||||
internal object SteamVolumeKeys {
|
||||
fun dispatch(event: KeyEvent, enabled: Boolean, adjust: (Int) -> Unit): Boolean {
|
||||
val direction = when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP -> AudioManager.ADJUST_RAISE
|
||||
KeyEvent.KEYCODE_VOLUME_DOWN -> AudioManager.ADJUST_LOWER
|
||||
KeyEvent.KEYCODE_VOLUME_MUTE -> AudioManager.ADJUST_TOGGLE_MUTE
|
||||
else -> return false
|
||||
}
|
||||
if (!enabled) return false
|
||||
if (event.action == KeyEvent.ACTION_DOWN &&
|
||||
(event.keyCode != KeyEvent.KEYCODE_VOLUME_MUTE || event.repeatCount == 0)) {
|
||||
adjust(direction)
|
||||
}
|
||||
return event.action == KeyEvent.ACTION_DOWN || event.action == KeyEvent.ACTION_UP
|
||||
}
|
||||
}
|
||||
@@ -360,8 +360,6 @@ object BattleNet {
|
||||
if (ComponentsManager.gameComponents(context, scope)["fex"] != file) {
|
||||
ComponentsManager.setGameComponent(context, scope, "fex", file)
|
||||
Log.i(TAG, "FEX for the Battle.net prefix: $file")
|
||||
} else if (ComponentsManager.republish(context)) {
|
||||
Log.i(TAG, "FEX for the Battle.net prefix: $file, now in every installed Proton")
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@ object DesktopCatalog {
|
||||
val icon: String, val category: String,
|
||||
)
|
||||
|
||||
fun fetch(url: String = CATALOG_URL, cancelled: java.util.function.BooleanSupplier? = null): List<Entry>? {
|
||||
val body = Downloader.downloadString(url, cancelled) ?: return null
|
||||
fun fetch(url: String = CATALOG_URL): List<Entry>? {
|
||||
val body = Downloader.downloadString(url) ?: return null
|
||||
return try {
|
||||
val json = JSONObject(body)
|
||||
val arr = json.getJSONArray("packages")
|
||||
@@ -71,22 +71,9 @@ object DesktopCatalog {
|
||||
}
|
||||
|
||||
fun resumeInterrupted(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
|
||||
resumeInterrupted(context, null, listener)
|
||||
}
|
||||
|
||||
fun resumeInterrupted(
|
||||
context: Context,
|
||||
cancelled: Downloader.Cancellation?,
|
||||
listener: LinuxRuntimeInstaller.ProgressListener?,
|
||||
): String? = synchronized(installLock) {
|
||||
for (entry in interrupted(context)) {
|
||||
Log.w(TAG, "finishing the interrupted install of ${entry.id} ${entry.version}")
|
||||
val problem = if (cancelled == null) {
|
||||
install(context, entry, listener)
|
||||
} else {
|
||||
install(context, entry, cancelled, listener)
|
||||
}
|
||||
if (problem != null) return problem
|
||||
install(context, entry, listener)?.let { return it }
|
||||
}
|
||||
null
|
||||
}
|
||||
@@ -157,16 +144,10 @@ object DesktopCatalog {
|
||||
}
|
||||
|
||||
fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
|
||||
installLocked(context, entry, null, listener)
|
||||
installLocked(context, entry, listener)
|
||||
}
|
||||
|
||||
fun install(context: Context, entry: Entry, cancelled: Downloader.Cancellation,
|
||||
listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) {
|
||||
installLocked(context, entry, cancelled, listener)
|
||||
}
|
||||
|
||||
private fun installLocked(context: Context, entry: Entry, cancelled: Downloader.Cancellation?,
|
||||
listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||
private fun installLocked(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
if (!root.isDirectory) return context.getString(R.string.deskpkg_runtime_missing)
|
||||
if (entry.sha256.isEmpty()) return context.getString(R.string.deskpkg_no_checksum, entry.name)
|
||||
@@ -185,20 +166,14 @@ object DesktopCatalog {
|
||||
if (!downloaded(download, entry)) {
|
||||
val downloading = context.getString(R.string.user_apps_downloading, entry.name)
|
||||
report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, 0)
|
||||
val progress = java.util.function.Consumer<Float> { f ->
|
||||
val ok = Downloader.downloadFile(entry.url, download, true, entry.sha256) { f ->
|
||||
report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, if (f < 0) -1 else Math.round(f * 100f))
|
||||
}
|
||||
val ok = if (cancelled == null) {
|
||||
Downloader.downloadFile(entry.url, download, true, entry.sha256, progress)
|
||||
} else {
|
||||
Downloader.downloadFile(entry.url, download, true, entry.sha256, cancelled, progress)
|
||||
}
|
||||
if (!ok || cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed)
|
||||
if (!ok) return context.getString(R.string.user_apps_download_failed)
|
||||
report.onProgress(LinuxRuntimeInstaller.Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1)
|
||||
val actual = Hashes.sha256(download)
|
||||
if (!entry.sha256.equals(actual, ignoreCase = true)) return context.getString(R.string.deskpkg_checksum_mismatch)
|
||||
}
|
||||
if (cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed)
|
||||
report.onProgress(context.getString(R.string.deskpkg_installing, entry.name), -1)
|
||||
when (entry.kind) {
|
||||
"appimage" -> {
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.database.ContentObserver
|
||||
import android.media.AudioManager
|
||||
import android.net.Uri
|
||||
import android.os.FileObserver
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
@@ -29,16 +29,14 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
|
||||
private val directory = directory(root)
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var running = false
|
||||
private var permissionNotified = false
|
||||
private var pendingBrightness: Float? = null
|
||||
private var permissionRequestAt = -5_000L
|
||||
private var previous = ""
|
||||
private var revision = 0L
|
||||
init { prepareBacklight(context, root) }
|
||||
private val observer = object : ContentObserver(handler) {
|
||||
override fun onChange(selfChange: Boolean) { if (running) publish() }
|
||||
}
|
||||
private val volumeSteps = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) { if (running) publishVolume() }
|
||||
}
|
||||
private val requests = object : FileObserver(directory.path, CLOSE_WRITE or MOVED_TO) {
|
||||
override fun onEvent(event: Int, path: String?) {
|
||||
if (path in REQUESTS) handler.post { if (running) consume() }
|
||||
@@ -48,29 +46,25 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
|
||||
override fun run() {
|
||||
if (!running) return
|
||||
consume()
|
||||
if (permissionNotified && Settings.System.canWrite(context))
|
||||
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
|
||||
pendingBrightness?.let { value ->
|
||||
if (Settings.System.canWrite(context)) {
|
||||
pendingBrightness = null
|
||||
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
|
||||
brightness(value)
|
||||
}
|
||||
}
|
||||
publish()
|
||||
handler.postDelayed(this, 250)
|
||||
}
|
||||
}
|
||||
|
||||
private fun publishVolume() {
|
||||
fun publish(force: Boolean = false) {
|
||||
try {
|
||||
directory.mkdirs()
|
||||
val level = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
|
||||
val maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1)
|
||||
val muted = audio.isStreamMute(AudioManager.STREAM_MUSIC)
|
||||
write("volume.state", "$level $maximum ${if (muted) 1 else 0}\n")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not publish Android volume", e)
|
||||
}
|
||||
}
|
||||
|
||||
fun publish(force: Boolean = false) {
|
||||
publishVolume()
|
||||
try {
|
||||
directory.mkdirs()
|
||||
val value = Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS, 128)
|
||||
write("backlight/droiddeck/brightness", "$value\n")
|
||||
write("backlight/droiddeck/actual_brightness", "$value\n")
|
||||
@@ -92,13 +86,8 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
|
||||
File(directory, "$it.processing").delete()
|
||||
}
|
||||
running = true
|
||||
permissionNotified = false
|
||||
context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, observer)
|
||||
requests.startWatching()
|
||||
context.registerReceiver(volumeSteps, IntentFilter().apply {
|
||||
addAction(VOLUME_CHANGED_ACTION)
|
||||
addAction(STREAM_MUTE_CHANGED_ACTION)
|
||||
}, null, handler)
|
||||
refresh.run()
|
||||
}
|
||||
}
|
||||
@@ -108,8 +97,8 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
|
||||
running = false
|
||||
handler.removeCallbacks(refresh)
|
||||
requests.stopWatching()
|
||||
try { context.unregisterReceiver(volumeSteps) } catch (e: IllegalArgumentException) { }
|
||||
context.contentResolver.unregisterContentObserver(observer)
|
||||
pendingBrightness = null
|
||||
context.getSystemService(NotificationManager::class.java).cancel(PERMISSION_NOTIFICATION)
|
||||
}
|
||||
}
|
||||
@@ -145,13 +134,13 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
|
||||
|
||||
private fun brightness(value: Float) {
|
||||
if (!Settings.System.canWrite(context)) {
|
||||
if (!permissionNotified) {
|
||||
permissionNotified = true
|
||||
pendingBrightness = value
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (now - permissionRequestAt >= 5_000) {
|
||||
permissionRequestAt = now
|
||||
try {
|
||||
val intent = Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java)
|
||||
.setAction(com.droiddeck.launcher.core.SteamIntegration.ACTION_SETUP)
|
||||
.putExtra(com.droiddeck.launcher.core.SteamIntegration.EXTRA_FEATURE, "BRIGHTNESS")
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
|
||||
Uri.parse("package:${context.packageName}")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(NotificationChannel(PERMISSION_CHANNEL,
|
||||
context.getString(R.string.brightness_permission_title), NotificationManager.IMPORTANCE_DEFAULT))
|
||||
@@ -161,8 +150,7 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
|
||||
.setContentTitle(context.getString(R.string.brightness_permission_title))
|
||||
.setContentText(context.getString(R.string.brightness_permission_text))
|
||||
.setContentIntent(action).setOnlyAlertOnce(true).setAutoCancel(true).build())
|
||||
if (activityVisible()) android.widget.Toast.makeText(context, R.string.integration_brightness_needed,
|
||||
android.widget.Toast.LENGTH_LONG).show()
|
||||
if (activityVisible()) context.startActivity(intent)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not open brightness permission", e)
|
||||
}
|
||||
@@ -189,9 +177,6 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DeviceControls"
|
||||
// AudioService sends these on every stream step; the Settings observer and 250 ms poll lag a held volume key.
|
||||
private const val VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION"
|
||||
private const val STREAM_MUTE_CHANGED_ACTION = "android.media.STREAM_MUTE_CHANGED_ACTION"
|
||||
private const val PERMISSION_CHANNEL = "brightness_permission"
|
||||
private const val PERMISSION_NOTIFICATION = 0x4442
|
||||
private val REQUESTS = setOf("brightness.request", "volume.request", "mute.request")
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
@@ -38,10 +37,9 @@ object ProotFastPath {
|
||||
|
||||
fun hostEnv(key: String): Pair<String, String> = "PROOT_FASTPATH" to key
|
||||
|
||||
fun guestEnv(root: File, binds: List<String>, key: String, sdk: Int = Build.VERSION.SDK_INT): List<String> = listOf(
|
||||
fun guestEnv(root: File, binds: List<String>, key: String): List<String> = listOf(
|
||||
"PROOT_FP_ROOT=" + root.path,
|
||||
"PROOT_FP_BINDS=" + binds.joinToString("|"),
|
||||
"PROOT_FP_KEY=$key",
|
||||
"PROOT_FP_ANDROID_API=$sdk",
|
||||
)
|
||||
}
|
||||
@@ -155,7 +155,8 @@ object ComponentsManager {
|
||||
if (staged.exists()) check(staged.delete()) { "Could not remove unpublished component selections" }
|
||||
}
|
||||
|
||||
private fun saveState(context: Context, state: JSONObject, prepared: PreparedLaunchState = prepareLaunchState(context, state)) {
|
||||
private fun saveState(context: Context, state: JSONObject) {
|
||||
val prepared = prepareLaunchState(context, state)
|
||||
val dir = launchDir(context)
|
||||
val tmp = File(dir, "desired.tsv.tmp")
|
||||
try {
|
||||
@@ -174,17 +175,6 @@ object ComponentsManager {
|
||||
?.forEach { it.deleteRecursively() }
|
||||
}
|
||||
|
||||
fun republish(context: Context): Boolean = synchronized(lock) {
|
||||
recoverState(context)
|
||||
val saved = stateFile(context)
|
||||
if (saved.exists() && runCatching { JSONObject(saved.readText()) }.isFailure) return false
|
||||
val state = loadState(context)
|
||||
val prepared = prepareLaunchState(context, state)
|
||||
if ((FileUtils.readString(File(launchDir(context), "desired.tsv")) ?: "") == prepared.text) return false
|
||||
saveState(context, state, prepared)
|
||||
true
|
||||
}
|
||||
|
||||
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
|
||||
|
||||
private fun rememberProfiledComponent(state: JSONObject, comp: String) {
|
||||
|
||||
@@ -13,7 +13,6 @@ object GameEnvironmentStore {
|
||||
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
|
||||
const val DXVK_CONFIG = "dxvkConfig"
|
||||
const val DXVK_CONFIG_GAMES = "dxvkConfigGames"
|
||||
const val GAME_DEBUG_LOGS = "gameDebugLogs"
|
||||
|
||||
@Synchronized
|
||||
fun read(context: Context): GameEnvironment.Config {
|
||||
@@ -88,11 +87,7 @@ object GameEnvironmentStore {
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun publish(
|
||||
context: Context,
|
||||
config: GameEnvironment.Config = read(context),
|
||||
gameDebugLogsOverride: Boolean? = null,
|
||||
) {
|
||||
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
|
||||
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
|
||||
val json = encode(resolved)
|
||||
val dxvk = TextureFiltering.dxvkOptions(
|
||||
@@ -115,11 +110,6 @@ object GameEnvironmentStore {
|
||||
)
|
||||
}
|
||||
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
|
||||
json.put(
|
||||
GAME_DEBUG_LOGS,
|
||||
gameDebugLogsOverride ?: (SessionPrefs.logsEnabled(context) &&
|
||||
SessionPrefs.gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context)),
|
||||
)
|
||||
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
|
||||
}
|
||||
|
||||
|
||||
@@ -51,8 +51,7 @@ object NoSteamLaunch {
|
||||
|
||||
fun addedGame(context: Context, game: Library.SteamGame): AddedGames.Game? {
|
||||
val id = game.appId.toLong() and 0xFFFFFFFFL
|
||||
val one = game.gameFiles?.let { AddedGames.single(context, it.path) }
|
||||
return one?.takeIf { settingsId(it) == id } ?: AddedGames.scan(context).firstOrNull { settingsId(it) == id }
|
||||
return AddedGames.scan(context).firstOrNull { settingsId(it) == id }
|
||||
}
|
||||
|
||||
fun nameFor(program: String?, args: List<String>): String? = when (program) {
|
||||
|
||||
@@ -30,7 +30,6 @@ class RumbleComponent : SessionPart() {
|
||||
private val joyConPairs = HashMap<Long, Motors>()
|
||||
private var preferences: SharedPreferences? = null
|
||||
private var enabled = false
|
||||
private var quiet = false
|
||||
private var motorThread: HandlerThread? = null
|
||||
private var handler: Handler? = null
|
||||
private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
||||
@@ -45,11 +44,6 @@ class RumbleComponent : SessionPart() {
|
||||
if (!enabled) cancelAll()
|
||||
}
|
||||
|
||||
@Synchronized fun quiet(on: Boolean) {
|
||||
quiet = on
|
||||
if (on) cancelAll()
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
val ctx = app() ?: return
|
||||
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return }
|
||||
@@ -95,7 +89,7 @@ class RumbleComponent : SessionPart() {
|
||||
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
|
||||
|
||||
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int, slot: Int) {
|
||||
if (!enabled || quiet) return
|
||||
if (!enabled) return
|
||||
val target = target(slot)
|
||||
val previous = playing[slot]
|
||||
if (target !== previous) {
|
||||
|
||||
@@ -7,9 +7,6 @@ import com.droiddeck.launcher.core.SessionLogCapture
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.io.Writer
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
@@ -19,9 +16,6 @@ object SessionArtifacts {
|
||||
|
||||
const val COMPLETE_MARKER = ".complete"
|
||||
|
||||
private const val RECOVERY_RUNTIME_CAPTURED_MARKER = ".recovery-runtime-captured"
|
||||
private const val RECOVERY_RUNTIME_EXPIRED_MARKER = ".recovery-runtime-expired"
|
||||
|
||||
private val SCRUBBED_MARKER = ".scrubbed-r${LogRedactor.RULES_VERSION}"
|
||||
private val OLD_SCRUBBED_MARKER = Regex("""\.scrubbed-(r?\d+)""")
|
||||
|
||||
@@ -78,9 +72,9 @@ object SessionArtifacts {
|
||||
copySteamLogs(context, dir, record, steamArch)
|
||||
VacDiagnostics.collect(context, dir)
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
val scrubbed = markScrubbed(scrubTree(record))
|
||||
markScrubbed(scrubTree(record))
|
||||
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
|
||||
if (scrubbed) File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "collecting session artifacts", e)
|
||||
}
|
||||
@@ -94,10 +88,15 @@ object SessionArtifacts {
|
||||
}?.toList() ?: return
|
||||
if (dirs.isEmpty()) return
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
var done = 0
|
||||
for (dir in dirs) {
|
||||
if (SessionState.running) break
|
||||
if (scrubAndMark(dir, stopWhenSessionStarts = true)) done++
|
||||
val workers = (Runtime.getRuntime().availableProcessors() / 2).coerceIn(1, 4)
|
||||
val pool = java.util.concurrent.Executors.newFixedThreadPool(workers) { r ->
|
||||
Thread({ android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); r.run() }, "scrub-logs")
|
||||
}
|
||||
val done = try {
|
||||
pool.invokeAll(dirs.map { dir -> java.util.concurrent.Callable { scrubAndMark(dir) } })
|
||||
.count { f -> try { f.get() } catch (e: Exception) { false } }
|
||||
} finally {
|
||||
pool.shutdown()
|
||||
}
|
||||
val failed = dirs.size - done
|
||||
Log.i(TAG, "logs: scrubbed $done folders under r${LogRedactor.RULES_VERSION}" +
|
||||
@@ -115,121 +114,35 @@ object SessionArtifacts {
|
||||
private class Record(val dir: File) {
|
||||
val files = HashMap<File, Scrubbed>()
|
||||
var failed = false
|
||||
var deferred = false
|
||||
}
|
||||
|
||||
private sealed class ScrubResult {
|
||||
class Done(val scrubbed: Scrubbed) : ScrubResult()
|
||||
object Failed : ScrubResult()
|
||||
object Deferred : ScrubResult()
|
||||
private fun scrubFolder(dir: File, record: Record) {
|
||||
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }?.forEach { f ->
|
||||
if (LogRedactor.isBinary(f)) return@forEach
|
||||
// Too large to rewrite in memory: the folder must not be recorded as scrubbed.
|
||||
if (!LogRedactor.isText(f)) { record.failed = true; return@forEach }
|
||||
val done = scrubFile(dir, f)
|
||||
if (done == null) record.failed = true else record.files[f] = done
|
||||
}
|
||||
}
|
||||
|
||||
private fun scrubFolder(
|
||||
dir: File,
|
||||
record: Record,
|
||||
shouldStop: () -> Boolean,
|
||||
beforeReplace: (File) -> Unit,
|
||||
listFiles: (File) -> Array<File>?,
|
||||
): Boolean {
|
||||
val files = listFiles(dir)?.filter { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }
|
||||
if (files == null) {
|
||||
record.failed = true
|
||||
return true
|
||||
}
|
||||
for (f in files) {
|
||||
if (shouldStop()) return false
|
||||
if (LogRedactor.isBinary(f)) continue
|
||||
when (val result = scrubFile(dir, f, shouldStop, beforeReplace)) {
|
||||
is ScrubResult.Done -> record.files[f] = result.scrubbed
|
||||
ScrubResult.Failed -> record.failed = true
|
||||
ScrubResult.Deferred -> {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
private fun scrubFile(
|
||||
dir: File,
|
||||
f: File,
|
||||
shouldStop: () -> Boolean,
|
||||
beforeReplace: (File) -> Unit,
|
||||
): ScrubResult {
|
||||
private fun scrubFile(dir: File, f: File): Scrubbed? {
|
||||
val tmp = File(dir, ".${f.name}.scrub")
|
||||
return try {
|
||||
val before = Scrubbed(f.length(), f.lastModified())
|
||||
val scrubbed = tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w, shouldStop) }
|
||||
if (!scrubbed) {
|
||||
tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) }
|
||||
val scrubbed = tmp.readBytes()
|
||||
if (scrubbed.contentEquals(f.readBytes())) {
|
||||
tmp.delete()
|
||||
return ScrubResult.Deferred
|
||||
}
|
||||
val scrubbedLength = tmp.length()
|
||||
when (sameContents(tmp, f, shouldStop)) {
|
||||
null -> {
|
||||
tmp.delete()
|
||||
ScrubResult.Deferred
|
||||
}
|
||||
true -> {
|
||||
tmp.delete()
|
||||
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
|
||||
?.let { ScrubResult.Done(it) } ?: ScrubResult.Failed
|
||||
}
|
||||
false -> {
|
||||
if (shouldStop()) {
|
||||
tmp.delete()
|
||||
return ScrubResult.Deferred
|
||||
}
|
||||
beforeReplace(f)
|
||||
if (f.length() != before.length || f.lastModified() != before.modified) {
|
||||
tmp.delete()
|
||||
return ScrubResult.Failed
|
||||
}
|
||||
if (!tmp.renameTo(f)) {
|
||||
tmp.delete()
|
||||
return ScrubResult.Failed
|
||||
}
|
||||
Scrubbed(scrubbedLength, f.lastModified()).takeIf { f.length() == it.length }
|
||||
?.let { ScrubResult.Done(it) } ?: ScrubResult.Failed
|
||||
}
|
||||
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
|
||||
} else {
|
||||
if (!tmp.renameTo(f)) { f.writeBytes(scrubbed); tmp.delete() }
|
||||
Scrubbed(scrubbed.size.toLong(), f.lastModified()).takeIf { f.length() == it.length }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not scrub ${f.name}", e)
|
||||
tmp.delete()
|
||||
ScrubResult.Failed
|
||||
}
|
||||
}
|
||||
|
||||
internal fun sameContents(a: File, b: File, shouldStop: () -> Boolean = { false }): Boolean? {
|
||||
if (shouldStop()) return null
|
||||
if (a.length() != b.length()) return false
|
||||
fun readChunk(input: java.io.InputStream, buffer: ByteArray): Int? {
|
||||
var count = 0
|
||||
while (count < buffer.size) {
|
||||
if (shouldStop()) return null
|
||||
val read = input.read(buffer, count, buffer.size - count)
|
||||
if (shouldStop()) return null
|
||||
if (read < 0) break
|
||||
if (read == 0) continue
|
||||
count += read
|
||||
}
|
||||
return count
|
||||
}
|
||||
return a.inputStream().buffered().use { left ->
|
||||
b.inputStream().buffered().use { right ->
|
||||
val leftBuffer = ByteArray(64 * 1024)
|
||||
val rightBuffer = ByteArray(64 * 1024)
|
||||
while (true) {
|
||||
val leftCount = readChunk(left, leftBuffer) ?: return null
|
||||
val rightCount = readChunk(right, rightBuffer) ?: return null
|
||||
if (leftCount != rightCount) return false
|
||||
if (leftCount == 0) break
|
||||
if (shouldStop()) return null
|
||||
for (i in 0 until leftCount) if (leftBuffer[i] != rightBuffer[i]) return false
|
||||
}
|
||||
true
|
||||
}
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,44 +183,10 @@ object SessionArtifacts {
|
||||
}.toSet()
|
||||
}
|
||||
|
||||
internal fun scrubAndMark(
|
||||
dir: File,
|
||||
stopWhenSessionStarts: Boolean = false,
|
||||
beforeReplace: (File) -> Unit = {},
|
||||
listFiles: (File) -> Array<File>? = { it.listFiles() },
|
||||
sessionStarted: () -> Boolean = { SessionState.running },
|
||||
): Boolean {
|
||||
val shouldStop = { stopWhenSessionStarts && sessionStarted() }
|
||||
val record = scrubTree(
|
||||
Record(dir),
|
||||
listFiles = listFiles,
|
||||
beforeReplace = beforeReplace,
|
||||
shouldStop = shouldStop,
|
||||
)
|
||||
if (shouldStop()) {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
}
|
||||
return markScrubbed(record)
|
||||
}
|
||||
internal fun scrubAndMark(dir: File): Boolean = markScrubbed(scrubTree(Record(dir)))
|
||||
|
||||
private fun scrubTree(
|
||||
record: Record,
|
||||
listFiles: (File) -> Array<File>? = { it.listFiles() },
|
||||
beforeReplace: (File) -> Unit = {},
|
||||
shouldStop: () -> Boolean = { false },
|
||||
): Record {
|
||||
for (dir in record.dir.walkTopDown().filter { it.isDirectory }) {
|
||||
if (shouldStop() || !scrubFolder(dir, record, shouldStop, beforeReplace, listFiles)) {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (shouldStop()) {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
}
|
||||
private fun scrubTree(record: Record): Record {
|
||||
record.dir.walkTopDown().filter { it.isDirectory }.forEach { scrubFolder(it, record) }
|
||||
return record
|
||||
}
|
||||
|
||||
@@ -326,7 +205,6 @@ object SessionArtifacts {
|
||||
private const val HEAD = 4096L
|
||||
|
||||
private class Mark(val size: Long, val head: String)
|
||||
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
|
||||
|
||||
fun markSteamLogs(dir: File, logs: File) {
|
||||
val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
|
||||
@@ -362,54 +240,23 @@ object SessionArtifacts {
|
||||
.firstOrNull { m -> heads.getOrPut(minOf(m.size, HEAD)) { head(src, m.size) } == m.head }?.size ?: 0L
|
||||
}
|
||||
|
||||
private fun copySteamLogs(
|
||||
context: Context,
|
||||
dir: File,
|
||||
record: Record,
|
||||
steamArch: String? = null,
|
||||
stopWhenSessionStarts: Boolean = false,
|
||||
) {
|
||||
private fun copySteamLogs(context: Context, dir: File, record: Record, steamArch: String? = null) {
|
||||
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
|
||||
if (!logs.isDirectory) return
|
||||
val out = File(dir, "steam").apply { mkdirs() }
|
||||
val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }
|
||||
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
|
||||
record.failed = record.failed || result.failed
|
||||
record.deferred = record.deferred || result.deferred
|
||||
copySessionLogs(logs, dir, out).forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
|
||||
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
|
||||
}
|
||||
|
||||
internal fun copySessionLogs(
|
||||
logs: File,
|
||||
dir: File,
|
||||
out: File,
|
||||
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
||||
): List<File> = copySessionLogsResult(logs, dir, out, openWriter) { false }.files
|
||||
|
||||
private fun copySessionLogsResult(
|
||||
logs: File,
|
||||
dir: File,
|
||||
out: File,
|
||||
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
||||
shouldStop: () -> Boolean,
|
||||
): CopyResult {
|
||||
internal fun copySessionLogs(logs: File, dir: File, out: File): List<File> {
|
||||
val marks = steamLogMarks(dir)
|
||||
val copied = ArrayList<File>()
|
||||
var failed = false
|
||||
var deferred = false
|
||||
val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false)
|
||||
for (src in sources) {
|
||||
if (shouldStop()) {
|
||||
failed = true
|
||||
deferred = true
|
||||
break
|
||||
}
|
||||
logs.listFiles { f -> f.isFile }?.forEach { src ->
|
||||
val size = src.length()
|
||||
val from = marks?.let { startOf(src, size, it) } ?: 0L
|
||||
if (marks != null && from == size || size - from >= MAX_STEAM_LOG) continue
|
||||
val dst = File(out, src.name)
|
||||
val staging = File(out, ".${src.name}.copy")
|
||||
if (marks != null && from == size || size - from >= MAX_STEAM_LOG) return@forEach
|
||||
try {
|
||||
val dst = File(out, src.name)
|
||||
src.inputStream().buffered().use { input ->
|
||||
var left = if (from > 0) from - 1 else 0L
|
||||
while (left > 0) {
|
||||
@@ -423,183 +270,49 @@ object SessionArtifacts {
|
||||
if (c < 0 || c == '\n'.code) break
|
||||
}
|
||||
}
|
||||
val complete = openWriter(staging).use { w -> scrubSteamLog(input, w, shouldStop) }
|
||||
if (!complete) {
|
||||
staging.delete()
|
||||
failed = true
|
||||
deferred = true
|
||||
dst.bufferedWriter().use { w ->
|
||||
input.bufferedReader().forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
|
||||
}
|
||||
}
|
||||
if (deferred) break
|
||||
Files.move(
|
||||
staging.toPath(),
|
||||
dst.toPath(),
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING,
|
||||
)
|
||||
copied += dst
|
||||
copied.add(dst)
|
||||
} catch (e: Exception) {
|
||||
staging.delete()
|
||||
Log.w(TAG, "could not scrub ${src.name}", e)
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
return CopyResult(copied, failed, deferred)
|
||||
}
|
||||
|
||||
private fun scrubSteamLog(
|
||||
input: java.io.InputStream,
|
||||
out: java.io.Writer,
|
||||
shouldStop: () -> Boolean,
|
||||
): Boolean {
|
||||
input.reader().use { reader ->
|
||||
val chunk = CharArray(8192)
|
||||
val line = StringBuilder(4096)
|
||||
var oversized = false
|
||||
var pendingContent = false
|
||||
var pendingCarriageReturn = false
|
||||
|
||||
fun emit() {
|
||||
out.write(if (oversized) LogRedactor.OVERSIZED_LINE else LogRedactor.redact(line.toString()))
|
||||
out.write("\n")
|
||||
line.setLength(0)
|
||||
oversized = false
|
||||
pendingContent = false
|
||||
}
|
||||
|
||||
while (true) {
|
||||
if (shouldStop()) return false
|
||||
val count = reader.read(chunk)
|
||||
if (count < 0) break
|
||||
if (shouldStop()) return false
|
||||
for (i in 0 until count) {
|
||||
if (shouldStop()) return false
|
||||
val char = chunk[i]
|
||||
if (pendingCarriageReturn) {
|
||||
emit()
|
||||
pendingCarriageReturn = false
|
||||
if (char == '\n') continue
|
||||
}
|
||||
when (char) {
|
||||
'\r' -> pendingCarriageReturn = true
|
||||
'\n' -> emit()
|
||||
else -> {
|
||||
pendingContent = true
|
||||
if (!oversized) {
|
||||
if (line.length < LogRedactor.MAX_LINE_LENGTH) line.append(char)
|
||||
else {
|
||||
line.setLength(0)
|
||||
oversized = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pendingCarriageReturn || pendingContent) {
|
||||
if (shouldStop()) return false
|
||||
emit()
|
||||
}
|
||||
}
|
||||
return true
|
||||
return copied
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun finishAbandoned(context: Context, beforeGuestStart: Boolean = false) {
|
||||
val stopWhenSessionStarts = !beforeGuestStart
|
||||
fun finishAbandoned(context: Context) {
|
||||
val parent = LinuxRuntime.logDir(context)
|
||||
val abandoned = parent.listFiles { f ->
|
||||
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists() && !inFlight(f)
|
||||
}?.sortedWith(SessionPaths.chronological) ?: return
|
||||
if (abandoned.isEmpty()) return
|
||||
val current = SessionPaths.current()
|
||||
val latestPreviousSession = SessionPaths.sessionFolders(context).lastOrNull { it != current }
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
for (dir in abandoned) {
|
||||
if (stopWhenSessionStarts && SessionState.running) break
|
||||
if (dir == current) continue
|
||||
if (beforeGuestStart && dir != latestPreviousSession) continue
|
||||
val newest = dir == latestPreviousSession
|
||||
abandoned.forEachIndexed { i, dir ->
|
||||
if (dir == current) return@forEachIndexed
|
||||
val newest = i == abandoned.lastIndex
|
||||
try {
|
||||
val recoveryNote = File(dir, "ended-without-teardown.txt")
|
||||
val runtimeCaptured = File(dir, RECOVERY_RUNTIME_CAPTURED_MARKER)
|
||||
val runtimeExpired = File(dir, RECOVERY_RUNTIME_EXPIRED_MARKER)
|
||||
val recoveryPreviouslyAttempted = recoveryNote.exists()
|
||||
val recoveryAttempted = recoveryPreviouslyAttempted &&
|
||||
(runtimeCaptured.exists() || runtimeExpired.exists() || !beforeGuestStart)
|
||||
if (!recoveryAttempted) {
|
||||
recoveryNote.writeText(
|
||||
"This session's process ended without running its own teardown - killed by\n" +
|
||||
"Android, a native crash, or the device going down - so the files below were\n" +
|
||||
"gathered when the app next started, at ${now()}.\n" +
|
||||
"The logs written during the session (session.log, app.log, wayland.log,\n" +
|
||||
"audio.log, device.txt) were on disk already and are as they were left.\n" +
|
||||
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
|
||||
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
|
||||
"session died of a crash, the entry is in there unless the device rebooted.\n"
|
||||
)
|
||||
}
|
||||
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() &&
|
||||
(runtimeExpired.exists() || !beforeGuestStart) &&
|
||||
!recoveryNote.readText().contains("runtime capture did not finish")) {
|
||||
recoveryNote.appendText(
|
||||
"Steam's logs and VAC evidence are not included: runtime capture did not finish " +
|
||||
"before its evidence expired.\n"
|
||||
)
|
||||
}
|
||||
if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() && !beforeGuestStart) {
|
||||
runtimeExpired.writeText("runtime evidence no longer belongs to this session, at ${now()}\n")
|
||||
}
|
||||
File(dir, "ended-without-teardown.txt").writeText(
|
||||
"This session's process ended without running its own teardown - killed by\n" +
|
||||
"Android, a native crash, or the device going down - so the files below were\n" +
|
||||
"gathered when the app next started, at ${now()}.\n" +
|
||||
"The logs written during the session (session.log, app.log, wayland.log,\n" +
|
||||
"audio.log, device.txt) were on disk already and are as they were left.\n" +
|
||||
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
|
||||
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
|
||||
"session died of a crash, the entry is in there unless the device rebooted.\n"
|
||||
)
|
||||
val record = Record(dir)
|
||||
if (newest && !recoveryAttempted) {
|
||||
copySteamLogs(
|
||||
context,
|
||||
dir,
|
||||
record,
|
||||
steamArch = recordedClient(dir),
|
||||
stopWhenSessionStarts = stopWhenSessionStarts,
|
||||
)
|
||||
if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) {
|
||||
if (!record.failed && VacDiagnostics.collect(context, dir)) {
|
||||
try {
|
||||
runtimeCaptured.writeText("collected at ${now()}\n")
|
||||
} catch (e: Exception) {
|
||||
record.failed = true
|
||||
if (beforeGuestStart) {
|
||||
runtimeExpired.writeText("runtime capture marker failed, at ${now()}\n")
|
||||
}
|
||||
Log.w(TAG, "could not mark runtime capture for $dir", e)
|
||||
}
|
||||
} else {
|
||||
record.failed = true
|
||||
if (beforeGuestStart) {
|
||||
runtimeExpired.writeText("runtime capture failed, at ${now()}\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (record.deferred || stopWhenSessionStarts && SessionState.running) {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
markScrubbed(record)
|
||||
break
|
||||
}
|
||||
val crashLog = File(dir, "crash.log")
|
||||
if (!crashLog.exists()) {
|
||||
SessionLogCapture.dumpCrashBuffer(crashLog)
|
||||
}
|
||||
if (stopWhenSessionStarts && SessionState.running) {
|
||||
record.failed = true
|
||||
record.deferred = true
|
||||
markScrubbed(record)
|
||||
break
|
||||
if (newest) {
|
||||
copySteamLogs(context, dir, record, recordedClient(dir))
|
||||
VacDiagnostics.collect(context, dir)
|
||||
}
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
|
||||
if (beforeGuestStart) return
|
||||
val scrubbed = scrubTree(record) { stopWhenSessionStarts && SessionState.running }
|
||||
val marked = markScrubbed(scrubbed)
|
||||
if (scrubbed.deferred) break
|
||||
if (!marked) continue
|
||||
markScrubbed(scrubTree(record))
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
|
||||
Log.i(TAG, "finished the abandoned session folder $dir")
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
enum class SessionLaunchFailure {
|
||||
STEAM_ILLEGAL_INSTRUCTION,
|
||||
VULKAN_DEVICE_MISSING;
|
||||
|
||||
companion object {
|
||||
private val ANSI = Regex("\u001b\\[[0-?]*[ -/]*[@-~]")
|
||||
private val STEAM_EXIT = Regex("== steam exited rc=(\\d+)")
|
||||
|
||||
fun find(lines: Sequence<String>): SessionLaunchFailure? {
|
||||
var steamStarted = false
|
||||
var illegalInstruction = false
|
||||
var missingDevice = false
|
||||
lines.forEach { raw ->
|
||||
val line = ANSI.replace(raw, "").trim()
|
||||
when {
|
||||
line.startsWith("== droiddeck-session ") -> {
|
||||
steamStarted = false
|
||||
illegalInstruction = false
|
||||
missingDevice = false
|
||||
}
|
||||
line.startsWith("== STEP ") && line.contains("starting the Steam client") -> {
|
||||
steamStarted = true
|
||||
illegalInstruction = false
|
||||
}
|
||||
STEAM_EXIT.matches(line) && steamStarted ->
|
||||
illegalInstruction = STEAM_EXIT.matchEntire(line)?.groupValues?.get(1) == "132"
|
||||
line.startsWith("[gamescope]") && line.contains("vulkan:") -> when {
|
||||
line.contains("failed to find physical device") -> missingDevice = true
|
||||
line.contains("selecting physical device") -> missingDevice = false
|
||||
}
|
||||
}
|
||||
}
|
||||
return when {
|
||||
illegalInstruction -> STEAM_ILLEGAL_INSTRUCTION
|
||||
missingDevice -> VULKAN_DEVICE_MISSING
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,10 +44,6 @@ object SessionPaths {
|
||||
|
||||
fun current(): File? = dir
|
||||
|
||||
/** Whether the current session folder will survive teardown. No session means the next one can retain logs. */
|
||||
fun currentSessionLogsRetained(context: Context): Boolean =
|
||||
dir?.let { it.parentFile == SessionFiles.logDirectory(context) } ?: true
|
||||
|
||||
fun lastEnded(): File? = ended?.takeIf { it.isDirectory }
|
||||
|
||||
@Synchronized
|
||||
|
||||
@@ -255,16 +255,6 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("backActionsInverted", inverted).apply()
|
||||
}
|
||||
|
||||
val BACK_DOUBLE_TAP_MS_OPTIONS = (100..800 step 100).toList()
|
||||
|
||||
fun backDoubleTapMs(context: Context): Int =
|
||||
prefs(context).getInt("backDoubleTapMs", 500).takeIf { it in BACK_DOUBLE_TAP_MS_OPTIONS } ?: 500
|
||||
|
||||
fun setBackDoubleTapMs(context: Context, ms: Int) {
|
||||
require(ms in BACK_DOUBLE_TAP_MS_OPTIONS)
|
||||
prefs(context).edit().putInt("backDoubleTapMs", ms).apply()
|
||||
}
|
||||
|
||||
const val TOUCH_AUTO = "auto"
|
||||
const val TOUCH_PAD = "touchpad"
|
||||
const val TOUCH_DIRECT = "direct"
|
||||
@@ -602,8 +592,6 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true)
|
||||
fun vsyncThread(context: Context): Boolean = prefs(context).getBoolean("vsyncThread", true)
|
||||
fun renderOnCommit(context: Context): Boolean = prefs(context).getBoolean("renderOnCommit", true)
|
||||
fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() }
|
||||
|
||||
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
|
||||
@@ -631,74 +619,8 @@ object SessionPrefs {
|
||||
fun logsEnabled(context: Context): Boolean =
|
||||
prefs(context).getBoolean("logs", true)
|
||||
|
||||
fun setLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) {
|
||||
setLogPreference(
|
||||
context,
|
||||
key = "logs",
|
||||
oldValue = logsEnabled(context),
|
||||
newValue = on,
|
||||
newEffective = on && gameDebugLogsEnabled(context) && SessionPaths.currentSessionLogsRetained(context),
|
||||
)
|
||||
}
|
||||
|
||||
/** Extra Proton, Wine and graphics diagnostics for the next game launch; off unless chosen. */
|
||||
fun gameDebugLogsEnabled(context: Context): Boolean =
|
||||
prefs(context).getBoolean("gameDebugLogsEnabled", false)
|
||||
|
||||
fun setGameDebugLogsEnabled(context: Context, on: Boolean): Boolean = synchronized(GameEnvironmentStore) {
|
||||
setLogPreference(
|
||||
context,
|
||||
key = "gameDebugLogsEnabled",
|
||||
oldValue = gameDebugLogsEnabled(context),
|
||||
newValue = on,
|
||||
newEffective = logsEnabled(context) && on && SessionPaths.currentSessionLogsRetained(context),
|
||||
)
|
||||
}
|
||||
|
||||
private fun setLogPreference(
|
||||
context: Context,
|
||||
key: String,
|
||||
oldValue: Boolean,
|
||||
newValue: Boolean,
|
||||
newEffective: Boolean,
|
||||
): Boolean {
|
||||
if (oldValue == newValue) return true
|
||||
val saved = prefs(context)
|
||||
val oldEffective = logsEnabled(context) && gameDebugLogsEnabled(context) &&
|
||||
SessionPaths.currentSessionLogsRetained(context)
|
||||
fun publish(value: Boolean) = GameEnvironmentStore.publish(context, gameDebugLogsOverride = value)
|
||||
if (oldEffective == newEffective) {
|
||||
if (saved.edit().putBoolean(key, newValue).commit()) return true
|
||||
saved.edit().putBoolean(key, oldValue).commit()
|
||||
return false
|
||||
}
|
||||
if (oldEffective && !newEffective) {
|
||||
try {
|
||||
publish(false)
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("GameEnvironment", "Could not disable game diagnostics", e)
|
||||
return false
|
||||
}
|
||||
if (saved.edit().putBoolean(key, newValue).commit()) return true
|
||||
saved.edit().putBoolean(key, oldValue).commit()
|
||||
runCatching { publish(oldEffective) }
|
||||
.onFailure { android.util.Log.e("GameEnvironment", "Could not restore game diagnostics", it) }
|
||||
return false
|
||||
}
|
||||
if (!saved.edit().putBoolean(key, newValue).commit()) {
|
||||
saved.edit().putBoolean(key, oldValue).commit()
|
||||
return false
|
||||
}
|
||||
return try {
|
||||
publish(newEffective)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
saved.edit().putBoolean(key, oldValue).commit()
|
||||
runCatching { publish(oldEffective) }
|
||||
.onFailure { android.util.Log.e("GameEnvironment", "Could not restore game diagnostics", it) }
|
||||
android.util.Log.e("GameEnvironment", "Could not update game diagnostics", e)
|
||||
false
|
||||
}
|
||||
fun setLogsEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("logs", on).apply()
|
||||
}
|
||||
|
||||
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
|
||||
@@ -1006,15 +928,22 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Performance mode: buffers go back to the game as soon as they are replaced
|
||||
* instead of once per refresh, and gamescope's WSI layer and winex11 reuse their per-present window checks.
|
||||
*/
|
||||
fun performanceMode(context: Context, mode: String): Boolean = prefs(context).getBoolean("performanceMode.$mode", false)
|
||||
|
||||
fun setPerformanceMode(context: Context, mode: String, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("performanceMode.$mode", on).apply()
|
||||
}
|
||||
|
||||
/** Compositor frame limit that releases buffers to the game unpaced. */
|
||||
const val FPS_UNPACED = -1
|
||||
|
||||
/**
|
||||
* Buffers go back to the game as soon as they are replaced instead of once per refresh;
|
||||
* Steam's Frame Limit in the Quick Access menu caps games. Mirroring still follows the glasses' refresh rate.
|
||||
*/
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int): Int =
|
||||
if (mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
|
||||
/** Mirroring still follows the glasses' refresh rate when Performance mode is on. */
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int, performanceMode: Boolean): Int =
|
||||
if (performanceMode && mirrorRefreshLimit <= 0) FPS_UNPACED else mirrorRefreshLimit
|
||||
|
||||
val upscalerChoices = listOf(
|
||||
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
|
||||
|
||||
@@ -91,7 +91,6 @@ class SessionService : Service() {
|
||||
private var screenOn = true
|
||||
private var sessionDisplayId = Display.DEFAULT_DISPLAY
|
||||
private var manualPauseRequested = false
|
||||
private var manualHold = false
|
||||
private var steamSleepToken: String? = null
|
||||
private var nativeSleepToken: String? = null
|
||||
private var nativeSleepReady = false
|
||||
@@ -275,11 +274,7 @@ class SessionService : Service() {
|
||||
val hold = intent?.getBooleanExtra(EXTRA_HOLD, false) == true
|
||||
if (hold == signInHold) return START_NOT_STICKY
|
||||
signInHold = hold
|
||||
if (hold) {
|
||||
manualPauseRequested = false
|
||||
manualHold = false
|
||||
SessionState.manualPause = false
|
||||
}
|
||||
if (hold) manualPauseRequested = false
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
@@ -309,14 +304,6 @@ class SessionService : Service() {
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_PAUSE_NOW -> {
|
||||
if (!SessionState.running || SessionState.suspended || signInHold) return START_NOT_STICKY
|
||||
manualHold = true
|
||||
SessionState.manualPause = true
|
||||
suspendAttemptFailed = false
|
||||
updateSuspendPolicy()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
ACTION_RESUME -> {
|
||||
resumeSession()
|
||||
return START_NOT_STICKY
|
||||
@@ -359,8 +346,6 @@ class SessionService : Service() {
|
||||
SessionState.resumeRequested = false
|
||||
SessionState.resuming = false
|
||||
SessionState.resumeFailed = false
|
||||
manualHold = false
|
||||
SessionState.manualPause = false
|
||||
SessionState.pipActive = false
|
||||
pipTask = false
|
||||
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
|
||||
@@ -400,10 +385,10 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
private fun collectSessionArtifacts(dir: File, steamArch: String?) {
|
||||
SessionLogCapture.stopFor(dir)
|
||||
try {
|
||||
SessionArtifacts.collect(this, dir, "session stopped", steamArch)
|
||||
} finally {
|
||||
SessionLogCapture.stopFor(dir)
|
||||
SessionPaths.release(this, dir)
|
||||
}
|
||||
}
|
||||
@@ -476,20 +461,13 @@ class SessionService : Service() {
|
||||
SessionFiles.stage(this, root, startsSession = true)
|
||||
// Earlier sessions' reports still read the Steam logs and VAC marker this session replaces.
|
||||
SessionArtifacts.awaitCollections()
|
||||
SessionArtifacts.finishAbandoned(this, beforeGuestStart = true)
|
||||
SessionArtifacts.finishAbandoned(this)
|
||||
VacDiagnostics.arm(this)
|
||||
com.droiddeck.launcher.agent.AgentGuest.reset(this)
|
||||
com.droiddeck.launcher.stores.gog.GogComet.begin()
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.start(this)
|
||||
|
||||
val sessionDir = openSessionFolder()
|
||||
try {
|
||||
GameEnvironmentStore.publish(this)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "could not publish the game environment", e)
|
||||
stopSession(-1)
|
||||
return
|
||||
}
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
val prootLine = "== proot: ${LinuxRuntime.prootBinary(this).path} (${LinuxRuntime.prootSource(this)})"
|
||||
Log.i(TAG, prootLine)
|
||||
@@ -502,9 +480,6 @@ class SessionService : Service() {
|
||||
val size = SessionState.outputSize
|
||||
val guest = ArrayList<String>()
|
||||
val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
runCatching { ComponentsManager.republish(this) }
|
||||
.onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") }
|
||||
.onFailure { Log.w(TAG, "component selections", it) }
|
||||
if (steamHere) {
|
||||
runCatching { ComponentsManager.ensureForcedPackages(this) }
|
||||
.onSuccess { if (it != null) Log.i(TAG, it) }
|
||||
@@ -532,13 +507,16 @@ class SessionService : Service() {
|
||||
guest.add("DXVK_HDR=1")
|
||||
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
|
||||
}
|
||||
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long.
|
||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
|
||||
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
|
||||
// gamescope turns buffers around slower than an uncapped game draws; more images keep it drawing.
|
||||
// The WSI layer goes back to its default count while Steam's Frame Limit holds the game.
|
||||
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
|
||||
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
|
||||
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long; 0 checks on every present.
|
||||
val windowCheckMs = if (SessionState.performanceMode) 100 else 0
|
||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=$windowCheckMs")
|
||||
guest.add("WINE_OFFSCREEN_CHECK_MS=$windowCheckMs")
|
||||
if (SessionState.performanceMode) {
|
||||
// gamescope turns buffers around slower than an unpaced game draws; more images keep it drawing.
|
||||
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
|
||||
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
|
||||
}
|
||||
Log.i(TAG, "performance mode " + (if (SessionState.performanceMode) "on" else "off"))
|
||||
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
|
||||
guest.add("BL_LOG=" + sessionLog.path)
|
||||
guest.add("BL_DEBUG_DIR=" + sessionDir.path)
|
||||
@@ -1354,8 +1332,6 @@ class SessionService : Service() {
|
||||
if (panelVisible) activityVisible = true
|
||||
screenOn = readScreenOn()
|
||||
manualPauseRequested = false
|
||||
manualHold = false
|
||||
SessionState.manualPause = false
|
||||
suspendDownloadNow = false
|
||||
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake()
|
||||
completeNativeSleep()
|
||||
@@ -1563,12 +1539,12 @@ class SessionService : Service() {
|
||||
manualPauseRequested = false
|
||||
}
|
||||
val controller = suspendController ?: return
|
||||
if (downloadsBlockingSuspend && !manualHold) acquireLocks()
|
||||
val steamPause = SessionState.mode == MODE_STEAM && (manualHold || !downloadsBlockingSuspend && when (suspendPolicy) {
|
||||
if (downloadsBlockingSuspend) acquireLocks()
|
||||
val steamPause = SessionState.mode == MODE_STEAM && !downloadsBlockingSuspend && when (suspendPolicy) {
|
||||
SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE -> hidden
|
||||
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested
|
||||
else -> false
|
||||
})
|
||||
}
|
||||
if (!steamPause) {
|
||||
completeNativeSleep()
|
||||
} else if (nativeSleepToken == null && steamSleepToken == null &&
|
||||
@@ -1576,15 +1552,12 @@ class SessionService : Service() {
|
||||
prepareNativeSleep()
|
||||
}
|
||||
val prepared = SessionState.mode != MODE_STEAM || nativeSleepReady
|
||||
val shouldSuspend = steamSleepToken != null || (manualHold && prepared) || when (suspendPolicy) {
|
||||
val shouldSuspend = steamSleepToken != null || when (suspendPolicy) {
|
||||
SessionPrefs.SUSPEND_AUTO -> hidden && prepared && !downloadsBlockingSuspend
|
||||
SessionPrefs.SUSPEND_NATIVE -> hidden && nativeSleepReady && !downloadsBlockingSuspend
|
||||
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && prepared && !downloadsBlockingSuspend
|
||||
else -> false
|
||||
}
|
||||
// A frozen game never sends the stop for a held rumble, so the keepalive would run on.
|
||||
val quietRumble = !screenOn || shouldSuspend || SessionState.suspended
|
||||
components.forEach { (it as? RumbleComponent)?.quiet(quietRumble) }
|
||||
if (freezePending && !shouldSuspend && !freezeCancelled) {
|
||||
freezeCancelled = true
|
||||
controller.cancelFreeze()
|
||||
@@ -1624,8 +1597,6 @@ class SessionService : Service() {
|
||||
SessionEvents.record("session.suspend_cancelled")
|
||||
} else {
|
||||
suspendAttemptFailed = true
|
||||
manualHold = false
|
||||
SessionState.manualPause = false
|
||||
Log.w(TAG, "could not confirm that the session stopped")
|
||||
}
|
||||
}
|
||||
@@ -1674,7 +1645,7 @@ class SessionService : Service() {
|
||||
}
|
||||
|
||||
private fun resumeSteamSleepOnReturn() {
|
||||
if (!manualHold && suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) {
|
||||
if (suspendPolicy in setOf(SessionPrefs.SUSPEND_AUTO, SessionPrefs.SUSPEND_NATIVE) && hasVisibleSurface) {
|
||||
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake()
|
||||
completeNativeSleep()
|
||||
completeSteamSleep()
|
||||
@@ -1732,48 +1703,42 @@ class SessionService : Service() {
|
||||
}.onFailure { Log.w(TAG, "could not request Steam wake", it) }
|
||||
}
|
||||
|
||||
private fun finishSessionStop(status: Int, stoppedGen: Int, afterStopped: () -> Unit = {}) {
|
||||
private fun finishSessionStop(status: Int, stoppedGen: Int) {
|
||||
mainHandler.post {
|
||||
try {
|
||||
if (stoppedGen != sessionGen || SessionState.running) {
|
||||
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
|
||||
return@post
|
||||
}
|
||||
SessionState.suspended = false
|
||||
SessionState.resumeRequested = false
|
||||
SessionState.resuming = false
|
||||
SessionState.resumeFailed = false
|
||||
manualHold = false
|
||||
SessionState.manualPause = false
|
||||
SessionState.pipActive = false
|
||||
pipTask = false
|
||||
SessionState.guestPid = -1
|
||||
com.droiddeck.launcher.agent.AgentGuest.stop()
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
|
||||
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
|
||||
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
|
||||
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
|
||||
releaseLocks()
|
||||
MemoryLog.stop()
|
||||
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
|
||||
if (status == 0) {
|
||||
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
|
||||
} else {
|
||||
val code = SessionState.failureCode ?: "GUEST_EXIT"
|
||||
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
|
||||
val failureStatus = SessionState.failureStatus ?: status
|
||||
SessionEvents.fail(code, message, failureStatus)
|
||||
}
|
||||
SessionState.steamVr = false
|
||||
com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart()
|
||||
com.droiddeck.launcher.glasses.Glasses.setVrActive(false)
|
||||
com.droiddeck.launcher.glasses.Glasses.set3dForVr(false)
|
||||
SessionState.notifyEnded(status)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
} finally {
|
||||
afterStopped()
|
||||
if (stoppedGen != sessionGen || SessionState.running) {
|
||||
Log.i(TAG, "session $stoppedGen finished stopping after a new one started")
|
||||
return@post
|
||||
}
|
||||
SessionState.suspended = false
|
||||
SessionState.resumeRequested = false
|
||||
SessionState.resuming = false
|
||||
SessionState.resumeFailed = false
|
||||
SessionState.pipActive = false
|
||||
pipTask = false
|
||||
SessionState.guestPid = -1
|
||||
com.droiddeck.launcher.agent.AgentGuest.stop()
|
||||
com.droiddeck.launcher.stores.StoreLaunchRequests.stop()
|
||||
Thread({ com.droiddeck.launcher.stores.CloudSaves.uploadAllDirty(applicationContext, "session-end", running = false) }, "cloud-session-end").start()
|
||||
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
|
||||
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
|
||||
releaseLocks()
|
||||
MemoryLog.stop()
|
||||
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
|
||||
if (status == 0) {
|
||||
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
|
||||
} else {
|
||||
val code = SessionState.failureCode ?: "GUEST_EXIT"
|
||||
val message = SessionState.failureMessage ?: "Session guest exited with status $status"
|
||||
val failureStatus = SessionState.failureStatus ?: status
|
||||
SessionEvents.fail(code, message, failureStatus)
|
||||
}
|
||||
SessionState.steamVr = false
|
||||
com.droiddeck.launcher.glasses.Glasses.cancelSteamVrStart()
|
||||
com.droiddeck.launcher.glasses.Glasses.setVrActive(false)
|
||||
com.droiddeck.launcher.glasses.Glasses.set3dForVr(false)
|
||||
SessionState.notifyEnded(status)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1804,9 +1769,7 @@ class SessionService : Service() {
|
||||
SessionEvents.record("guest.exited", mapOf("status" to status))
|
||||
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
|
||||
SessionState.running = false
|
||||
val ended = SessionPaths.take()
|
||||
if (ended != null) SessionArtifacts.collectionStarted(ended)
|
||||
ended to SessionState.steamClientArch
|
||||
SessionPaths.take() to SessionState.steamClientArch
|
||||
}
|
||||
SessionState.micAvailable = false
|
||||
SessionState.micEnabled = false
|
||||
@@ -1835,6 +1798,8 @@ class SessionService : Service() {
|
||||
suspendController = null
|
||||
if (ended != null) {
|
||||
VacDiagnostics.snapshot(this, ended)
|
||||
SessionArtifacts.collectionStarted(ended)
|
||||
Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
|
||||
}
|
||||
components.reversed().forEach {
|
||||
try {
|
||||
@@ -1844,9 +1809,6 @@ class SessionService : Service() {
|
||||
}
|
||||
}
|
||||
components.clear()
|
||||
val collectEnded = {
|
||||
if (ended != null) Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start()
|
||||
}
|
||||
FakeInputWriter.releaseAllRingSlots()
|
||||
com.droiddeck.launcher.input.SteamTouchDevice.release()
|
||||
val steamClientMayRun = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP
|
||||
@@ -1858,13 +1820,13 @@ class SessionService : Service() {
|
||||
auxiliary.forEach { (pid, started) -> teardown(pid, started) }
|
||||
if (prootPid > 1) teardown(prootPid)
|
||||
killGuestLeftovers()
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
finishSessionStop(status, stoppedGen)
|
||||
if (launcherEnded) importLauncherGames()
|
||||
}, "session-teardown").start()
|
||||
} else {
|
||||
Thread({
|
||||
com.droiddeck.launcher.stores.gog.GogComet.end(stoppedSession)
|
||||
finishSessionStop(status, stoppedGen, collectEnded)
|
||||
finishSessionStop(status, stoppedGen)
|
||||
if (launcherEnded) importLauncherGames()
|
||||
}, "gog-session-stop").start()
|
||||
}
|
||||
@@ -2103,7 +2065,6 @@ class SessionService : Service() {
|
||||
const val ACTION_STOP = "com.droiddeck.launcher.STOP_SESSION"
|
||||
const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION"
|
||||
const val ACTION_SUSPEND_NOW = "com.droiddeck.launcher.SUSPEND_NOW"
|
||||
private const val ACTION_PAUSE_NOW = "com.droiddeck.launcher.PAUSE_NOW"
|
||||
private const val ACTION_PIP_BEGIN = "com.droiddeck.launcher.PIP_BEGIN"
|
||||
const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME"
|
||||
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
|
||||
@@ -2178,7 +2139,6 @@ class SessionService : Service() {
|
||||
fun stop(context: Context) {
|
||||
if (!SessionState.running) {
|
||||
SessionState.stopRequested = true
|
||||
SessionState.installCancellation?.cancel()
|
||||
return
|
||||
}
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP))
|
||||
@@ -2224,10 +2184,6 @@ class SessionService : Service() {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SIGN_IN_HOLD).putExtra(EXTRA_HOLD, hold))
|
||||
}
|
||||
|
||||
fun pause(context: Context) {
|
||||
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PAUSE_NOW))
|
||||
}
|
||||
|
||||
fun resume(context: Context) {
|
||||
if (!SessionState.running) return
|
||||
if (SessionState.suspended) SessionState.resumeRequested = true
|
||||
|
||||
@@ -37,9 +37,6 @@ object SessionState {
|
||||
@Volatile
|
||||
var installing: String? = null
|
||||
|
||||
@Volatile
|
||||
var installCancellation: com.droiddeck.launcher.core.Downloader.Cancellation? = null
|
||||
|
||||
@Volatile
|
||||
var stopRequested = false
|
||||
|
||||
@@ -56,7 +53,6 @@ object SessionState {
|
||||
var resuming by mutableStateOf(false)
|
||||
var resumeFailures by mutableIntStateOf(0)
|
||||
var resumeFailed by mutableStateOf(false)
|
||||
var manualPause by mutableStateOf(false)
|
||||
@Volatile var pipActive = false
|
||||
@Volatile
|
||||
var program: String? = null
|
||||
@@ -107,6 +103,9 @@ object SessionState {
|
||||
@Volatile
|
||||
var upscaleRatio: Float = 0f
|
||||
|
||||
@Volatile
|
||||
var performanceMode = false
|
||||
|
||||
@Volatile
|
||||
var firstFrameSeen = false
|
||||
|
||||
|
||||
@@ -14,14 +14,14 @@ object SettingsReset {
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
|
||||
"stretch16x9", "picturePosition",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen",
|
||||
@@ -37,7 +37,6 @@ object SettingsReset {
|
||||
internal fun isSessionSetting(key: String) = key in SESSION_KEYS || SESSION_PREFIXES.any { key.startsWith(it) }
|
||||
|
||||
fun resetAll(context: Context, gameProfiles: Boolean, gameScopes: Collection<String> = emptyList()): Boolean {
|
||||
if (!SessionPrefs.setGameDebugLogsEnabled(context, false)) return false
|
||||
var ok = true
|
||||
val session = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
session.edit().apply { session.all.keys.filter { isSessionSetting(it) }.forEach { remove(it) } }.commit()
|
||||
|
||||
@@ -68,13 +68,13 @@ object VacDiagnostics {
|
||||
}
|
||||
}
|
||||
|
||||
fun collect(context: Context, dir: File): Boolean {
|
||||
fun collect(context: Context, dir: File) {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val kept = File(dir, SNAPSHOT_MARKER).takeIf { it.isFile }
|
||||
val marker = kept ?: File(root, MARKER)
|
||||
val launchList = if (kept != null) File(dir, SNAPSHOT_LAUNCHES) else File(root, LAUNCHES)
|
||||
if (!marker.isFile) return true
|
||||
return try {
|
||||
if (!marker.isFile) return
|
||||
try {
|
||||
val armed = marker.readLines().map { it.trim() }
|
||||
val since = (armed.getOrNull(0)?.toLongOrNull() ?: 0L) * 1000 - 5_000
|
||||
val arch = armed.getOrNull(1)?.takeIf { it.isNotEmpty() } ?: SessionPrefs.steamClientArch(context)
|
||||
@@ -125,10 +125,8 @@ object VacDiagnostics {
|
||||
File(dir, SNAPSHOT_MARKER).delete()
|
||||
File(dir, SNAPSHOT_LAUNCHES).delete()
|
||||
Log.i(TAG, "VAC diagnostics: ${consoles.size} console log(s), ${steamHits.size} client VAC line(s), into $dir")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "collecting VAC diagnostics", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ class StoreGameSidecar(
|
||||
val file = File(folder, FILE_NAME)
|
||||
val tmp = File(folder, "$FILE_NAME.tmp")
|
||||
tmp.writeText(toJson().toString(2))
|
||||
if (!tmp.renameTo(file)) java.nio.file.Files.move(tmp.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
if (!tmp.renameTo(file)) { file.delete(); tmp.renameTo(file) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -30,12 +30,7 @@ object StoreInstalls {
|
||||
it.write(before.copy(state = StoreGameSidecar.STATE_UPDATING, installVersion = "").toJson().toString(2).toByteArray(Charsets.UTF_8))
|
||||
it.fd.sync()
|
||||
}
|
||||
val record = StoreGameSidecar.file(folder).toPath()
|
||||
try {
|
||||
Files.move(stage.toPath(), record, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
|
||||
} catch (e: java.nio.file.AtomicMoveNotSupportedException) {
|
||||
Files.move(stage.toPath(), record, StandardCopyOption.REPLACE_EXISTING)
|
||||
}
|
||||
Files.move(stage.toPath(), StoreGameSidecar.file(folder).toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
|
||||
} finally {
|
||||
stage.delete()
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ object StoresState {
|
||||
|
||||
fun detailItem(store: Store, id: String): CatalogItem? = detailCatalogItem(
|
||||
store, id, library[store].orEmpty(),
|
||||
found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items + com.droiddeck.launcher.stores.itch.ItchCollections.items() else emptyList(),
|
||||
found[store].orEmpty() + if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchBrowseState.items else emptyList(),
|
||||
shelves[store],
|
||||
)
|
||||
|
||||
@@ -191,10 +191,6 @@ object StoresState {
|
||||
backend?.signOut(app)
|
||||
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) }
|
||||
else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store)
|
||||
if (store == Store.ITCH) {
|
||||
com.droiddeck.launcher.stores.itch.ItchCollections.clear()
|
||||
com.droiddeck.launcher.stores.itch.ItchUpdates.clear(app)
|
||||
}
|
||||
main.post {
|
||||
if (store == Store.XBOX && StoreAccounts.signedInAs(app, store) != null) return@post
|
||||
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store); libraryAsked.remove(store)
|
||||
@@ -285,7 +281,6 @@ object StoresState {
|
||||
main.post {
|
||||
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
|
||||
uninstalling.remove(key)
|
||||
if (game.sidecar.store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchUpdates.applied(app, key)
|
||||
}
|
||||
})
|
||||
main.post(onDone)
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.droiddeck.launcher.stores.gfn
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import org.json.JSONObject
|
||||
import java.io.BufferedWriter
|
||||
import java.io.File
|
||||
import java.util.concurrent.CompletableFuture
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.TimeoutException
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
class GfnError(val code: String, message: String) : Exception(message)
|
||||
|
||||
/**
|
||||
* OpenNOW's core service (external/opennow, MIT, by Zortos) as a child process: sign-in, the
|
||||
* GeForce NOW catalog and CloudMatch sessions, spoken as newline-delimited JSON on its stdin and
|
||||
* stdout (external/opennow/docs/core-protocol.md). It ships as libopennowcore.so in the native
|
||||
* library directory, the one place the app may run programs from.
|
||||
*/
|
||||
object GfnCore {
|
||||
private const val TAG = "GfnCore"
|
||||
private const val PROTOCOL_VERSION = 5
|
||||
private const val BINARY = "libopennowcore.so"
|
||||
|
||||
private var process: Process? = null
|
||||
private var writer: BufferedWriter? = null
|
||||
private val pending = ConcurrentHashMap<String, CompletableFuture<JSONObject>>()
|
||||
private val nextId = AtomicLong(1)
|
||||
private val listeners = java.util.concurrent.CopyOnWriteArrayList<(String, JSONObject) -> Unit>()
|
||||
|
||||
/** The core runs in the :gfn process; other processes reach it through [GfnCoreService]. */
|
||||
private val inCoreProcess: Boolean by lazy {
|
||||
val name = if (android.os.Build.VERSION.SDK_INT >= 28) android.app.Application.getProcessName()
|
||||
else runCatching { File("/proc/self/cmdline").readText().trimEnd('\u0000') }.getOrDefault("")
|
||||
name.endsWith(":gfn")
|
||||
}
|
||||
|
||||
fun addListener(listener: (String, JSONObject) -> Unit) { listeners += listener }
|
||||
fun removeListener(listener: (String, JSONObject) -> Unit) { listeners -= listener }
|
||||
|
||||
/** Starts the core if it is not running, then checks the protocol and turns its reporting off. */
|
||||
@Synchronized
|
||||
fun ensureStarted(context: Context) {
|
||||
if (process?.isAlive == true) return
|
||||
val app = context.applicationContext
|
||||
val binary = File(app.applicationInfo.nativeLibraryDir, BINARY)
|
||||
check(binary.isFile) { "This build has no GeForce NOW core ($BINARY)" }
|
||||
val dataDir = File(app.filesDir, "gfn/core").apply { mkdirs() }
|
||||
val logFile = File(app.filesDir, "gfn/core.log")
|
||||
val started = ProcessBuilder(binary.path, "--data-dir", dataDir.path)
|
||||
.directory(dataDir)
|
||||
.redirectError(ProcessBuilder.Redirect.appendTo(logFile))
|
||||
.start()
|
||||
process = started
|
||||
writer = started.outputStream.bufferedWriter()
|
||||
Thread({ readLoop(started) }, "gfn-core-out").apply { isDaemon = true; start() }
|
||||
Log.i(TAG, "core started")
|
||||
request(app, "core.hello", JSONObject()
|
||||
.put("protocolVersion", PROTOCOL_VERSION)
|
||||
.put("shell", "qt")
|
||||
.put("shellVersion", "droiddeck"), timeoutMs = 10_000)
|
||||
// DroidDeck never sends OpenNOW's analytics or crash reports anywhere.
|
||||
for ((key, value) in listOf("automaticBugReports" to "disabled", "errorReportingConsent" to "denied")) {
|
||||
runCatching { request(app, "settings.set", JSONObject().put("key", key).put("value", value)) }
|
||||
.onFailure { Log.w(TAG, "could not set $key: ${it.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
/** One request, answered with its `result` or thrown as [GfnError]. Blocking: call off the main thread. */
|
||||
fun request(context: Context, method: String, params: JSONObject = JSONObject(), timeoutMs: Long = 30_000): JSONObject {
|
||||
if (!inCoreProcess) return GfnRemote.request(context, method, params, timeoutMs)
|
||||
if (method != "core.hello") ensureStarted(context)
|
||||
val id = "dd-" + nextId.getAndIncrement()
|
||||
val answer = CompletableFuture<JSONObject>()
|
||||
pending[id] = answer
|
||||
try {
|
||||
val line = JSONObject().put("type", "request").put("id", id).put("method", method).put("params", params).toString()
|
||||
synchronized(this) {
|
||||
val out = writer ?: throw GfnError("core_stopped", "The GeForce NOW core is not running")
|
||||
out.write(line)
|
||||
out.newLine()
|
||||
out.flush()
|
||||
}
|
||||
val response = try {
|
||||
answer.get(timeoutMs, TimeUnit.MILLISECONDS)
|
||||
} catch (e: TimeoutException) {
|
||||
throw GfnError("timeout", "GeForce NOW did not answer in time ($method)")
|
||||
}
|
||||
if (response.optBoolean("ok")) return response.optJSONObject("result") ?: JSONObject()
|
||||
val error = response.optJSONObject("error")
|
||||
throw GfnError(error?.optString("code").orEmpty().ifEmpty { "error" },
|
||||
error?.optString("message").orEmpty().ifEmpty { "GeForce NOW request failed ($method)" })
|
||||
} finally {
|
||||
pending.remove(id)
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun stop() {
|
||||
runCatching { writer?.close() }
|
||||
process?.destroy()
|
||||
process = null
|
||||
writer = null
|
||||
pending.values.forEach { it.completeExceptionally(GfnError("core_stopped", "The GeForce NOW core stopped")) }
|
||||
pending.clear()
|
||||
}
|
||||
|
||||
private fun readLoop(running: Process) {
|
||||
try {
|
||||
running.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
val message = runCatching { JSONObject(line) }.getOrNull() ?: return@forEach
|
||||
when (message.optString("type")) {
|
||||
"event" -> {
|
||||
val name = message.optString("name")
|
||||
val payload = message.optJSONObject("payload") ?: JSONObject()
|
||||
listeners.forEach { runCatching { it(name, payload) } }
|
||||
}
|
||||
else -> pending[message.optString("id")]?.complete(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
Log.w(TAG, "core output ended")
|
||||
synchronized(this) {
|
||||
if (process === running) {
|
||||
process = null
|
||||
writer = null
|
||||
}
|
||||
}
|
||||
pending.values.forEach { it.completeExceptionally(GfnError("core_stopped", "The GeForce NOW core stopped")) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.droiddeck.launcher.stores.gfn
|
||||
|
||||
import android.app.Service
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.ServiceConnection
|
||||
import android.os.Binder
|
||||
import android.os.IBinder
|
||||
import android.os.Parcel
|
||||
import android.os.Process
|
||||
import android.os.RemoteException
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Hosts the one OpenNOW core in the :gfn process (the core locks its data directory, so a second
|
||||
* copy cannot run) and answers core requests from the Stores page in the main process.
|
||||
*/
|
||||
class GfnCoreService : Service() {
|
||||
private val binder = object : Binder() {
|
||||
override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean {
|
||||
if (code != REQUEST) return super.onTransact(code, data, reply, flags)
|
||||
if (getCallingUid() != Process.myUid() || reply == null) return false
|
||||
val method = data.readString().orEmpty()
|
||||
val params = runCatching { JSONObject(data.readString() ?: "{}") }.getOrDefault(JSONObject())
|
||||
val timeoutMs = data.readLong()
|
||||
try {
|
||||
val result = GfnCore.request(applicationContext, method, params, timeoutMs)
|
||||
reply.writeInt(1)
|
||||
reply.writeString(result.toString())
|
||||
} catch (e: Exception) {
|
||||
reply.writeInt(0)
|
||||
reply.writeString(JSONObject().put("code", (e as? GfnError)?.code ?: "error")
|
||||
.put("message", e.message ?: "GeForce NOW request failed ($method)").toString())
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder = binder
|
||||
|
||||
companion object {
|
||||
const val REQUEST = IBinder.FIRST_CALL_TRANSACTION
|
||||
}
|
||||
}
|
||||
|
||||
/** The main process's side of [GfnCoreService]. Blocking: call off the main thread. */
|
||||
internal object GfnRemote {
|
||||
private val lock = Object()
|
||||
@Volatile private var binder: IBinder? = null
|
||||
private var bound = false
|
||||
|
||||
private val connection = object : ServiceConnection {
|
||||
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
|
||||
synchronized(lock) { binder = service; lock.notifyAll() }
|
||||
}
|
||||
override fun onServiceDisconnected(name: ComponentName?) { binder = null }
|
||||
override fun onBindingDied(name: ComponentName?) { synchronized(lock) { binder = null; bound = false } }
|
||||
}
|
||||
|
||||
fun request(context: Context, method: String, params: JSONObject, timeoutMs: Long): JSONObject {
|
||||
val service = connect(context)
|
||||
val data = Parcel.obtain()
|
||||
val reply = Parcel.obtain()
|
||||
try {
|
||||
data.writeString(method)
|
||||
data.writeString(params.toString())
|
||||
data.writeLong(timeoutMs)
|
||||
if (!service.transact(GfnCoreService.REQUEST, data, reply, 0))
|
||||
throw GfnError("core_stopped", "The GeForce NOW service refused the request")
|
||||
val ok = reply.readInt() == 1
|
||||
val body = reply.readString() ?: "{}"
|
||||
if (ok) return JSONObject(body)
|
||||
val error = JSONObject(body)
|
||||
throw GfnError(error.optString("code").ifEmpty { "error" }, error.optString("message"))
|
||||
} catch (e: RemoteException) {
|
||||
binder = null
|
||||
throw GfnError("core_stopped", "The GeForce NOW service stopped")
|
||||
} finally {
|
||||
data.recycle()
|
||||
reply.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun connect(context: Context): IBinder {
|
||||
synchronized(lock) {
|
||||
binder?.takeIf { it.isBinderAlive }?.let { return it }
|
||||
val app = context.applicationContext
|
||||
if (!bound) bound = app.bindService(Intent(app, GfnCoreService::class.java), connection, Context.BIND_AUTO_CREATE)
|
||||
if (!bound) throw GfnError("core_stopped", "The GeForce NOW service could not start")
|
||||
val deadline = System.currentTimeMillis() + 15_000
|
||||
while (binder?.isBinderAlive != true) {
|
||||
val left = deadline - System.currentTimeMillis()
|
||||
if (left <= 0) throw GfnError("timeout", "The GeForce NOW service did not start")
|
||||
lock.wait(left)
|
||||
}
|
||||
return binder!!
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package com.droiddeck.launcher.stores.gfn
|
||||
|
||||
import android.app.AlertDialog
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.Gravity
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.WindowManager
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.TextView
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowInsetsControllerCompat
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** Plays one GeForce NOW game: books a seat, waits in the queue, then streams onto a SurfaceView. */
|
||||
class GfnPlayerActivity : ComponentActivity() {
|
||||
companion object {
|
||||
const val EXTRA_APP_ID = "appId"
|
||||
const val EXTRA_VARIANT_ID = "variantId"
|
||||
const val EXTRA_TITLE = "title"
|
||||
private const val TAG = "GfnPlayer"
|
||||
private const val DEADZONE = 0.15f
|
||||
}
|
||||
|
||||
private lateinit var status: TextView
|
||||
private val worker = Executors.newSingleThreadExecutor()
|
||||
private var streamer: GfnStreamer? = null
|
||||
@Volatile private var session: JSONObject? = null
|
||||
@Volatile private var closed = false
|
||||
@Volatile private var capabilities: JSONObject? = null
|
||||
private val helloWait = java.util.concurrent.CompletableFuture<JSONObject>()
|
||||
private val pads = Pads()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
WindowCompat.setDecorFitsSystemWindows(window, false)
|
||||
WindowInsetsControllerCompat(window, window.decorView).apply {
|
||||
hide(WindowInsetsCompat.Type.systemBars())
|
||||
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
|
||||
}
|
||||
val root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
||||
val surface = SurfaceView(this)
|
||||
surface.holder.addCallback(object : SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(holder: SurfaceHolder) = GfnStreamer.setSurface(holder.surface)
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) = GfnStreamer.setSurface(null)
|
||||
})
|
||||
root.addView(surface, FrameLayout.LayoutParams(-1, -1))
|
||||
status = TextView(this).apply {
|
||||
setTextColor(Color.WHITE)
|
||||
textSize = 18f
|
||||
gravity = Gravity.CENTER
|
||||
setPadding(48, 48, 48, 48)
|
||||
}
|
||||
root.addView(status, FrameLayout.LayoutParams(-1, -1))
|
||||
setContentView(root)
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() = confirmLeave()
|
||||
})
|
||||
val appId = intent.getStringExtra(EXTRA_APP_ID).orEmpty()
|
||||
val variantId = intent.getStringExtra(EXTRA_VARIANT_ID).orEmpty()
|
||||
val title = intent.getStringExtra(EXTRA_TITLE).orEmpty()
|
||||
show("Starting $title…")
|
||||
worker.execute {
|
||||
runCatching { play(appId, variantId, title) }.onFailure {
|
||||
Log.w(TAG, "could not start: ${it.message}")
|
||||
show(it.message ?: "GeForce NOW could not start this game.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun play(appId: String, variantId: String, title: String) {
|
||||
val engine = GfnStreamer(::onStreamerMessage)
|
||||
streamer = engine
|
||||
engine.send("hello", JSONObject().put("protocolVersion", 7))
|
||||
val caps = helloWait.get(10, java.util.concurrent.TimeUnit.SECONDS)
|
||||
capabilities = caps
|
||||
|
||||
val inspect = GfnCore.request(this, "catalog.launch.inspect", JSONObject().put("appId", appId).put("variantId", variantId))
|
||||
val decision = inspect.optJSONObject("decision")
|
||||
if (decision?.optString("status") != "ready") {
|
||||
show(decision?.optString("message").orEmpty().ifEmpty { "This game can't be started with this account." })
|
||||
return
|
||||
}
|
||||
show("Requesting a GeForce NOW seat…")
|
||||
var current = GfnCore.request(this, "session.create", JSONObject()
|
||||
.put("appId", variantId)
|
||||
.put("variantId", variantId)
|
||||
.put("catalogAppId", appId)
|
||||
.put("scope", inspect.opt("scope"))
|
||||
.put("title", title)
|
||||
.put("runtimeCapabilities", caps), timeoutMs = 60_000)
|
||||
current = current.optJSONObject("session") ?: current
|
||||
session = current
|
||||
while (!closed && !ready(current)) {
|
||||
val position = current.optInt("queuePosition", 0)
|
||||
show(if (position > 0) "In the queue: position $position" else "Preparing your seat…")
|
||||
Thread.sleep(2_000)
|
||||
val polled = GfnCore.request(this, "session.poll", JSONObject()
|
||||
.put("sessionId", current.opt("sessionId"))
|
||||
.put("streamingBaseUrl", current.opt("streamingBaseUrl")), timeoutMs = 35_000)
|
||||
current = polled.optJSONObject("session") ?: polled
|
||||
session = current
|
||||
if (current.optString("phase") == "failed") {
|
||||
show("GeForce NOW could not prepare this session.")
|
||||
return
|
||||
}
|
||||
}
|
||||
if (closed) return
|
||||
show("Connecting…")
|
||||
val prepared = GfnCore.request(this, "streamer.prepare",
|
||||
JSONObject().put("session", current).put("runtimeCapabilities", caps))
|
||||
prepared.optJSONObject("session")?.let { session = it }
|
||||
val context = prepared.optJSONObject("context") ?: error("GeForce NOW returned no stream context")
|
||||
engine.send("start", JSONObject().put("context", context).put("microphoneEnabled", false))
|
||||
}
|
||||
|
||||
private fun ready(session: JSONObject): Boolean {
|
||||
val phase = session.optString("phase")
|
||||
return phase == "ready" || phase == "streaming" || session.optInt("status", 0) >= 2
|
||||
}
|
||||
|
||||
private fun onStreamerMessage(message: JSONObject) {
|
||||
when (message.optString("type")) {
|
||||
"ready" -> message.optJSONObject("capabilities")?.let { helloWait.complete(it) }
|
||||
"error" -> {
|
||||
Log.w(TAG, "streamer error ${message.optString("code")}: ${message.optString("message")}")
|
||||
show(message.optString("message").ifEmpty { "The stream stopped." })
|
||||
}
|
||||
"status" -> when (message.optString("event")) {
|
||||
"first-frame" -> runOnUiThread { status.visibility = android.view.View.GONE }
|
||||
}
|
||||
"stopped" -> show("The stream ended.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun show(text: String) = runOnUiThread {
|
||||
status.text = text
|
||||
status.visibility = android.view.View.VISIBLE
|
||||
}
|
||||
|
||||
private fun confirmLeave() {
|
||||
AlertDialog.Builder(this)
|
||||
.setTitle("Leave the game?")
|
||||
.setMessage("This ends your GeForce NOW session.")
|
||||
.setPositiveButton("Leave") { _, _ -> finish() }
|
||||
.setNegativeButton("Keep playing", null)
|
||||
.show()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
closed = true
|
||||
val engine = streamer
|
||||
val active = session
|
||||
streamer = null
|
||||
Thread({
|
||||
runCatching { engine?.send("stop") }
|
||||
if (active != null) {
|
||||
runCatching {
|
||||
GfnCore.request(applicationContext, "session.stop", JSONObject()
|
||||
.put("sessionId", active.opt("sessionId"))
|
||||
.put("streamingBaseUrl", active.opt("streamingBaseUrl")))
|
||||
}.onFailure { Log.w(TAG, "session stop: ${it.message}") }
|
||||
}
|
||||
engine?.close()
|
||||
}, "gfn-leave").start()
|
||||
worker.shutdownNow()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
// --- controllers: Android gamepads in XInput layout, the same mapping OpenNOW uses ---
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (event.isFromSource(InputDevice.SOURCE_GAMEPAD) || event.isFromSource(InputDevice.SOURCE_JOYSTICK)) {
|
||||
val bit = buttonBit(event.keyCode)
|
||||
if (bit != 0) {
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) pads.press(event.deviceId, bit, true)
|
||||
else if (event.action == KeyEvent.ACTION_UP) pads.press(event.deviceId, bit, false)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
if (event.isFromSource(InputDevice.SOURCE_JOYSTICK) && event.action == MotionEvent.ACTION_MOVE) {
|
||||
pads.move(event)
|
||||
return true
|
||||
}
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
private fun buttonBit(keyCode: Int): Int = when (keyCode) {
|
||||
KeyEvent.KEYCODE_BUTTON_A -> 0x1000
|
||||
KeyEvent.KEYCODE_BUTTON_B -> 0x2000
|
||||
KeyEvent.KEYCODE_BUTTON_X -> 0x4000
|
||||
KeyEvent.KEYCODE_BUTTON_Y -> 0x8000
|
||||
KeyEvent.KEYCODE_BUTTON_SELECT -> 0x0020
|
||||
KeyEvent.KEYCODE_BUTTON_START -> 0x0010
|
||||
KeyEvent.KEYCODE_BUTTON_THUMBL -> 0x0040
|
||||
KeyEvent.KEYCODE_BUTTON_THUMBR -> 0x0080
|
||||
KeyEvent.KEYCODE_BUTTON_L1 -> 0x0100
|
||||
KeyEvent.KEYCODE_BUTTON_R1 -> 0x0200
|
||||
KeyEvent.KEYCODE_DPAD_UP -> 0x0001
|
||||
KeyEvent.KEYCODE_DPAD_DOWN -> 0x0002
|
||||
KeyEvent.KEYCODE_DPAD_LEFT -> 0x0004
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT -> 0x0008
|
||||
else -> 0
|
||||
}
|
||||
|
||||
private inner class Pads {
|
||||
private inner class Pad(val slot: Int) {
|
||||
var buttons = 0
|
||||
var hatButtons = 0
|
||||
var lt = 0
|
||||
var rt = 0
|
||||
var lx = 0
|
||||
var ly = 0
|
||||
var rx = 0
|
||||
var ry = 0
|
||||
}
|
||||
|
||||
private val bySlot = arrayOfNulls<Pad>(4)
|
||||
private val byDevice = HashMap<Int, Pad>()
|
||||
|
||||
@Synchronized
|
||||
private fun pad(deviceId: Int): Pad? = byDevice[deviceId] ?: run {
|
||||
val free = (0 until 4).firstOrNull { bySlot[it] == null } ?: return null
|
||||
Pad(free).also { bySlot[free] = it; byDevice[deviceId] = it }
|
||||
}
|
||||
|
||||
private fun connected(): Int = (0 until 4).filter { bySlot[it] != null }.fold(0) { bits, slot -> bits or (1 shl slot) or (1 shl (slot + 8)) }
|
||||
|
||||
fun press(deviceId: Int, bit: Int, down: Boolean) {
|
||||
val pad = pad(deviceId) ?: return
|
||||
pad.buttons = if (down) pad.buttons or bit else pad.buttons and bit.inv()
|
||||
send(pad)
|
||||
}
|
||||
|
||||
fun move(event: MotionEvent) {
|
||||
val pad = pad(event.deviceId) ?: return
|
||||
val (lx, ly) = stick(event.getAxisValue(MotionEvent.AXIS_X), event.getAxisValue(MotionEvent.AXIS_Y))
|
||||
val rightX = event.getAxisValue(MotionEvent.AXIS_Z).takeIf { it != 0f } ?: event.getAxisValue(MotionEvent.AXIS_RX)
|
||||
val rightY = event.getAxisValue(MotionEvent.AXIS_RZ).takeIf { it != 0f } ?: event.getAxisValue(MotionEvent.AXIS_RY)
|
||||
val (rx, ry) = stick(rightX, rightY)
|
||||
pad.lx = lx; pad.ly = ly; pad.rx = rx; pad.ry = ry
|
||||
pad.lt = trigger(maxOf(event.getAxisValue(MotionEvent.AXIS_LTRIGGER), event.getAxisValue(MotionEvent.AXIS_BRAKE)))
|
||||
pad.rt = trigger(maxOf(event.getAxisValue(MotionEvent.AXIS_RTRIGGER), event.getAxisValue(MotionEvent.AXIS_GAS)))
|
||||
val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X)
|
||||
val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
|
||||
pad.hatButtons = (if (hatY < -0.5f) 0x0001 else 0) or (if (hatY > 0.5f) 0x0002 else 0) or
|
||||
(if (hatX < -0.5f) 0x0004 else 0) or (if (hatX > 0.5f) 0x0008 else 0)
|
||||
send(pad)
|
||||
}
|
||||
|
||||
/** Radial deadzone, Y flipped so up is positive (XInput). */
|
||||
private fun stick(x: Float, y: Float): Pair<Int, Int> {
|
||||
val magnitude = hypot(x, y)
|
||||
if (magnitude < DEADZONE) return 0 to 0
|
||||
val scaled = ((magnitude - DEADZONE) / (1f - DEADZONE)).coerceIn(0f, 1f) / magnitude
|
||||
return (x * scaled * 32767f).roundToInt() to (-y * scaled * 32767f).roundToInt()
|
||||
}
|
||||
|
||||
private fun trigger(value: Float): Int = (value.coerceIn(0f, 1f) * 255f).roundToInt()
|
||||
|
||||
private fun send(pad: Pad) {
|
||||
streamer?.gamepad(pad.slot, connected(), pad.buttons or pad.hatButtons, pad.lt, pad.rt, pad.lx, pad.ly, pad.rx, pad.ry)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
package com.droiddeck.launcher.stores.gfn
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
|
||||
data class GfnGame(val id: String, val variantId: String, val title: String, val store: String,
|
||||
val imageUrl: String, val inLibrary: Boolean, val search: String)
|
||||
|
||||
data class GfnStoreAccount(val provider: String, val label: String, val displayName: String, val connected: Boolean,
|
||||
val status: String, val syncState: String, val canLink: Boolean, val canSync: Boolean)
|
||||
|
||||
/**
|
||||
* The GeForce NOW tab on the Stores page: NVIDIA sign-in, the store catalog, the account's library
|
||||
* and its connected stores, all through OpenNOW's core. Kept here so it survives switching tabs.
|
||||
*/
|
||||
object GfnState {
|
||||
sealed interface Phase {
|
||||
data object Loading : Phase
|
||||
data class SignedOut(val error: String? = null) : Phase
|
||||
data class Code(val userCode: String, val url: String, val attemptId: String, val intervalMs: Long) : Phase
|
||||
data class SignedIn(val user: String) : Phase
|
||||
data class Failed(val message: String) : Phase
|
||||
}
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
var phase by mutableStateOf<Phase>(Phase.Loading)
|
||||
private set
|
||||
private var started = false
|
||||
private var signInJob: Job? = null
|
||||
|
||||
var storeGames by mutableStateOf(emptyList<GfnGame>())
|
||||
private set
|
||||
var storeTotal by mutableStateOf(0)
|
||||
private set
|
||||
var storeLoading by mutableStateOf(false)
|
||||
private set
|
||||
var storeError by mutableStateOf<String?>(null)
|
||||
private set
|
||||
private var storeQuery = ""
|
||||
private var storeNext = ""
|
||||
private var storeMore = true
|
||||
private var storeGeneration = 0
|
||||
private var storeJob: Job? = null
|
||||
|
||||
var library by mutableStateOf<List<GfnGame>?>(null)
|
||||
private set
|
||||
var libraryError by mutableStateOf<String?>(null)
|
||||
private set
|
||||
private var libraryJob: Job? = null
|
||||
|
||||
var accounts by mutableStateOf<List<GfnStoreAccount>?>(null)
|
||||
private set
|
||||
var accountsMessage by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var accountsBusy by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** Loads the sign-in state once; [force] checks again (Try again). */
|
||||
fun start(context: Context, force: Boolean = false) {
|
||||
if (started && !force) return
|
||||
started = true
|
||||
val app = context.applicationContext
|
||||
phase = Phase.Loading
|
||||
scope.launch { phase = withContext(Dispatchers.IO) { loadSignedIn(app) } }
|
||||
}
|
||||
|
||||
fun signIn(context: Context) {
|
||||
val app = context.applicationContext
|
||||
signInJob?.cancel()
|
||||
signInJob = scope.launch {
|
||||
val code = withContext(Dispatchers.IO) { runCatching { startSignIn(app) } }
|
||||
.getOrElse { phase = Phase.SignedOut(it.message); return@launch }
|
||||
phase = code
|
||||
phase = waitForSignIn(app, code)
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelSignIn() {
|
||||
signInJob?.cancel()
|
||||
phase = Phase.SignedOut()
|
||||
}
|
||||
|
||||
fun signOut(context: Context) {
|
||||
val app = context.applicationContext
|
||||
signInJob?.cancel()
|
||||
scope.launch {
|
||||
withContext(Dispatchers.IO) { runCatching { GfnCore.request(app, "auth.logout") } }
|
||||
clearAccountData()
|
||||
phase = Phase.SignedOut()
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearAccountData() {
|
||||
storeJob?.cancel(); libraryJob?.cancel()
|
||||
storeGames = emptyList(); storeTotal = 0; storeNext = ""; storeMore = true; storeError = null; storeLoading = false
|
||||
library = null; libraryError = null
|
||||
accounts = null; accountsMessage = null
|
||||
}
|
||||
|
||||
/** Shows the store for [query]: loads it when the query changed or nothing is loaded yet. */
|
||||
fun showStore(context: Context, query: String) {
|
||||
if (query.trim() != storeQuery || (storeGames.isEmpty() && !storeLoading && storeError == null)) loadStore(context, query, reset = true)
|
||||
}
|
||||
|
||||
/** NVIDIA's signed-in store catalog, a page at a time; a new [query] starts over. */
|
||||
fun loadStore(context: Context, query: String, reset: Boolean) {
|
||||
val text = query.trim()
|
||||
if (!reset && (storeLoading || !storeMore || text != storeQuery)) return
|
||||
val app = context.applicationContext
|
||||
storeGeneration += 1
|
||||
val asked = storeGeneration
|
||||
storeQuery = text
|
||||
if (reset) { storeNext = ""; storeMore = true }
|
||||
val cursor = storeNext
|
||||
storeLoading = true
|
||||
storeJob?.cancel()
|
||||
storeJob = scope.launch {
|
||||
if (reset && text.isNotEmpty()) delay(350)
|
||||
val page = withContext(Dispatchers.IO) { runCatching { storePage(app, cursor, text) } }
|
||||
if (asked != storeGeneration) return@launch
|
||||
storeLoading = false
|
||||
page.onSuccess {
|
||||
storeError = null
|
||||
val seen = if (reset) HashSet() else storeGames.map { game -> game.id }.toHashSet()
|
||||
storeGames = (if (reset) emptyList() else storeGames) + it.games.filter { game -> seen.add(game.id) }
|
||||
storeNext = it.next
|
||||
storeMore = it.more
|
||||
storeTotal = maxOf(it.total, storeGames.size)
|
||||
}.onFailure { storeError = it.message ?: "The GeForce NOW store did not answer." }
|
||||
}
|
||||
}
|
||||
|
||||
fun loadLibrary(context: Context, force: Boolean = false) {
|
||||
if (!force && (library != null || libraryJob?.isActive == true)) return
|
||||
val app = context.applicationContext
|
||||
if (force) library = null
|
||||
libraryError = null
|
||||
libraryJob?.cancel()
|
||||
libraryJob = scope.launch {
|
||||
withContext(Dispatchers.IO) { runCatching { libraryGames(app) } }
|
||||
.onSuccess { library = it.sortedBy { game -> game.title.lowercase() } }
|
||||
.onFailure { libraryError = it.message ?: "Your GeForce NOW library could not be loaded." }
|
||||
}
|
||||
}
|
||||
|
||||
fun loadAccounts(context: Context) {
|
||||
val app = context.applicationContext
|
||||
scope.launch {
|
||||
withContext(Dispatchers.IO) { runCatching { storeAccounts(app) } }
|
||||
.onSuccess { accounts = it }
|
||||
.onFailure { accountsMessage = it.message ?: "Connected stores could not be loaded." }
|
||||
}
|
||||
}
|
||||
|
||||
fun link(context: Context, account: GfnStoreAccount) = perform(context) { app -> linkStore(app, account) }
|
||||
fun sync(context: Context, account: GfnStoreAccount) = perform(context) { app -> syncStore(app, account) }
|
||||
fun unlink(context: Context, account: GfnStoreAccount) = perform(context) { app ->
|
||||
withContext(Dispatchers.IO) {
|
||||
GfnCore.request(app, "account.connections.unlink", JSONObject().put("provider", account.provider))
|
||||
.optString("message").ifEmpty { "${account.label} disconnected." }
|
||||
}
|
||||
}
|
||||
|
||||
private fun perform(context: Context, action: suspend (Context) -> String) {
|
||||
if (accountsBusy) return
|
||||
val app = context.applicationContext
|
||||
accountsBusy = true
|
||||
scope.launch {
|
||||
accountsMessage = runCatching { action(app) }.getOrElse { it.message ?: "That did not work. Try again." }
|
||||
accountsBusy = false
|
||||
loadAccounts(app)
|
||||
loadLibrary(app, force = true)
|
||||
}
|
||||
}
|
||||
|
||||
fun play(context: Context, game: GfnGame) {
|
||||
context.startActivity(Intent(context, GfnPlayerActivity::class.java)
|
||||
.apply { if (context !is android.app.Activity) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }
|
||||
.putExtra(GfnPlayerActivity.EXTRA_APP_ID, game.id)
|
||||
.putExtra(GfnPlayerActivity.EXTRA_VARIANT_ID, game.variantId)
|
||||
.putExtra(GfnPlayerActivity.EXTRA_TITLE, game.title))
|
||||
}
|
||||
|
||||
/** OpenNOW's own rule for which action a connected-store row offers. */
|
||||
fun actionFor(account: GfnStoreAccount): String = when {
|
||||
account.canLink && (!account.connected || account.status == "expired" ||
|
||||
(account.syncState == "SYNC_DENIED" && account.provider != "STEAM")) -> "link"
|
||||
account.canSync -> "sync"
|
||||
account.connected && account.canLink -> "unlink"
|
||||
else -> "none"
|
||||
}
|
||||
|
||||
private fun loadSignedIn(context: Context): Phase = runCatching {
|
||||
val auth = GfnCore.request(context, "auth.session.get")
|
||||
val user = auth.optJSONObject("session")?.optJSONObject("user") ?: auth.optJSONObject("user")
|
||||
if (user == null || user.optString("userId").isEmpty()) return Phase.SignedOut()
|
||||
Phase.SignedIn(user.optString("displayName").ifEmpty { "Signed in" })
|
||||
}.getOrElse { Phase.Failed(it.message ?: "GeForce NOW could not start.") }
|
||||
|
||||
private fun startSignIn(context: Context): Phase.Code {
|
||||
val challenge = GfnCore.request(context, "auth.device.start")
|
||||
return Phase.Code(
|
||||
userCode = challenge.optString("userCode"),
|
||||
url = challenge.optString("verificationUriComplete").ifEmpty { challenge.optString("verificationUri") },
|
||||
attemptId = challenge.optString("attemptId"),
|
||||
intervalMs = (challenge.optDouble("intervalSeconds", 5.0) * 1000).toLong().coerceAtLeast(1000))
|
||||
}
|
||||
|
||||
private suspend fun waitForSignIn(context: Context, code: Phase.Code): Phase {
|
||||
var interval = code.intervalMs
|
||||
while (true) {
|
||||
delay(interval)
|
||||
val poll = withContext(Dispatchers.IO) {
|
||||
runCatching { GfnCore.request(context, "auth.device.poll", JSONObject().put("attemptId", code.attemptId)) }
|
||||
}.getOrElse { return Phase.SignedOut(it.message) }
|
||||
when (poll.optString("status")) {
|
||||
"authorized" -> {
|
||||
withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
GfnCore.request(context, "auth.device.complete",
|
||||
JSONObject().put("attemptId", code.attemptId).put("staySignedIn", true))
|
||||
}
|
||||
}.onFailure { return Phase.SignedOut(it.message) }
|
||||
clearAccountData()
|
||||
return withContext(Dispatchers.IO) { loadSignedIn(context) }
|
||||
}
|
||||
"pending", "slow_down" -> interval = poll.optLong("retryAfterMs",
|
||||
(poll.optDouble("intervalSeconds", interval / 1000.0) * 1000).toLong()).coerceAtLeast(1000)
|
||||
else -> return Phase.SignedOut(poll.optString("message").ifEmpty { "Sign-in did not finish. Try again." })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class Page(val games: List<GfnGame>, val next: String, val more: Boolean, val total: Int)
|
||||
|
||||
/** Browsing reads the core's local copy of the catalog, which grows a page at a time; a search asks NVIDIA. */
|
||||
private fun storePage(context: Context, cursor: String, query: String): Page {
|
||||
val params = JSONObject().put("limit", 40).put("cursor", cursor).put("searchQuery", query)
|
||||
if (query.isEmpty()) params.put("genre", "").put("store", "").put("categoryId", "").put("refresh", false)
|
||||
val result = GfnCore.request(context, if (query.isEmpty()) "catalog.store.local" else "catalog.store.list", params, timeoutMs = 60_000)
|
||||
val games = gamesOf(result)
|
||||
return Page(games, result.optString("nextCursor"), result.optBoolean("hasNextPage") && result.optString("nextCursor").isNotEmpty(),
|
||||
result.optInt("totalCount", games.size))
|
||||
}
|
||||
|
||||
/** Pages of 50 keep each answer well under the binder transaction limit. */
|
||||
private fun libraryGames(context: Context): List<GfnGame> {
|
||||
val games = LinkedHashMap<String, GfnGame>()
|
||||
val traversal = System.currentTimeMillis().toString()
|
||||
var cursor = ""
|
||||
var revision: Any? = null
|
||||
var catalogContext = ""
|
||||
repeat(100) {
|
||||
val params = JSONObject().put("limit", 50).put("cursor", cursor).put("traversalId", traversal)
|
||||
.put("catalogRevision", revision ?: JSONObject.NULL).put("catalogContext", catalogContext)
|
||||
val page = GfnCore.request(context, "catalog.library.list", params, timeoutMs = 60_000)
|
||||
gamesOf(page).forEach { games.putIfAbsent(it.id, it.copy(inLibrary = true)) }
|
||||
revision = page.opt("catalogRevision")
|
||||
catalogContext = page.optString("catalogContext")
|
||||
cursor = page.optString("nextCursor")
|
||||
if (!page.optBoolean("hasNextPage") || cursor.isEmpty()) return games.values.toList()
|
||||
}
|
||||
return games.values.toList()
|
||||
}
|
||||
|
||||
private fun gamesOf(result: JSONObject): List<GfnGame> {
|
||||
val list = result.optJSONArray("games") ?: return emptyList()
|
||||
return (0 until list.length()).mapNotNull { index ->
|
||||
val game = list.optJSONObject(index) ?: return@mapNotNull null
|
||||
val variants = game.optJSONArray("variants")
|
||||
val variant = variants?.optJSONObject(game.optInt("selectedVariantIndex", 0).coerceIn(0, (variants.length() - 1).coerceAtLeast(0)))
|
||||
GfnGame(id = game.optString("id"),
|
||||
variantId = variant?.optString("id").orEmpty().ifEmpty { game.optString("launchAppId") },
|
||||
title = game.optString("title"),
|
||||
store = storeLabel(variant?.optString("store").orEmpty()),
|
||||
imageUrl = game.optString("imageUrl"),
|
||||
inLibrary = game.optBoolean("isInLibrary") || variant?.optBoolean("inLibrary") == true,
|
||||
search = game.optString("searchText").ifEmpty { game.optString("title").lowercase() })
|
||||
}.filter { it.id.isNotEmpty() && it.variantId.isNotEmpty() }
|
||||
}
|
||||
|
||||
private fun storeLabel(store: String): String = when (store.uppercase()) {
|
||||
"STEAM" -> "Steam"
|
||||
"EPIC" -> "Epic"
|
||||
"XBOX" -> "Xbox"
|
||||
"BATTLENET" -> "Battle.net"
|
||||
"UPLAY", "UBISOFT" -> "Ubisoft"
|
||||
"GOG" -> "GOG"
|
||||
"EA_APP", "EA", "ORIGIN" -> "EA"
|
||||
"GAIJIN" -> "Gaijin"
|
||||
else -> store.lowercase().replaceFirstChar { it.uppercase() }
|
||||
}
|
||||
|
||||
private fun storeAccounts(context: Context): List<GfnStoreAccount> {
|
||||
val list = GfnCore.request(context, "account.connections.list").optJSONArray("accounts") ?: return emptyList()
|
||||
return (0 until list.length()).mapNotNull { index ->
|
||||
val account = list.optJSONObject(index) ?: return@mapNotNull null
|
||||
if (account.optString("provider") in setOf("", "UNKNOWN", "NONE", "NVIDIA")) return@mapNotNull null
|
||||
GfnStoreAccount(provider = account.optString("provider"), label = account.optString("label").ifEmpty { account.optString("provider") },
|
||||
displayName = account.optString("displayName"),
|
||||
connected = account.optBoolean("isConnected") || account.optString("status") == "connected",
|
||||
status = account.optString("status"), syncState = account.optString("syncState"),
|
||||
canLink = account.optBoolean("supportsLinking"), canSync = account.optBoolean("supportsSync"))
|
||||
}.filter { it.canLink || it.canSync || it.connected }
|
||||
}
|
||||
|
||||
private suspend fun linkStore(context: Context, account: GfnStoreAccount): String {
|
||||
val attempt = withContext(Dispatchers.IO) {
|
||||
GfnCore.request(context, "account.connections.link.start", JSONObject().put("provider", account.provider))
|
||||
}
|
||||
val url = attempt.optString("loginUrl")
|
||||
if (url.isNotEmpty()) runCatching {
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
repeat(150) {
|
||||
delay(2_000)
|
||||
val poll = withContext(Dispatchers.IO) {
|
||||
GfnCore.request(context, "account.connections.link.poll",
|
||||
JSONObject().put("attemptId", attempt.optString("attemptId")), timeoutMs = 10_000)
|
||||
}
|
||||
when (poll.optString("status")) {
|
||||
"pending" -> {}
|
||||
"complete" -> return "${account.label} connected."
|
||||
else -> return poll.optString("message").ifEmpty { "${account.label} was not connected." }
|
||||
}
|
||||
}
|
||||
return "Stopped waiting for ${account.label}. Finish signing in, then refresh."
|
||||
}
|
||||
|
||||
private suspend fun syncStore(context: Context, account: GfnStoreAccount): String = withContext(Dispatchers.IO) {
|
||||
var state = GfnCore.request(context, "account.connections.sync", JSONObject().put("provider", account.provider))
|
||||
val operation = state.optString("operationId")
|
||||
if (operation.isEmpty()) return@withContext state.optString("message").ifEmpty { "${account.label} synced." }
|
||||
repeat(90) {
|
||||
when (state.optString("phase")) {
|
||||
"waiting_remote", "starting" -> {
|
||||
delay(state.optLong("retryAfterMs", 2_000).coerceAtLeast(2_000))
|
||||
state = GfnCore.request(context, "account.connections.sync.status", JSONObject().put("operationId", operation))
|
||||
}
|
||||
"refreshing_library" -> {
|
||||
runCatching { libraryGames(context) }
|
||||
runCatching {
|
||||
GfnCore.request(context, "account.connections.sync.status",
|
||||
JSONObject().put("operationId", operation).put("libraryRefreshed", true), timeoutMs = 10_000)
|
||||
}
|
||||
return@withContext "${account.label} synced. Your library is up to date."
|
||||
}
|
||||
"timed_out" -> return@withContext "The sync could not be confirmed. ${account.label} may still finish; refresh later."
|
||||
else -> return@withContext "${account.label} could not finish the sync. Try again."
|
||||
}
|
||||
}
|
||||
"Still waiting for ${account.label}; refresh later."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.droiddeck.launcher.stores.gfn
|
||||
|
||||
import android.view.Surface
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/**
|
||||
* OpenNOW's native streamer engine (external/opennow, MIT, by Zortos) inside libdroiddeckgfn.so,
|
||||
* with DroidDeck's Android media backend: MediaCodec onto [setSurface]'s Surface, AAudio sound.
|
||||
* Commands are the engine's JSON protocol (`hello`, `start`, `stop`, ...); answers and events
|
||||
* arrive on [onMessage] from a polling thread.
|
||||
*/
|
||||
class GfnStreamer(private val onMessage: (JSONObject) -> Unit) {
|
||||
private var handle = nativeOpen()
|
||||
private val ids = AtomicLong(1)
|
||||
@Volatile private var open = true
|
||||
private val poller = Thread({
|
||||
while (open) {
|
||||
val line = nativePoll(handle, 250) ?: continue
|
||||
runCatching { JSONObject(line) }.getOrNull()?.let { message -> runCatching { onMessage(message) } }
|
||||
}
|
||||
}, "gfn-streamer-poll").apply { isDaemon = true; start() }
|
||||
|
||||
/** Sends one command; returns its id (responses carry it), or "" if the engine is closed. */
|
||||
fun send(type: String, fields: JSONObject = JSONObject()): String {
|
||||
if (!open) return ""
|
||||
val id = "dd-" + ids.getAndIncrement()
|
||||
fields.put("id", id).put("type", type)
|
||||
return if (nativeCommand(handle, fields.toString())) id else ""
|
||||
}
|
||||
|
||||
fun gamepad(slot: Int, connected: Int, buttons: Int, leftTrigger: Int, rightTrigger: Int,
|
||||
leftX: Int, leftY: Int, rightX: Int, rightY: Int) {
|
||||
if (open) nativeGamepad(handle, slot, connected, buttons, leftTrigger, rightTrigger, leftX, leftY, rightX, rightY)
|
||||
}
|
||||
|
||||
fun key(virtualKey: Int, modifiers: Int, pressed: Boolean) {
|
||||
if (open) nativeKey(handle, virtualKey, modifiers, pressed)
|
||||
}
|
||||
|
||||
fun close() {
|
||||
if (!open) return
|
||||
open = false
|
||||
poller.join(1_000)
|
||||
nativeClose(handle)
|
||||
handle = 0
|
||||
}
|
||||
|
||||
companion object {
|
||||
init { System.loadLibrary("droiddeckgfn") }
|
||||
|
||||
@JvmStatic fun setSurface(surface: Surface?) = nativeSetSurface(surface)
|
||||
|
||||
@JvmStatic private external fun nativeOpen(): Long
|
||||
@JvmStatic private external fun nativeCommand(handle: Long, json: String): Boolean
|
||||
@JvmStatic private external fun nativePoll(handle: Long, timeoutMs: Int): String?
|
||||
@JvmStatic private external fun nativeClose(handle: Long)
|
||||
@JvmStatic private external fun nativeSetSurface(surface: Surface?)
|
||||
@JvmStatic private external fun nativeGamepad(handle: Long, slot: Int, connected: Int, buttons: Int,
|
||||
leftTrigger: Int, rightTrigger: Int,
|
||||
leftX: Int, leftY: Int, rightX: Int, rightY: Int)
|
||||
@JvmStatic private external fun nativeKey(handle: Long, virtualKey: Int, modifiers: Int, pressed: Boolean)
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,6 @@ internal object ItchApi {
|
||||
|
||||
fun ownedKeys(key: String, page: Int): JSONObject? = get("/profile/owned-keys?page=$page&per_page=500", key)
|
||||
|
||||
fun collections(key: String): JSONArray? = get("/profile/collections", key)?.optJSONArray("collections")
|
||||
|
||||
fun collectionGames(key: String, collectionId: String, page: Int): JSONObject? =
|
||||
get("/collections/$collectionId/collection-games?page=$page", key)
|
||||
|
||||
fun uploads(key: String, gameId: String, downloadKeyId: String): JSONArray? =
|
||||
get("/games/$gameId/uploads" + keyQuery(downloadKeyId), key)?.optJSONArray("uploads")
|
||||
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
internal class ItchCollection(val id: String, val title: String, val count: Int)
|
||||
|
||||
internal object ItchCollections {
|
||||
var list by mutableStateOf<List<ItchCollection>>(emptyList())
|
||||
private set
|
||||
var selected by mutableStateOf<String?>(null)
|
||||
private set
|
||||
private val games = mutableStateMapOf<String, List<CatalogItem>>()
|
||||
private val loading = ConcurrentHashMap.newKeySet<String>()
|
||||
@Volatile private var generation = 0
|
||||
|
||||
fun items(): List<CatalogItem> = games.values.flatten()
|
||||
|
||||
fun gamesOf(id: String): List<CatalogItem>? = games[id]
|
||||
|
||||
fun chosen(): ItchCollection? = list.firstOrNull { it.id == selected }
|
||||
|
||||
fun clear() {
|
||||
generation++
|
||||
StoresState.post {
|
||||
list = emptyList()
|
||||
selected = null
|
||||
games.clear()
|
||||
}
|
||||
}
|
||||
|
||||
fun load(context: Context) {
|
||||
val app = context.applicationContext
|
||||
val started = generation
|
||||
val guard = "$started:"
|
||||
if (!loading.add(guard)) return
|
||||
Thread({
|
||||
try {
|
||||
val key = ItchAuth.key(app)
|
||||
if (key.isBlank()) return@Thread
|
||||
val parsed = parseCollections(ItchApi.collections(key) ?: return@Thread)
|
||||
if (started != generation) return@Thread
|
||||
StoresState.post {
|
||||
if (started != generation) return@post
|
||||
list = parsed
|
||||
if (selected != null && parsed.none { it.id == selected }) selected = null
|
||||
}
|
||||
StoresState.logLine("itch.io: ${parsed.size} collections")
|
||||
selected?.let { fetchGames(key, it, started) }
|
||||
} finally {
|
||||
loading.remove(guard)
|
||||
}
|
||||
}, "itch-collections").start()
|
||||
}
|
||||
|
||||
fun select(context: Context, id: String?) {
|
||||
selected = id
|
||||
if (id == null) return
|
||||
val app = context.applicationContext
|
||||
val started = generation
|
||||
Thread({
|
||||
val key = ItchAuth.key(app)
|
||||
if (key.isNotBlank()) fetchGames(key, id, started)
|
||||
}, "itch-collection-games").start()
|
||||
}
|
||||
|
||||
private fun fetchGames(key: String, id: String, started: Int) {
|
||||
val guard = "$started:$id"
|
||||
if (!loading.add(guard)) return
|
||||
try {
|
||||
val out = ArrayList<CatalogItem>()
|
||||
val seen = HashSet<String>()
|
||||
var page = 1
|
||||
while (true) {
|
||||
val body = ItchApi.collectionGames(key, id, page)
|
||||
if (body == null) {
|
||||
StoresState.logLine("itch.io: collection $id page $page failed")
|
||||
return
|
||||
}
|
||||
val batch = parseGames(body)
|
||||
if (batch.isEmpty()) break
|
||||
val before = out.size
|
||||
out.addAll(batch.filter { seen.add(it.id) })
|
||||
if (out.size == before) break
|
||||
page++
|
||||
}
|
||||
val distinct = out.toList()
|
||||
StoresState.post { if (started == generation) games[id] = distinct }
|
||||
StoresState.logLine("itch.io: collection $id has ${distinct.size} games")
|
||||
} finally {
|
||||
loading.remove(guard)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun parseCollections(array: JSONArray): List<ItchCollection> = (0 until array.length()).mapNotNull { i ->
|
||||
val c = array.optJSONObject(i) ?: return@mapNotNull null
|
||||
val id = c.opt("id")?.toString().orEmpty().takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null
|
||||
val title = c.optString("title").ifBlank { return@mapNotNull null }
|
||||
ItchCollection(id, title, c.optInt("games_count", c.optInt("gamesCount")))
|
||||
}
|
||||
|
||||
internal fun parseGames(body: JSONObject): List<CatalogItem> {
|
||||
val rows = body.optJSONArray("collection_games") ?: body.optJSONArray("collectionGames") ?: return emptyList()
|
||||
return (0 until rows.length()).mapNotNull { i ->
|
||||
rows.optJSONObject(i)?.optJSONObject("game")?.let { ItchLibrary.item(it, "") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,10 +33,6 @@ internal class ItchInstaller(
|
||||
private val folder: File,
|
||||
) : DownloadQueue.DownloadJob {
|
||||
private val cancelled = AtomicBoolean(false)
|
||||
private var work: File = folder
|
||||
private var updating = false
|
||||
private var previous: StoreGameSidecar? = null
|
||||
private val commit = Any()
|
||||
|
||||
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||
val key = ItchAuth.key(app)
|
||||
@@ -44,10 +40,7 @@ internal class ItchInstaller(
|
||||
val downloadKeyId = item.extra["downloadKeyId"].orEmpty()
|
||||
if (downloadKeyId.isBlank() && !item.isFree) throw IllegalStateException(app.getString(R.string.stores_itch_not_owned))
|
||||
val gameId = ItchGame.resolveId(item) ?: throw IllegalStateException(app.getString(R.string.stores_itch_no_game))
|
||||
val before = StoreGameSidecar.read(folder)
|
||||
previous = before
|
||||
updating = before != null && (before.isInstalled || before.state == StoreGameSidecar.STATE_UPDATING)
|
||||
val resuming = before?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true
|
||||
val resuming = StoreGameSidecar.read(folder)?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true
|
||||
StoreInstalls.begin(folder, Store.ITCH, item.id, item.title, item.imageUrl, item.imageUrl)
|
||||
handle.stage(DownloadStage.MANIFEST)
|
||||
val uploads = ItchApi.uploads(key, gameId, downloadKeyId)
|
||||
@@ -67,12 +60,12 @@ internal class ItchInstaller(
|
||||
handle.stage(DownloadStage.INSTALL)
|
||||
install(archive, filename, handle, resuming)
|
||||
} catch (t: Throwable) {
|
||||
if (!cancelled.get()) dropCaches(scratch)
|
||||
if (!cancelled.get()) StoreInstalls.discard(app, folder, listOf(scratch))
|
||||
throw t
|
||||
}
|
||||
if (exe == null) {
|
||||
if (cancelled.get()) return null
|
||||
dropCaches(scratch)
|
||||
StoreInstalls.discard(app, folder, listOf(scratch))
|
||||
throw IllegalStateException(app.getString(R.string.stores_itch_no_exe))
|
||||
}
|
||||
archive.delete()
|
||||
@@ -82,8 +75,6 @@ internal class ItchInstaller(
|
||||
id = item.id,
|
||||
title = item.title,
|
||||
exe = exe,
|
||||
args = previous?.args.orEmpty(),
|
||||
env = previous?.env.orEmpty(),
|
||||
installVersion = upload.optString("updated_at", upload.optString("updatedAt")),
|
||||
installedAt = System.currentTimeMillis(),
|
||||
cover = item.imageUrl,
|
||||
@@ -92,24 +83,12 @@ internal class ItchInstaller(
|
||||
cloud = false,
|
||||
)
|
||||
StoreInstalls.complete(app, folder, sidecar) { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }
|
||||
ItchUpdates.applied(app, item.key)
|
||||
return folder.path
|
||||
}
|
||||
|
||||
override fun cancel(deleteFiles: Boolean) {
|
||||
cancelled.set(true)
|
||||
if (deleteFiles) dropCaches(StoreInstallRoot.scratchDir(app, Store.ITCH, item.id))
|
||||
}
|
||||
|
||||
private fun dropCaches(scratch: File) {
|
||||
if (!updating) {
|
||||
StoreInstalls.discard(app, folder, listOf(scratch))
|
||||
return
|
||||
}
|
||||
synchronized(commit) {
|
||||
StoreInstalls.deleteTree(scratch)
|
||||
ItchStaging.delete(File(folder, ItchStaging.DIR))
|
||||
}
|
||||
if (deleteFiles) StoreInstalls.discard(app, folder, listOf(StoreInstallRoot.scratchDir(app, Store.ITCH, item.id)))
|
||||
}
|
||||
|
||||
private fun download(key: String, downloadKeyId: String, uploadId: String, version: String, target: File, expected: Long,
|
||||
@@ -179,45 +158,23 @@ internal class ItchInstaller(
|
||||
}
|
||||
|
||||
private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean): String? {
|
||||
work = if (updating) File(folder, ItchStaging.DIR) else folder
|
||||
if (updating) ItchStaging.delete(work)
|
||||
work.mkdirs()
|
||||
folder.mkdirs()
|
||||
if (resuming) clearPartialInstall()
|
||||
val exe = try {
|
||||
when (val kind = sniff(archive, filename)) {
|
||||
"zip" -> unzip(archive, handle)
|
||||
"7z" -> sevenZip(archive, handle)
|
||||
"rar" -> unrar(archive, handle)
|
||||
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
|
||||
"tar" -> untar(archive, null, handle)
|
||||
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
|
||||
else -> copy(archive, File(work, filename.ifBlank { "game" }))
|
||||
}
|
||||
val hint = filename.substringBeforeLast('.')
|
||||
StoreExe.pick(work, hint.ifBlank { null }, item.title)
|
||||
} catch (t: Throwable) {
|
||||
if (updating) ItchStaging.delete(work)
|
||||
throw t
|
||||
when (val kind = sniff(archive, filename)) {
|
||||
"zip" -> unzip(archive, handle)
|
||||
"7z" -> sevenZip(archive, handle)
|
||||
"rar" -> unrar(archive, handle)
|
||||
"exe" -> copy(archive, File(folder, filename.ifBlank { "game.exe" }))
|
||||
"tar" -> untar(archive, null, handle)
|
||||
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
|
||||
else -> copy(archive, File(folder, filename.ifBlank { "game" }))
|
||||
}
|
||||
val hint = filename.substringBeforeLast('.')
|
||||
val exe = StoreExe.pick(folder, hint.ifBlank { null }, item.title)
|
||||
if (exe.isBlank()) {
|
||||
handle.log("itch.io: no exe found in ${folder.name}")
|
||||
if (updating) ItchStaging.delete(work)
|
||||
return null
|
||||
}
|
||||
if (updating) synchronized(commit) {
|
||||
if (cancelled.get()) {
|
||||
ItchStaging.delete(work)
|
||||
return null
|
||||
}
|
||||
try {
|
||||
StoreInstalls.markUpdating(folder)
|
||||
} catch (t: Throwable) {
|
||||
ItchStaging.delete(work)
|
||||
throw t
|
||||
}
|
||||
ItchStaging.merge(work, folder)
|
||||
ItchStaging.delete(work)
|
||||
}
|
||||
return exe
|
||||
}
|
||||
|
||||
@@ -240,8 +197,8 @@ internal class ItchInstaller(
|
||||
}
|
||||
|
||||
private fun target(name: String): File? {
|
||||
val file = File(work, name.replace('\\', '/'))
|
||||
val root = work.canonicalPath
|
||||
val file = File(folder, name.replace('\\', '/'))
|
||||
val root = folder.canonicalPath
|
||||
val path = file.canonicalPath
|
||||
return if (path == root || path.startsWith(root + File.separator)) file else null
|
||||
}
|
||||
@@ -249,8 +206,8 @@ internal class ItchInstaller(
|
||||
// No JVM library reads RAR5; the runtime's bsdtar (libarchive) does.
|
||||
private fun unrar(archive: File, handle: DownloadQueue.JobHandle) {
|
||||
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.stores_itch_archive, "rar"))
|
||||
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
|
||||
else listOf(work.absolutePath)
|
||||
val binds = if (listOf(app.filesDir, app.cacheDir).any { folder.absolutePath.startsWith(it.absolutePath + "/") }) null
|
||||
else listOf(folder.absolutePath)
|
||||
fun bsdtar(args: List<String>, onLine: (String) -> Unit) =
|
||||
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = "itch-unrar", extraBinds = binds, fastPath = true) { line ->
|
||||
if (!line.startsWith("proot ")) onLine(line)
|
||||
@@ -259,7 +216,7 @@ internal class ItchInstaller(
|
||||
bsdtar(listOf("-tf", archive.absolutePath)) { entries++ }
|
||||
var done = 0L
|
||||
val tail = ArrayDeque<String>()
|
||||
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line ->
|
||||
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", folder.absolutePath)) { line ->
|
||||
if (line.startsWith("x ")) handle.stageProgress(++done, entries) else {
|
||||
if (tail.size == 5) tail.removeFirst()
|
||||
tail.addLast(line)
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
|
||||
internal object ItchStaging {
|
||||
const val DIR = ".droiddeck-update"
|
||||
const val RECORD = ".droiddeck-store.json"
|
||||
|
||||
fun merge(from: File, to: File, top: Boolean = true) {
|
||||
for (child in from.listFiles().orEmpty()) {
|
||||
if (top && child.name == RECORD) continue
|
||||
val dest = File(to, child.name)
|
||||
val destPath = dest.toPath()
|
||||
if (child.isDirectory && !Files.isSymbolicLink(child.toPath()) && dest.isDirectory && !Files.isSymbolicLink(destPath)) {
|
||||
merge(child, dest, false)
|
||||
continue
|
||||
}
|
||||
if (Files.isSymbolicLink(destPath) || dest.exists()) {
|
||||
delete(dest)
|
||||
}
|
||||
Files.move(child.toPath(), destPath)
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(file: File) {
|
||||
if (!Files.isSymbolicLink(file.toPath()) && file.isDirectory) file.listFiles().orEmpty().forEach { delete(it) }
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
package com.droiddeck.launcher.stores.itch
|
||||
|
||||
import android.content.Context
|
||||
import android.widget.Toast
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal class ItchUpdate(val uploadId: String, val updatedAt: String, val filename: String, val replaced: Boolean)
|
||||
|
||||
internal object ItchUpdates {
|
||||
private const val KEY_AT = "updates_checked_at"
|
||||
private const val KEY_FOUND = "updates_found"
|
||||
private const val THROTTLE_MS = 6 * 60 * 60 * 1000L
|
||||
private const val GAP_MS = 1_000L
|
||||
|
||||
val available = mutableStateMapOf<String, ItchUpdate>()
|
||||
var checkingKey by mutableStateOf<String?>(null)
|
||||
private set
|
||||
|
||||
private val running = AtomicBoolean(false)
|
||||
private val restored = AtomicBoolean(false)
|
||||
@Volatile private var generation = 0
|
||||
|
||||
internal fun evaluate(uploads: JSONArray?, uploadId: String, version: String): ItchUpdate? {
|
||||
if (uploads == null || version.isBlank()) return null
|
||||
val current = ItchUploads.byId(uploads, uploadId)
|
||||
if (current != null) {
|
||||
val stamp = ItchUploads.updatedAt(current)
|
||||
return if (stamp > version) ItchUpdate(uploadId, stamp, ItchUploads.filename(current), false) else null
|
||||
}
|
||||
val next = ItchUploads.newestWindows(uploads) ?: return null
|
||||
val stamp = ItchUploads.updatedAt(next)
|
||||
if (uploadId.isBlank() && stamp <= version) return null
|
||||
return ItchUpdate(next.optString("id"), stamp, ItchUploads.filename(next), uploadId.isNotBlank())
|
||||
}
|
||||
|
||||
internal fun encode(found: Map<String, ItchUpdate>): String = JSONObject().also { out ->
|
||||
for ((key, u) in found) out.put(key, JSONObject().put("uploadId", u.uploadId).put("updatedAt", u.updatedAt).put("filename", u.filename).put("replaced", u.replaced))
|
||||
}.toString()
|
||||
|
||||
internal fun decode(raw: String?): Map<String, ItchUpdate> {
|
||||
val json = runCatching { JSONObject(raw.orEmpty()) }.getOrNull() ?: return emptyMap()
|
||||
val out = LinkedHashMap<String, ItchUpdate>()
|
||||
for (key in json.keys()) {
|
||||
val u = json.optJSONObject(key) ?: continue
|
||||
val id = u.optString("uploadId")
|
||||
if (id.isBlank()) continue
|
||||
out[key] = ItchUpdate(id, u.optString("updatedAt"), u.optString("filename"), u.optBoolean("replaced"))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun restore(app: Context) {
|
||||
if (!restored.compareAndSet(false, true)) return
|
||||
val started = generation
|
||||
val saved = decode(ItchPrefs.get(app).getString(KEY_FOUND, null))
|
||||
StoresState.post {
|
||||
if (started != generation) return@post
|
||||
for ((k, v) in saved) if (k !in available) available[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
private fun save(app: Context) {
|
||||
ItchPrefs.get(app).edit().putString(KEY_FOUND, encode(available.toMap())).apply()
|
||||
}
|
||||
|
||||
fun check(context: Context) {
|
||||
val app = context.applicationContext
|
||||
if (!running.compareAndSet(false, true)) return
|
||||
val started = generation
|
||||
Thread({
|
||||
try {
|
||||
restore(app)
|
||||
val prefs = ItchPrefs.get(app)
|
||||
if (System.currentTimeMillis() - prefs.getLong(KEY_AT, 0L) < THROTTLE_MS) return@Thread
|
||||
val key = ItchAuth.key(app)
|
||||
if (key.isBlank()) return@Thread
|
||||
val games = StoresState.installed.toList().filter { it.sidecar.store == Store.ITCH && it.sidecar.isInstalled }
|
||||
val found = LinkedHashMap<String, ItchUpdate>()
|
||||
val answered = HashSet<String>()
|
||||
val snapshot = HashMap<String, Pair<String, String>>()
|
||||
var failed = false
|
||||
games.forEachIndexed { i, game ->
|
||||
if (i > 0) Thread.sleep(GAP_MS)
|
||||
val extra = game.sidecar.extra
|
||||
snapshot[game.key] = game.sidecar.installVersion to extra["uploadId"].orEmpty()
|
||||
val gameId = extra["gameId"].orEmpty()
|
||||
if (gameId.isNotEmpty()) {
|
||||
val uploads = ItchApi.uploads(key, gameId, extra["downloadKeyId"].orEmpty())
|
||||
if (uploads == null) failed = true
|
||||
else {
|
||||
answered += game.key
|
||||
evaluate(uploads, extra["uploadId"].orEmpty(), game.sidecar.installVersion)?.let { found[game.key] = it }
|
||||
}
|
||||
} else failed = true
|
||||
}
|
||||
if (started != generation) return@Thread
|
||||
StoresState.post {
|
||||
if (started != generation) return@post
|
||||
for (k in answered) {
|
||||
val now = StoresState.installed.firstOrNull { it.key == k } ?: continue
|
||||
if (snapshot[k] != now.sidecar.installVersion to now.sidecar.extra["uploadId"].orEmpty()) continue
|
||||
val u = found[k]
|
||||
if (u != null) available[k] = u else available.remove(k)
|
||||
}
|
||||
save(app)
|
||||
}
|
||||
if (!failed && started == generation) prefs.edit().putLong(KEY_AT, System.currentTimeMillis()).apply()
|
||||
StoresState.logLine("itch.io: checked ${games.size} installed games, ${found.size} with updates")
|
||||
} finally {
|
||||
running.set(false)
|
||||
}
|
||||
}, "itch-updates").start()
|
||||
}
|
||||
|
||||
fun checkGame(context: Context, game: InstalledStoreGame) {
|
||||
val app = context.applicationContext
|
||||
if (checkingKey != null) return
|
||||
checkingKey = game.key
|
||||
val started = generation
|
||||
val version = game.sidecar.installVersion
|
||||
val uploadId = game.sidecar.extra["uploadId"].orEmpty()
|
||||
Thread({
|
||||
try {
|
||||
val key = ItchAuth.key(app)
|
||||
val extra = game.sidecar.extra
|
||||
val gameId = extra["gameId"].orEmpty()
|
||||
val uploads = if (key.isBlank() || gameId.isEmpty()) null else ItchApi.uploads(key, gameId, extra["downloadKeyId"].orEmpty())
|
||||
val found = evaluate(uploads, uploadId, version)
|
||||
StoresState.post {
|
||||
if (started != generation) return@post
|
||||
val now = StoresState.installed.firstOrNull { it.key == game.key }
|
||||
if (uploads != null && now != null && now.sidecar.installVersion == version && now.sidecar.extra["uploadId"].orEmpty() == uploadId) {
|
||||
if (found != null) available[game.key] = found else available.remove(game.key)
|
||||
save(app)
|
||||
}
|
||||
val text = when {
|
||||
uploads == null -> app.getString(R.string.stores_sync_failed)
|
||||
found != null -> app.getString(R.string.stores_itch_updates_found, 1)
|
||||
else -> app.getString(R.string.upd_current_status)
|
||||
}
|
||||
Toast.makeText(app, text, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
StoresState.logLine("itch.io: checked ${game.sidecar.title}, ${if (found != null) "update available" else "up to date"}")
|
||||
} finally {
|
||||
StoresState.post { checkingKey = null }
|
||||
}
|
||||
}, "itch-update-check").start()
|
||||
}
|
||||
|
||||
fun start(context: Context, game: InstalledStoreGame, update: ItchUpdate) {
|
||||
val app = context.applicationContext
|
||||
if (StoresState.uninstalling.containsKey(game.key)) return
|
||||
val root = game.folder.parentFile?.parentFile ?: return
|
||||
val extra = game.sidecar.extra + ("uploadId" to update.uploadId)
|
||||
val item = CatalogItem(
|
||||
Store.ITCH, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover,
|
||||
isFree = extra["downloadKeyId"].isNullOrBlank(), owned = true, extra = extra,
|
||||
)
|
||||
StoresState.install(app, item, root)
|
||||
}
|
||||
|
||||
fun applied(context: Context, key: String) {
|
||||
val app = context.applicationContext
|
||||
StoresState.post {
|
||||
available.remove(key)
|
||||
save(app)
|
||||
}
|
||||
}
|
||||
|
||||
fun clear(context: Context) {
|
||||
val app = context.applicationContext
|
||||
generation++
|
||||
ItchPrefs.get(app).edit().remove(KEY_AT).remove(KEY_FOUND).apply()
|
||||
StoresState.post { available.clear() }
|
||||
}
|
||||
}
|
||||
@@ -18,14 +18,6 @@ internal object ItchUploads {
|
||||
return candidates.maxWithOrNull(compareBy({ it.optString("updated_at", it.optString("updatedAt")) }, { it.optLong("id") }))
|
||||
}
|
||||
|
||||
fun newestWindows(uploads: JSONArray?): JSONObject? {
|
||||
if (uploads == null) return null
|
||||
val windows = (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }
|
||||
.filter { it.optString("storage") != "external" && !it.optBoolean("demo") && windows(it) }
|
||||
val games = windows.filter { it.optString("type") in GAME_TYPES }
|
||||
return games.ifEmpty { windows }.maxWithOrNull(compareBy({ updatedAt(it) }, { it.optLong("id") }))
|
||||
}
|
||||
|
||||
fun windows(upload: JSONObject): Boolean {
|
||||
val platforms = upload.optJSONObject("platforms")
|
||||
if (platforms != null) {
|
||||
@@ -60,8 +52,6 @@ internal object ItchUploads {
|
||||
return (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }.firstOrNull { it.optString("id") == id }
|
||||
}
|
||||
|
||||
fun updatedAt(upload: JSONObject): String = upload.optString("updated_at", upload.optString("updatedAt"))
|
||||
|
||||
fun size(upload: JSONObject): Long = upload.optLong("size", upload.optLong("size_bytes"))
|
||||
|
||||
fun filename(upload: JSONObject): String = upload.optString("filename").substringAfterLast('/')
|
||||
|
||||
@@ -1,959 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.view.KeyEvent
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
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.imePadding
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyGridState
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.FilterAlt
|
||||
import androidx.compose.material.icons.filled.Sort
|
||||
import androidx.compose.material.icons.filled.Widgets
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.zIndex
|
||||
import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.HomeFolders
|
||||
import com.droiddeck.launcher.HomeHidden
|
||||
import com.droiddeck.launcher.HomePins
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.graphics.Bitmap
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import com.droiddeck.launcher.HomeWidgets
|
||||
import com.droiddeck.launcher.R
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
private sealed interface AppEntry : AppEntryKey {
|
||||
val key: String
|
||||
|
||||
class App(val app: HomeApp.LaunchableApp) : AppEntry {
|
||||
override val label get() = app.label
|
||||
override val key get() = "app:" + app.key
|
||||
override val installedAt get() = app.installedAt
|
||||
override val updatedAt get() = app.updatedAt
|
||||
}
|
||||
|
||||
class Folder(val folder: HomeFolders.Folder, val apps: List<HomeApp.LaunchableApp>) : AppEntry {
|
||||
override val label get() = folder.name
|
||||
override val key get() = "folder:" + folder.id
|
||||
override val installedAt get() = apps.maxOf { it.installedAt }
|
||||
override val updatedAt get() = apps.maxOf { it.updatedAt }
|
||||
}
|
||||
|
||||
class Shortcut(val pinned: HomePins.Pinned) : AppEntry {
|
||||
override val label get() = pinned.label
|
||||
override val key get() = pinned.key
|
||||
override val installedAt get() = 0L
|
||||
override val updatedAt get() = 0L
|
||||
}
|
||||
}
|
||||
|
||||
private fun indexLetter(label: String): String {
|
||||
val c = label.trim().firstOrNull()?.uppercaseChar() ?: return "#"
|
||||
return if (c in 'A'..'Z') c.toString() else if (c.isLetter()) c.toString() else "#"
|
||||
}
|
||||
|
||||
private fun searchRank(label: String, q: String): Int? {
|
||||
if (label.startsWith(q, ignoreCase = true)) return 0
|
||||
if (label.split(' ', '-', '_', '.').any { it.startsWith(q, ignoreCase = true) }) return 1
|
||||
if (label.contains(q, ignoreCase = true)) return 2
|
||||
return null
|
||||
}
|
||||
|
||||
internal fun Context.findActivity(): Activity? {
|
||||
var c: Context? = this
|
||||
while (c is ContextWrapper) {
|
||||
if (c is Activity) return c
|
||||
c = c.baseContext
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun Modifier.menuKey(onMenu: () -> Unit): Modifier = onPreviewKeyEvent { event ->
|
||||
val k = event.nativeKeyEvent
|
||||
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y && k.keyCode != KeyEvent.KEYCODE_MENU) false
|
||||
else {
|
||||
if (k.action == KeyEvent.ACTION_DOWN && k.repeatCount == 0) onMenu()
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
internal object AppsView {
|
||||
const val ALL = "all"
|
||||
const val GAMES = "games"
|
||||
const val DOWNLOADED = "downloaded"
|
||||
const val SYSTEM = "system"
|
||||
const val HIDDEN = "hidden"
|
||||
val FILTERS = listOf(ALL, GAMES, DOWNLOADED, SYSTEM, HIDDEN)
|
||||
const val NAME_ASC = "nameAsc"
|
||||
const val NAME_DESC = "nameDesc"
|
||||
const val INSTALLED = "installed"
|
||||
const val UPDATED = "updated"
|
||||
val SORTS = listOf(NAME_ASC, NAME_DESC, INSTALLED, UPDATED)
|
||||
|
||||
var filter by mutableStateOf(ALL)
|
||||
var sort by mutableStateOf(NAME_ASC)
|
||||
private var loaded = false
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("home_launcher", Context.MODE_PRIVATE)
|
||||
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val p = prefs(context)
|
||||
filter = p.getString("filter", ALL)?.takeIf { it in FILTERS } ?: ALL
|
||||
sort = p.getString("sort", NAME_ASC)?.takeIf { it in SORTS } ?: NAME_ASC
|
||||
}
|
||||
|
||||
fun setFilter(context: Context, value: String) {
|
||||
filter = value
|
||||
prefs(context).edit().putString("filter", value).apply()
|
||||
}
|
||||
|
||||
fun setSort(context: Context, value: String) {
|
||||
sort = value
|
||||
prefs(context).edit().putString("sort", value).apply()
|
||||
}
|
||||
|
||||
fun keeps(app: HomeApp.LaunchableApp): Boolean {
|
||||
val hidden = app.key in HomeHidden.keys
|
||||
return when (filter) {
|
||||
HIDDEN -> hidden
|
||||
GAMES -> !hidden && app.game
|
||||
DOWNLOADED -> !hidden && !app.system
|
||||
SYSTEM -> !hidden && app.system
|
||||
else -> !hidden
|
||||
}
|
||||
}
|
||||
|
||||
fun comparator(): Comparator<AppEntryKey> = when (sort) {
|
||||
NAME_DESC -> compareBy<AppEntryKey, String>(String.CASE_INSENSITIVE_ORDER) { it.label }.reversed()
|
||||
INSTALLED -> compareByDescending<AppEntryKey> { it.installedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label }
|
||||
UPDATED -> compareByDescending<AppEntryKey> { it.updatedAt }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.label }
|
||||
else -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }
|
||||
}
|
||||
}
|
||||
|
||||
internal interface AppEntryKey {
|
||||
val label: String
|
||||
val installedAt: Long
|
||||
val updatedAt: Long
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
internal fun AndroidAppsPage(s: FrontEndState, modifier: Modifier, onLaunch: (HomeApp.LaunchableApp) -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
remember { HomeFolders.load(ctx); HomeWidgets.load(ctx); HomeHidden.load(ctx); AppsView.load(ctx); true }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val narrow = LocalNarrowPane.current
|
||||
val padH = if (narrow) 16.dp else 22.dp
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
var openFolder by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var renameOnOpen by rememberSaveable { mutableStateOf(false) }
|
||||
var picking by rememberSaveable { mutableStateOf(false) }
|
||||
val folders = HomeFolders.folders
|
||||
val byKey = remember(s.androidApps) { s.androidApps.associateBy { it.key } }
|
||||
val byPkg = remember(s.androidApps) { s.androidApps.filterNot { it.work }.groupBy { it.packageName }.mapNotNull { (pkg, apps) -> apps.singleOrNull()?.let { pkg to it } }.toMap() }
|
||||
LaunchedEffect(byPkg) { if (byPkg.isNotEmpty()) HomeFolders.migrateMembers(ctx) { byPkg[it]?.key } }
|
||||
val member: (String) -> HomeApp.LaunchableApp? = { byKey[it] ?: byPkg[it] }
|
||||
val pins = HomePins.pinned
|
||||
val hidden = HomeHidden.keys
|
||||
val q = query.trim()
|
||||
val filter = AppsView.filter
|
||||
val sort = AppsView.sort
|
||||
val entries: List<AppEntry> = remember(s.androidApps, folders, q, filter, sort, pins, hidden) {
|
||||
val kept = s.androidApps.filter { AppsView.keeps(it) }
|
||||
val shortcuts = if (filter == AppsView.ALL) pins.map { AppEntry.Shortcut(it) } else emptyList()
|
||||
if (q.isNotEmpty()) {
|
||||
(kept.map { AppEntry.App(it) } + shortcuts).mapNotNull { e -> searchRank(e.label, q)?.let { it to e } }
|
||||
.sortedWith(compareBy<Pair<Int, AppEntry>> { it.first }.thenBy(String.CASE_INSENSITIVE_ORDER) { it.second.label })
|
||||
.map { it.second }
|
||||
} else if (filter != AppsView.ALL) {
|
||||
kept.map { AppEntry.App(it) }.sortedWith(AppsView.comparator())
|
||||
} else {
|
||||
val folderEntries = folders.mapNotNull { f ->
|
||||
val apps = f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })
|
||||
if (apps.isEmpty()) null else AppEntry.Folder(f, apps)
|
||||
}
|
||||
val grouped = folderEntries.flatMap { f -> f.apps.map { it.key } }.toSet()
|
||||
(folderEntries + kept.filter { it.key !in grouped }.map { AppEntry.App(it) } + shortcuts).sortedWith(AppsView.comparator())
|
||||
}
|
||||
}
|
||||
val grid = rememberLazyGridState()
|
||||
LaunchedEffect(q, filter, sort) { grid.scrollToItem(0) }
|
||||
val widgetsShown = q.isEmpty() && filter == AppsView.ALL && HomeWidgets.widgets.isNotEmpty()
|
||||
val leadItems = if (widgetsShown) 1 else 0
|
||||
val byName = sort == AppsView.NAME_ASC || sort == AppsView.NAME_DESC
|
||||
val newFolder: (HomeApp.LaunchableApp) -> Unit = { app ->
|
||||
val f = HomeFolders.create(ctx, ctx.getString(R.string.apps_folder_default), app.key)
|
||||
renameOnOpen = true
|
||||
openFolder = f.id
|
||||
}
|
||||
|
||||
Box(modifier) {
|
||||
Column(Modifier.fillMaxSize().imePadding()) {
|
||||
Box(Modifier.fillMaxWidth().padding(start = padH, end = padH, top = if (narrow) 8.dp else 12.dp)) {
|
||||
ModeHeader(
|
||||
stringResource(R.string.content_android_apps), query, { query = it },
|
||||
placeholder = stringResource(R.string.apps_search_hint),
|
||||
clearSearchFocus = openFolder != null || picking,
|
||||
lead = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 2.dp, end = 4.dp)) {
|
||||
Text(stringResource(R.string.content_android_apps), fontSize = if (narrow) 20.sp else 24.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
|
||||
val shownCount = s.androidApps.count { AppsView.keeps(it) } + if (filter == AppsView.ALL) pins.size else 0
|
||||
Text(androidx.compose.ui.res.pluralStringResource(R.plurals.apps_count, shownCount, shownCount), fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
},
|
||||
) {
|
||||
AppsFilterButton()
|
||||
AppsSortButton()
|
||||
HeaderIconButton(stringResource(R.string.apps_add_widget), Icons.Filled.Widgets, "add-widget") {
|
||||
HomeWidgets.loadProviders(ctx)
|
||||
picking = true
|
||||
}
|
||||
}
|
||||
}
|
||||
Box(Modifier.weight(1f).fillMaxWidth()) {
|
||||
val scroller = q.isEmpty() && byName && entries.size > 16
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Adaptive(if (narrow) 84.dp else 96.dp),
|
||||
state = grid,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
contentPadding = PaddingValues(start = padH, end = if (scroller) padH + 22.dp else padH, top = 12.dp, bottom = 16.dp),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
if (widgetsShown) item(key = "widgets", span = { GridItemSpan(maxLineSpan) }) {
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val maxW = maxWidth
|
||||
FlowRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp),
|
||||
) {
|
||||
for (w in HomeWidgets.widgets) key(w.id) { WidgetCard(w, maxW.value.toInt()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (entries.isEmpty()) item(key = "empty", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Note(
|
||||
when {
|
||||
q.isNotEmpty() -> stringResource(R.string.apps_no_match, q)
|
||||
filter == AppsView.HIDDEN -> stringResource(R.string.apps_hidden_none)
|
||||
else -> stringResource(R.string.content_no_android_apps)
|
||||
},
|
||||
)
|
||||
}
|
||||
items(entries, key = { it.key }) { entry ->
|
||||
when (entry) {
|
||||
is AppEntry.App -> AppTile(
|
||||
entry.app, folderId = null, onLaunch = onLaunch, onNewFolder = newFolder,
|
||||
first = entry === entries.first(),
|
||||
)
|
||||
is AppEntry.Shortcut -> PinnedTile(entry.pinned, first = entry === entries.first())
|
||||
is AppEntry.Folder -> FolderTile(entry, first = entry === entries.first(), onOpen = { renameOnOpen = false; openFolder = entry.folder.id }) {
|
||||
renameOnOpen = true
|
||||
openFolder = entry.folder.id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (scroller) AlphabetScroller(entries, grid, leadItems, Modifier.align(Alignment.CenterEnd).fillMaxHeight().padding(end = 4.dp, top = 8.dp, bottom = 8.dp))
|
||||
}
|
||||
}
|
||||
|
||||
val folder = folders.firstOrNull { it.id == openFolder }
|
||||
LaunchedEffect(folder == null, openFolder) { if (folder == null && openFolder != null) openFolder = null }
|
||||
AnimatedVisibility(
|
||||
folder != null, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)),
|
||||
modifier = Modifier.fillMaxSize().zIndex(2f),
|
||||
) {
|
||||
var last by remember { mutableStateOf(folder) }
|
||||
if (folder != null) last = folder
|
||||
last?.let { f ->
|
||||
FolderSheet(f, f.apps.mapNotNull(member).filter { it.key !in hidden }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label }), renameOnOpen, onLaunch, newFolder) {
|
||||
openFolder = null
|
||||
renameOnOpen = false
|
||||
}
|
||||
}
|
||||
}
|
||||
AnimatedVisibility(
|
||||
picking, enter = fadeIn(Motion.tw(180)), exit = fadeOut(Motion.tw(160)),
|
||||
modifier = Modifier.fillMaxSize().zIndex(3f),
|
||||
) { WidgetPicker(padH) { picking = false } }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SwipeLock() {
|
||||
DisposableEffect(Unit) {
|
||||
PageSwipe.locks++
|
||||
onDispose { PageSwipe.locks-- }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun appsFilterLabel(filter: String): String = stringResource(
|
||||
when (filter) {
|
||||
AppsView.GAMES -> R.string.apps_filter_games
|
||||
AppsView.DOWNLOADED -> R.string.apps_filter_downloaded
|
||||
AppsView.SYSTEM -> R.string.apps_filter_system
|
||||
AppsView.HIDDEN -> R.string.apps_filter_hidden
|
||||
else -> R.string.apps_filter_all
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun appsSortLabel(sort: String): String = stringResource(
|
||||
when (sort) {
|
||||
AppsView.NAME_DESC -> R.string.apps_sort_name_desc
|
||||
AppsView.INSTALLED -> R.string.apps_sort_installed
|
||||
AppsView.UPDATED -> R.string.apps_sort_updated
|
||||
else -> R.string.apps_sort_name_asc
|
||||
},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun AppsFilterButton() = HeaderChoiceButton(
|
||||
stringResource(R.string.apps_filter), Icons.Filled.FilterAlt, "apps-filter",
|
||||
AppsView.FILTERS, AppsView.filter, { appsFilterLabel(it) }, AppsView::setFilter,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun AppsSortButton() = HeaderChoiceButton(
|
||||
stringResource(R.string.stores_sort), Icons.Filled.Sort, "apps-sort",
|
||||
AppsView.SORTS, AppsView.sort, { appsSortLabel(it) }, AppsView::setSort,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun HeaderChoiceButton(
|
||||
title: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String,
|
||||
options: List<String>, current: String, label: @Composable (String) -> String, onPick: (Context, String) -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
var at by remember { mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) }
|
||||
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
|
||||
HeaderIconButton("$title · ${label(current)}", icon, key) {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = options.size,
|
||||
handle = { Icon(icon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
) {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
options.forEachIndexed { i, option ->
|
||||
StepChoice(
|
||||
label(option), selected = option == current, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (option == current) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
onPick(ctx, option)
|
||||
Steps.fold()
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val firstAt = remember(entries) {
|
||||
val map = LinkedHashMap<String, Int>()
|
||||
entries.forEachIndexed { i, e -> map.putIfAbsent(indexLetter(e.label), i) }
|
||||
map
|
||||
}
|
||||
val letters = remember(firstAt) { firstAt.keys.toList() }
|
||||
var dragging by remember { mutableStateOf<String?>(null) }
|
||||
val current by remember(entries, leadItems) {
|
||||
derivedStateOf {
|
||||
val i = (grid.firstVisibleItemIndex - leadItems).coerceIn(0, (entries.size - 1).coerceAtLeast(0))
|
||||
entries.getOrNull(i)?.let { indexLetter(it.label) }
|
||||
}
|
||||
}
|
||||
var height by remember { mutableIntStateOf(1) }
|
||||
val jump: (Float) -> Unit = { y ->
|
||||
val i = ((y / height) * letters.size).toInt().coerceIn(0, letters.size - 1)
|
||||
val letter = letters[i]
|
||||
if (letter != dragging) {
|
||||
dragging = letter
|
||||
val at = firstAt[letter] ?: 0
|
||||
scope.launch { grid.scrollToItem(if (at == 0) 0 else leadItems + at) }
|
||||
}
|
||||
}
|
||||
Box(modifier.width(22.dp)) {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.fillMaxSize()
|
||||
.clip(RoundedCornerShape(11.dp))
|
||||
.background(if (dragging != null) colors.surface.copy(alpha = 0.85f) else Color.Transparent)
|
||||
.onSizeChanged { height = it.height.coerceAtLeast(1) }
|
||||
.pointerInput(letters) {
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown()
|
||||
down.consume()
|
||||
jump(down.position.y)
|
||||
while (true) {
|
||||
val event = awaitPointerEvent()
|
||||
val c = event.changes.firstOrNull { it.id == down.id } ?: break
|
||||
if (!c.pressed) break
|
||||
c.consume()
|
||||
jump(c.position.y)
|
||||
}
|
||||
dragging = null
|
||||
}
|
||||
},
|
||||
) {
|
||||
for (l in letters) {
|
||||
val on = l == (dragging ?: current)
|
||||
Text(
|
||||
l, fontSize = 10.sp, lineHeight = 11.sp, fontWeight = if (on) FontWeight.Bold else FontWeight.Medium,
|
||||
color = if (on) pal.signal else colors.onSurfaceVariant, textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
dragging?.let { l ->
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.align(Alignment.Center).offset { IntOffset(-64.dp.roundToPx(), 0) }.size(56.dp)
|
||||
.clip(CircleShape).background(pal.signal),
|
||||
) { Text(l, fontSize = 26.sp, fontWeight = FontWeight.Bold, color = pal.onPrimary) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun TileFrame(
|
||||
id: String, first: Boolean, onClick: () -> Unit, onMenu: () -> Unit,
|
||||
content: @Composable (hot: Boolean) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.95f else if (hot) 1.04f else 1f, Motion.sp(0.55f, Spring.StiffnessMedium), label = "appScale")
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
.paneItem("tile:$id").then(if (first) Modifier.firstTile().paneEntry() else Modifier)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(Shape12)
|
||||
.background(if (hot) colors.surface else colors.surface.copy(alpha = 0.55f))
|
||||
.glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp)
|
||||
.hoverable(src)
|
||||
.combinedClickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onLongClick = onMenu, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
.menuKey(onMenu)
|
||||
.padding(horizontal = 6.dp, vertical = 10.dp),
|
||||
) { content(hot) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TileLabel(text: String) = Text(
|
||||
text, fontSize = 12.sp, lineHeight = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun AppIcon(app: HomeApp.LaunchableApp, size: androidx.compose.ui.unit.Dp) {
|
||||
val icon = app.icon
|
||||
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(size))
|
||||
else Box(Modifier.size(size).clip(CircleShape).background(artBrush(hueOf(app.label))))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AppTile(
|
||||
app: HomeApp.LaunchableApp, folderId: String?, first: Boolean,
|
||||
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
|
||||
) {
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
TileFrame(app.key, first, onClick = { onLaunch(app) }, onMenu = { menu = true }) {
|
||||
AppIcon(app, 52.dp)
|
||||
TileLabel(app.label)
|
||||
}
|
||||
AppMenu(app, folderId, menu, onDismiss = { menu = false }, onNewFolder = onNewFolder)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AppMenu(
|
||||
app: HomeApp.LaunchableApp, folderId: String?, open: Boolean,
|
||||
onDismiss: () -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit,
|
||||
) {
|
||||
val ctx = LocalContext.current
|
||||
var choosing by remember { mutableStateOf(false) }
|
||||
var shortcuts by remember { mutableStateOf<List<Pair<ShortcutInfo, Bitmap?>>>(emptyList()) }
|
||||
LaunchedEffect(open) {
|
||||
if (!open) {
|
||||
choosing = false
|
||||
return@LaunchedEffect
|
||||
}
|
||||
shortcuts = withContext(Dispatchers.IO) {
|
||||
HomeApp.shortcuts(ctx, app).map { it to HomeApp.shortcutIcon(ctx, it, 64) }
|
||||
}
|
||||
}
|
||||
val isHidden = app.key in HomeHidden.keys
|
||||
AnchoredMenu(open, onDismiss = onDismiss, title = app.label, compact = true, minWidth = 200.dp) { first ->
|
||||
if (choosing) {
|
||||
val others = HomeFolders.folders.filter { it.id != folderId }
|
||||
var firstUsed = false
|
||||
for (f in others) key(f.id) {
|
||||
MenuItem(f.name, checked = false, focusRequester = if (!firstUsed) first.also { firstUsed = true } else null) {
|
||||
HomeFolders.add(ctx, f.id, app.key)
|
||||
onDismiss()
|
||||
}
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_new_folder), checked = false, focusRequester = if (others.isEmpty()) first else null) {
|
||||
onDismiss()
|
||||
onNewFolder(app)
|
||||
}
|
||||
} else {
|
||||
shortcuts.forEachIndexed { i, (info, icon) ->
|
||||
key(info.id) {
|
||||
MenuItem(
|
||||
info.shortLabel?.toString().orEmpty(), checked = false,
|
||||
focusRequester = if (i == 0) first else null,
|
||||
leading = { MenuIcon(icon) },
|
||||
) {
|
||||
onDismiss()
|
||||
runCatching { HomeApp.startShortcut(ctx, info) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (shortcuts.isNotEmpty()) Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(LocalPalette.current.line))
|
||||
if (!isHidden) MenuItem(stringResource(R.string.apps_add_to_folder), checked = false, focusRequester = if (shortcuts.isEmpty()) first else null) { choosing = true }
|
||||
if (folderId != null) MenuItem(stringResource(R.string.apps_remove_from_folder), checked = false) {
|
||||
HomeFolders.remove(ctx, app.key)
|
||||
onDismiss()
|
||||
}
|
||||
MenuItem(stringResource(if (isHidden) R.string.apps_unhide else R.string.apps_hide), checked = false,
|
||||
focusRequester = if (isHidden && shortcuts.isEmpty()) first else null) {
|
||||
onDismiss()
|
||||
HomeHidden.set(ctx, app.key, !isHidden)
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_app_info), checked = false) {
|
||||
onDismiss()
|
||||
runCatching { HomeApp.openAppInfo(ctx, app) }
|
||||
}
|
||||
if (HomeApp.canUninstall(app)) MenuItem(stringResource(R.string.apps_uninstall), checked = false) {
|
||||
onDismiss()
|
||||
runCatching { HomeApp.uninstall(ctx, app) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MenuIcon(icon: Bitmap?) {
|
||||
if (icon != null) Image(icon.asImageBitmap(), null, modifier = Modifier.size(20.dp))
|
||||
else Spacer(Modifier.size(20.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PinnedTile(pinned: HomePins.Pinned, first: Boolean) {
|
||||
val ctx = LocalContext.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
TileFrame(pinned.key, first, onClick = { runCatching { HomeApp.startShortcut(ctx, pinned.info) } }, onMenu = { menu = true }) {
|
||||
Box {
|
||||
val icon = pinned.icon
|
||||
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp))
|
||||
else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(pinned.label))))
|
||||
}
|
||||
TileLabel(pinned.label)
|
||||
}
|
||||
AnchoredMenu(menu, onDismiss = { menu = false }, title = pinned.label, compact = true, minWidth = 180.dp) { firstItem ->
|
||||
MenuItem(stringResource(R.string.apps_shortcut_remove), checked = false, detail = pinned.appLabel, focusRequester = firstItem) {
|
||||
menu = false
|
||||
HomePins.unpin(ctx, pinned)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FolderIcon(apps: List<HomeApp.LaunchableApp>, size: androidx.compose.ui.unit.Dp) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val cell = (size - 14.dp) / 2
|
||||
Box(
|
||||
Modifier.size(size).clip(RoundedCornerShape(size / 3.5f)).background(colors.surfaceVariant)
|
||||
.glideBorder(false, RoundedCornerShape(size / 3.5f), pal.signal, pal.line2)
|
||||
.padding(5.dp),
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
for (row in apps.take(4).chunked(2)) Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
for (a in row) AppIcon(a, cell)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FolderTile(entry: AppEntry.Folder, first: Boolean, onOpen: () -> Unit, onRename: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
TileFrame(entry.key, first, onClick = onOpen, onMenu = { menu = true }) {
|
||||
FolderIcon(entry.apps, 52.dp)
|
||||
TileLabel(entry.folder.name)
|
||||
}
|
||||
AnchoredMenu(menu, onDismiss = { menu = false }, title = entry.folder.name, compact = true, minWidth = 160.dp) { firstItem ->
|
||||
MenuItem(stringResource(R.string.apps_folder_rename), checked = false, focusRequester = firstItem) {
|
||||
menu = false
|
||||
onRename()
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_folder_ungroup), checked = false) {
|
||||
menu = false
|
||||
HomeFolders.delete(ctx, entry.folder.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FolderSheet(
|
||||
folder: HomeFolders.Folder, apps: List<HomeApp.LaunchableApp>, renameFirst: Boolean,
|
||||
onLaunch: (HomeApp.LaunchableApp) -> Unit, onNewFolder: (HomeApp.LaunchableApp) -> Unit, onClose: () -> Unit,
|
||||
) {
|
||||
SwipeLock()
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var renaming by remember(folder.id) { mutableStateOf(renameFirst) }
|
||||
var name by remember(folder.id) { mutableStateOf(if (renameFirst) "" else folder.name) }
|
||||
val commit = {
|
||||
val n = name.trim()
|
||||
if (n.isNotEmpty() && n != folder.name) HomeFolders.rename(ctx, folder.id, n)
|
||||
renaming = false
|
||||
}
|
||||
val close = { if (renaming) commit(); onClose() }
|
||||
BackHandler { close() }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f))
|
||||
.pointerInput(Unit) { awaitEachGesture { val d = awaitFirstDown(); d.consume(); close() } },
|
||||
) {
|
||||
val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true }
|
||||
AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160)), exit = scaleOut(Motion.tw(140)) + fadeOut(Motion.tw(140))) {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 620.dp).fillMaxWidth(0.9f).heightIn(max = 520.dp)
|
||||
.clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f))
|
||||
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
|
||||
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
|
||||
.controllerBack(close)
|
||||
.padding(16.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp)) {
|
||||
if (renaming) Box(Modifier.weight(1f)) {
|
||||
AdbTextField(
|
||||
value = name, onValueChange = { name = it.take(40) }, label = stringResource(R.string.apps_folder_name),
|
||||
keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, compact = true, showLabel = false,
|
||||
placeholder = folder.name, focusOnShow = true, onDone = { commit() },
|
||||
)
|
||||
} else {
|
||||
Text(folder.name, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
|
||||
SmallIconButton(Icons.Filled.Edit, stringResource(R.string.apps_folder_rename), tint = colors.onSurfaceVariant) { renaming = true }
|
||||
Spacer(Modifier.weight(1f))
|
||||
}
|
||||
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = colors.onSurfaceVariant) { close() }
|
||||
}
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Adaptive(92.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(apps, key = { it.key }) { app ->
|
||||
AppTile(app, folderId = folder.id, first = false, onLaunch = { onClose(); onLaunch(it) }, onNewFolder = onNewFolder)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WidgetCard(w: HomeWidgets.Placed, maxWidthDp: Int) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val width = w.widthDp.coerceAtMost(maxWidthDp)
|
||||
val activity = remember(ctx) { ctx.findActivity() }
|
||||
Box {
|
||||
Box(
|
||||
Modifier.size(width.dp, w.heightDp.dp)
|
||||
.clip(Shape16)
|
||||
.background(colors.surface.copy(alpha = 0.35f))
|
||||
.glideBorder(hot || menu, Shape16, pal.signal)
|
||||
.hoverable(src).focusable(interactionSource = src)
|
||||
.controllerConfirm { menu = true }
|
||||
.menuKey { menu = true },
|
||||
) {
|
||||
AndroidView(
|
||||
factory = { c ->
|
||||
(HomeWidgets.createView(c, w.id) ?: android.view.View(c)).apply {
|
||||
val radius = 16 * c.resources.displayMetrics.density
|
||||
outlineProvider = object : android.view.ViewOutlineProvider() {
|
||||
override fun getOutline(view: android.view.View, outline: android.graphics.Outline) =
|
||||
outline.setRoundRect(0, 0, view.width, view.height, radius)
|
||||
}
|
||||
clipToOutline = true
|
||||
}
|
||||
},
|
||||
update = { v ->
|
||||
if (v is HomeWidgets.HomeWidgetView) {
|
||||
v.onLongPress = { menu = true }
|
||||
HomeWidgets.applySize(v, width, w.heightDp)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
val (minW, minH) = remember(w.id) { HomeWidgets.minSize(ctx, w.id) }
|
||||
val index = HomeWidgets.widgets.indexOfFirst { it.id == w.id }
|
||||
val label = remember(w.id) { HomeWidgets.info(ctx, w.id)?.loadLabel(ctx.packageManager) ?: "" }
|
||||
AnchoredMenu(menu, onDismiss = { menu = false }, title = label, compact = true, minWidth = 180.dp) { first ->
|
||||
val step = 48
|
||||
MenuItem(stringResource(R.string.apps_widget_wider), checked = false, enabled = width < maxWidthDp, focusRequester = first) {
|
||||
HomeWidgets.resize(ctx, w.id, (width + step).coerceAtMost(maxWidthDp), w.heightDp)
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_widget_narrower), checked = false, enabled = width > minW) {
|
||||
HomeWidgets.resize(ctx, w.id, (width - step).coerceAtLeast(minW), w.heightDp)
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_widget_taller), checked = false, enabled = w.heightDp < 480) {
|
||||
HomeWidgets.resize(ctx, w.id, width, (w.heightDp + step).coerceAtMost(480))
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_widget_shorter), checked = false, enabled = w.heightDp > minH) {
|
||||
HomeWidgets.resize(ctx, w.id, width, (w.heightDp - step).coerceAtLeast(minH))
|
||||
}
|
||||
if (index > 0) MenuItem(stringResource(R.string.apps_widget_move_earlier), checked = false) { HomeWidgets.move(ctx, w.id, -1) }
|
||||
if (index in 0 until HomeWidgets.widgets.size - 1) MenuItem(stringResource(R.string.apps_widget_move_later), checked = false) { HomeWidgets.move(ctx, w.id, 1) }
|
||||
if (activity != null && HomeWidgets.canReconfigure(ctx, w.id)) MenuItem(stringResource(R.string.apps_widget_configure), checked = false) {
|
||||
menu = false
|
||||
HomeWidgets.reconfigure(activity, w.id)
|
||||
}
|
||||
MenuItem(stringResource(R.string.apps_widget_remove), checked = false) {
|
||||
menu = false
|
||||
HomeWidgets.remove(ctx, w.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WidgetPicker(padH: androidx.compose.ui.unit.Dp, onClose: () -> Unit) {
|
||||
SwipeLock()
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val activity = remember(ctx) { ctx.findActivity() }
|
||||
BackHandler { onClose() }
|
||||
val providers = HomeWidgets.providers
|
||||
Column(Modifier.fillMaxSize().background(colors.background).pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false) } }) {
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Adaptive(150.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
contentPadding = PaddingValues(horizontal = padH, vertical = 14.dp),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
item(key = "back", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column {
|
||||
Box(Modifier.padding(bottom = 10.dp)) { BackLink(stringResource(R.string.rail_apps), compact = true, onClick = onClose) }
|
||||
PageHeader(stringResource(R.string.apps_add_widget)) {
|
||||
if (providers != null) Chip(providers.size.toString(), ok = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
when {
|
||||
providers == null -> item(key = "loading", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_loading)) }
|
||||
providers.isEmpty() -> item(key = "none", span = { GridItemSpan(maxLineSpan) }) { Note(stringResource(R.string.apps_widgets_none)) }
|
||||
else -> items(providers, key = { it.info.provider.flattenToString() }) { p ->
|
||||
ProviderCard(p, first = p === providers.first()) {
|
||||
onClose()
|
||||
if (activity != null) HomeWidgets.add(activity, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProviderCard(p: HomeWidgets.Provider, first: Boolean, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().paneItem("widget:" + p.info.provider.flattenToString()).then(if (first) Modifier.firstTile() else Modifier)
|
||||
.clip(Shape12).background(colors.surface)
|
||||
.glideBorder(hot, Shape12, pal.signal, hotWidth = 2.5.dp)
|
||||
.hoverable(src)
|
||||
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick),
|
||||
) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxWidth().aspectRatio(1.6f).background(colors.surfaceVariant).padding(10.dp),
|
||||
) {
|
||||
val preview = p.preview
|
||||
if (preview != null) Image(preview.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
Column(Modifier.padding(horizontal = 10.dp, vertical = 8.dp)) {
|
||||
Text(p.label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val cells = "${(p.widthDp / 80f).roundToInt().coerceAtLeast(1)} × ${(p.heightDp / 80f).roundToInt().coerceAtLeast(1)}"
|
||||
Text(if (p.appLabel == p.label) cells else "${p.appLabel} · $cells", fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun PinRequestPrompt(label: String, appLabel: String, icon: Bitmap?, wide: Boolean, onAdd: () -> Unit, onCancel: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
BackHandler { onCancel() }
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.55f))
|
||||
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume(); onCancel() } },
|
||||
) {
|
||||
val shown = remember { androidx.compose.animation.core.MutableTransitionState(false) }.apply { targetState = true }
|
||||
AnimatedVisibility(shown, enter = scaleIn(Motion.sp(0.75f), initialScale = 0.92f) + fadeIn(Motion.tw(160))) {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = Modifier.widthIn(min = 280.dp, max = 420.dp)
|
||||
.clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f))
|
||||
.glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f))
|
||||
.pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }
|
||||
.controllerBack(onCancel)
|
||||
.padding(18.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.apps_pin_title).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
letterSpacing = 1.5.sp, color = colors.onSurfaceVariant,
|
||||
)
|
||||
if (wide && icon != null) Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = 180.dp).clip(Shape12).background(MaterialTheme.colorScheme.surface).padding(10.dp),
|
||||
) { Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxWidth()) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
if (!wide) {
|
||||
if (icon != null) Image(icon.asImageBitmap(), null, contentScale = ContentScale.Fit, modifier = Modifier.size(52.dp))
|
||||
else Box(Modifier.size(52.dp).clip(CircleShape).background(artBrush(hueOf(label))))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(label, fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(appLabel, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.common_cancel), onClick = onCancel)
|
||||
PrimaryButton(stringResource(R.string.apps_pin_add), onClick = onAdd)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.vector.addPathNodes
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
internal val CollectionsIcon: ImageVector = ImageVector.Builder("Collections", 24.dp, 24.dp, 24f, 24f).apply {
|
||||
for (d in listOf(
|
||||
"M2.65,4.6H7.33V22H2.65Z",
|
||||
"M8.32,2H13V22H8.32Z",
|
||||
"M13.9,5.4H18.5L21.4,22H16.8Z",
|
||||
)) addPath(addPathNodes(d), fill = SolidColor(Color.Black))
|
||||
}.build()
|
||||
@@ -699,7 +699,7 @@ fun ComponentsPage(
|
||||
|
||||
Box(Modifier.fillMaxSize().onGloballyPositioned { pageAt = it.positionInRoot() }.onFocusChanged { pageFocused = it.hasFocus }) {
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp).padding(top = if (narrow) 12.dp else 18.dp)
|
||||
Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)
|
||||
.then(if (selectedGame == null) Modifier.bumpers(
|
||||
onPrevious = { pick(layerStep(layer, -1)) },
|
||||
onNext = { pick(layerStep(layer, 1)) },
|
||||
@@ -972,7 +972,7 @@ private fun Stack(
|
||||
onFocus = { onFocus(l) }, onClick = { onOpen(l) },
|
||||
)
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
StackHeading(stringResource(R.string.comp_this_device))
|
||||
card(GPU_TAB)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
|
||||
@@ -10,8 +10,6 @@ import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.snap
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
@@ -107,7 +105,7 @@ import java.io.File
|
||||
internal fun Pane(
|
||||
s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
|
||||
) {
|
||||
BoxWithConstraints(modifier = modifier) {
|
||||
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) {
|
||||
@@ -140,19 +138,12 @@ internal fun Pane(
|
||||
before[0] = target
|
||||
val targetNow by rememberUpdatedState(target)
|
||||
val leave = if (Hops.linking) PageLeave.Link else PageLeave.Ordinary
|
||||
LaunchedEffect(target) {
|
||||
Hops.linking = false
|
||||
PageSwipe.direction = 0
|
||||
}
|
||||
LaunchedEffect(target) { Hops.linking = false }
|
||||
AnimatedContent(
|
||||
targetState = target,
|
||||
modifier = Modifier.onGloballyPositioned { paneAt[0] = it.positionInRoot() },
|
||||
transitionSpec = {
|
||||
val swipe = PageSwipe.direction
|
||||
when {
|
||||
swipe != 0 -> (fadeIn(Motion.tw(260, 40)) + slideInHorizontally(Motion.tw(360)) { it * swipe / 8 })
|
||||
.togetherWith(fadeOut(Motion.tw(160)) + slideOutHorizontally(Motion.tw(220)) { -it * swipe / 8 })
|
||||
.apply { targetContentZIndex = 1f }
|
||||
targetState in origins -> (fadeIn(Motion.tw(120)))
|
||||
.togetherWith(fadeOut(Motion.tw(320, 80)) + scaleOut(Motion.tw(480), targetScale = 0.95f))
|
||||
.apply { targetContentZIndex = 1f }
|
||||
@@ -171,7 +162,7 @@ internal fun Pane(
|
||||
label = "pane",
|
||||
) { key ->
|
||||
val drawn = (if (page != null && key == s.pageKey) page else pages[key])
|
||||
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging) }
|
||||
?: { Content(s, if (key == "games") gameShown[0] else key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb) }
|
||||
val hopSink by androidx.compose.animation.core.animateFloatAsState(
|
||||
if (Hops.sinking == key) 1f else 0f, Motion.tw(260), label = "hopSink",
|
||||
)
|
||||
@@ -232,7 +223,7 @@ private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, L
|
||||
private fun Content(
|
||||
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit, onPairWirelessDebugging: () -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
|
||||
@@ -241,13 +232,13 @@ private fun Content(
|
||||
val padH = if (narrow) 16.dp else 22.dp
|
||||
val padV = if (narrow) 12.dp else 18.dp
|
||||
if (selected == "setup") {
|
||||
Column(modifier = modifier.padding(horizontal = padH).padding(top = padV)) {
|
||||
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb, onPairWirelessDebugging)
|
||||
Column(modifier = modifier.padding(horizontal = padH, vertical = padV)) {
|
||||
SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (selected == "updates") {
|
||||
UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV))
|
||||
UpdatesPage(s, a, modifier.padding(horizontal = padH, vertical = padV))
|
||||
return
|
||||
}
|
||||
if (selected == "steam") {
|
||||
@@ -270,12 +261,24 @@ private fun Content(
|
||||
DesktopPage(s, a, modifier, onSelect)
|
||||
return
|
||||
}
|
||||
if (selected == "android-apps" && s.isHomeApp) {
|
||||
AndroidAppsPage(s, modifier, onAndroidAppClick)
|
||||
return
|
||||
}
|
||||
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = padH, vertical = padV)) {
|
||||
when {
|
||||
selected == "android-apps" && s.isHomeApp -> {
|
||||
Rise(0) { PageHeader(stringResource(R.string.content_android_apps)) { Chip(stringResource(R.string.content_apps_count, s.androidApps.size), ok = false) } }
|
||||
if (s.androidApps.isEmpty()) Rise(3) { Note(stringResource(R.string.content_no_android_apps)) }
|
||||
else Rise(3, Modifier.fillMaxWidth()) {
|
||||
ArtGrid(s.androidApps.map { app ->
|
||||
Tile(
|
||||
app.label,
|
||||
null,
|
||||
null,
|
||||
"android:${app.packageName}",
|
||||
onClick = { onAndroidAppClick(app) },
|
||||
iconBitmap = app.icon,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
selected.startsWith("user:") -> {
|
||||
val app = UserAppsState.items.firstOrNull { "user:${it.key}" == selected }
|
||||
if (app == null) Note(stringResource(R.string.user_apps_gone)) else UserAppPage(app, s, a, onSelect)
|
||||
|
||||
@@ -84,9 +84,7 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.layout.boundsInParent
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.LayoutCoordinates
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.onPlaced
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
|
||||
|
||||
@@ -101,15 +99,15 @@ internal fun BottomBar(
|
||||
val keys = navigationKeys(s)
|
||||
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
|
||||
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
|
||||
val content = remember { arrayOfNulls<LayoutCoordinates>(1) }
|
||||
var barAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
|
||||
Row(modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surface), verticalAlignment = Alignment.CenterVertically) {
|
||||
BoxWithConstraints(Modifier.weight(1f)) {
|
||||
val itemWidth = (maxWidth / keys.size).coerceIn(56.dp, 88.dp)
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onPlaced { content[0] = it }) {
|
||||
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f)
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).onGloballyPositioned { barAt = it.boundsInRoot().topLeft }) {
|
||||
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-barAt), tint, GlideAxis.Horizontal, corner = 14.dp, fill = 0.14f, outline = 0f)
|
||||
Row(Modifier.selectableGroup().padding(vertical = 4.dp), horizontalArrangement = Arrangement.Center) {
|
||||
NavigationItems(s, shown, compact = true, iconOnly = false, height = 56.dp, width = itemWidth,
|
||||
place = { key -> Modifier.onGloballyPositioned { item -> content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }; Hops.railBounds[key] = item.boundsInRoot() } },
|
||||
place = { key -> Modifier.onGloballyPositioned { bounds[key] = it.boundsInRoot(); Hops.railBounds[key] = it.boundsInRoot() } },
|
||||
onSelect = onSelect, onFocusSelect = onFocusSelect)
|
||||
}
|
||||
}
|
||||
@@ -118,7 +116,7 @@ internal fun BottomBar(
|
||||
}
|
||||
}
|
||||
|
||||
internal fun navigationKeys(s: FrontEndState) = buildList {
|
||||
private fun navigationKeys(s: FrontEndState) = buildList {
|
||||
add("steam"); add("games")
|
||||
if (s.gameStoresEnabled) add("stores")
|
||||
add("desktop"); add("components")
|
||||
@@ -145,18 +143,18 @@ internal fun SideRail(
|
||||
val keys = navigationKeys(s)
|
||||
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, androidx.compose.ui.geometry.Rect>() }
|
||||
val tint = androidx.compose.runtime.rememberUpdatedState(LocalPalette.current.signal)
|
||||
val content = remember { arrayOfNulls<LayoutCoordinates>(1) }
|
||||
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onPlaced { content[0] = it }) {
|
||||
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown], tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f)
|
||||
var railAt by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
|
||||
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).onGloballyPositioned { railAt = it.boundsInRoot().topLeft }) {
|
||||
if (shown in keys) ChipGlide(keys.indexOf(shown), bounds[shown]?.translate(-railAt), tint, GlideAxis.Vertical, corner = 14.dp, fill = 0.14f, outline = 0f)
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = Modifier.fillMaxWidth().selectableGroup(),
|
||||
) {
|
||||
val place: (String) -> Modifier = { key ->
|
||||
Modifier.onGloballyPositioned { item ->
|
||||
content[0]?.let { bounds[key] = it.localBoundingBoxOf(item) }
|
||||
Hops.railBounds[key] = item.boundsInRoot()
|
||||
Modifier.onGloballyPositioned {
|
||||
bounds[key] = it.boundsInRoot()
|
||||
Hops.railBounds[key] = it.boundsInRoot()
|
||||
}
|
||||
}
|
||||
NavigationItems(s, shown, compact, iconOnly, fit, if (iconOnly) 52.dp else 80.dp, place, onSelect, onFocusSelect)
|
||||
|
||||
@@ -99,8 +99,6 @@ class FrontEndState(
|
||||
val frameGenLabel: String,
|
||||
val romsDir: String?,
|
||||
val logsEnabled: Boolean,
|
||||
val gameDebugLogsEnabled: Boolean = false,
|
||||
val gameDebugLogsNeedsRestart: Boolean = false,
|
||||
val vacDiagnostics: Boolean = false,
|
||||
val agentCommands: Boolean = false,
|
||||
val clearCachedApps: Boolean = false,
|
||||
@@ -123,8 +121,6 @@ class FrontEndState(
|
||||
val isHomeApp: Boolean = false,
|
||||
val homeScreenEnabled: Boolean = false,
|
||||
val defaultHomeLabel: String? = null,
|
||||
val integration: com.droiddeck.launcher.core.SteamIntegration.State = com.droiddeck.launcher.core.SteamIntegration.State(suggested = false),
|
||||
val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null,
|
||||
val androidApps: List<HomeApp.LaunchableApp> = emptyList(),
|
||||
val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(),
|
||||
val packages: List<PackageRow>? = null,
|
||||
@@ -210,7 +206,6 @@ class FrontEndActions(
|
||||
val onFiles: () -> Unit,
|
||||
val onBrowseFiles: (File) -> Unit = {},
|
||||
val onLogs: () -> Unit,
|
||||
val onGameDebugLogs: () -> Unit = {},
|
||||
val onVacDiagnostics: () -> Unit = {},
|
||||
val onAgentCommands: () -> Unit = {},
|
||||
val onClearCachedApps: (Boolean) -> Unit = {},
|
||||
@@ -242,11 +237,6 @@ class FrontEndActions(
|
||||
val onLibraryChanged: () -> Unit = {},
|
||||
val onHomeApp: () -> Unit = {},
|
||||
val onHomeScreen: (Boolean) -> Unit = {},
|
||||
val onSteamIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature?) -> Unit = {},
|
||||
val onDismissIntegration: () -> Unit = {},
|
||||
val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {},
|
||||
val onIntegrationAppInfo: () -> Unit = {},
|
||||
val onIntegrationLocation: () -> Unit = {},
|
||||
val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> },
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onRefreshPhantomStatus: () -> Unit = {},
|
||||
@@ -258,8 +248,6 @@ class FrontEndActions(
|
||||
val onCopyPhantomCommand: (Boolean) -> Unit = {},
|
||||
val onDismissPhantomGate: () -> Unit = {},
|
||||
val onStartWirelessAdbPairing: () -> Unit = {},
|
||||
val onStartPairingGuide: (Int?) -> Boolean = { false },
|
||||
val onShowPhantomGate: () -> Unit = {},
|
||||
val onOpenNotificationSettings: () -> Unit = {},
|
||||
val controller: ControllerActions? = null,
|
||||
val updates: UpdatesActions = UpdatesActions(),
|
||||
@@ -420,7 +408,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
"stores:downloads" -> { com.droiddeck.launcher.stores.StoresState.openDownloads = true; selected = "stores" }
|
||||
"components" -> a.onComponents(true)
|
||||
"setup:launcher" -> { SetupTabs.openLauncher = true; selected = "setup" }
|
||||
"setup:integration" -> { SetupTabs.openOverview = true; selected = "setup" }
|
||||
else -> selected = target
|
||||
}
|
||||
a.onNavigated()
|
||||
@@ -430,7 +417,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
}
|
||||
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
|
||||
var developerChoiceGuided by rememberSaveable { mutableStateOf(false) }
|
||||
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -439,36 +425,9 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
|
||||
val requestDeveloperOptions = {
|
||||
developerChoiceGuided = false
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
val openDeveloperOptionsOn: (Int?) -> Unit = { displayId ->
|
||||
if (developerChoiceGuided) a.onStartWirelessAdbPairing()
|
||||
if (!developerChoiceGuided || !a.onStartPairingGuide(displayId)) a.onOpenDeveloperOptions(displayId)
|
||||
developerChoiceGuided = false
|
||||
}
|
||||
val startGuidedPairing = {
|
||||
if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) {
|
||||
wirelessAdbDesiredEnabled = false
|
||||
showWirelessAdbFix = true
|
||||
} else {
|
||||
developerChoiceGuided = true
|
||||
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
}
|
||||
var applyingSavedPairing by remember { mutableStateOf(false) }
|
||||
val fixPhantomLimit = {
|
||||
if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing()
|
||||
else if (!applyingSavedPairing) {
|
||||
applyingSavedPairing = true
|
||||
a.onSetPhantomProcessLimit(false) { error ->
|
||||
applyingSavedPairing = false
|
||||
if (error != null) startGuidedPairing()
|
||||
}
|
||||
}
|
||||
}
|
||||
val requestWirelessAdbFix: (Boolean) -> Unit = { enabled ->
|
||||
wirelessAdbDesiredEnabled = enabled
|
||||
showWirelessAdbFix = true
|
||||
@@ -510,7 +469,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
selected.startsWith("emu:") || selected.startsWith("rom:") || selected.startsWith("user:") || selected == "store" -> "desktop"
|
||||
else -> s.pageKey ?: selected
|
||||
}
|
||||
val railSelectionNow = androidx.compose.runtime.rememberUpdatedState(railSelection)
|
||||
var railPicks by remember { mutableStateOf(0) }
|
||||
val showRailPage: (String, Boolean) -> Unit = { key, focusContent ->
|
||||
if (key == "components") a.onComponents(focusContent)
|
||||
@@ -613,23 +571,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
},
|
||||
) {
|
||||
Pane(
|
||||
s, selected, a, page,
|
||||
Modifier.fillMaxSize().then(paneFocus).pageSwipe({ !processSettingsPageVisible && appToChooseDisplay == null }) { dir ->
|
||||
val keys = navigationKeys(s)
|
||||
val at = keys.indexOf(railSelectionNow.value)
|
||||
if (at >= 0) keys.getOrNull(at + dir)?.let { key ->
|
||||
PageSwipe.direction = dir
|
||||
showRailPage(key, false)
|
||||
}
|
||||
},
|
||||
{ selected = it },
|
||||
s, selected, a, page, Modifier.fillMaxSize().then(paneFocus), { selected = it },
|
||||
onAndroidAppClick = { app ->
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
},
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onRequestWirelessAdb = requestWirelessAdbFix,
|
||||
onPairWirelessDebugging = startGuidedPairing,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -663,8 +611,10 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
status = s.phantomProcessStatus,
|
||||
onDismiss = a.onDismissPhantomGate,
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
applyingSavedPairing = applyingSavedPairing,
|
||||
onFixWithWirelessDebugging = fixPhantomLimit,
|
||||
onFixWithWirelessDebugging = {
|
||||
a.onStartWirelessAdbPairing()
|
||||
requestDeveloperOptions()
|
||||
},
|
||||
onEnterAddressManually = { requestWirelessAdbFix(false) },
|
||||
onCopyCommand = { a.onCopyPhantomCommand(false) },
|
||||
onOpenNotificationSettings = a.onOpenNotificationSettings,
|
||||
@@ -690,16 +640,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
},
|
||||
onMainScreen = {
|
||||
showDeveloperDisplayChoice = false
|
||||
openDeveloperOptionsOn(null)
|
||||
a.onOpenDeveloperOptions(null)
|
||||
},
|
||||
onSecondaryScreen = { displayId ->
|
||||
showDeveloperDisplayChoice = false
|
||||
openDeveloperOptionsOn(displayId)
|
||||
},
|
||||
onDismiss = {
|
||||
showDeveloperDisplayChoice = false
|
||||
developerChoiceGuided = false
|
||||
a.onOpenDeveloperOptions(displayId)
|
||||
},
|
||||
onDismiss = { showDeveloperDisplayChoice = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,7 +91,6 @@ private const val LAUNCHER_TAB = 2
|
||||
|
||||
internal object SetupTabs {
|
||||
var openLauncher = false
|
||||
var openOverview = false
|
||||
}
|
||||
private const val GLASSES_TAB = 5
|
||||
|
||||
@@ -141,7 +140,6 @@ internal fun SetupPanel(
|
||||
a: FrontEndActions,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onRequestWirelessAdb: (Boolean) -> Unit,
|
||||
onPairWirelessDebugging: () -> Unit,
|
||||
) {
|
||||
val host = rememberMenuHost()
|
||||
val ctx = LocalContext.current
|
||||
@@ -193,7 +191,6 @@ internal fun SetupPanel(
|
||||
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
|
||||
var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) }
|
||||
SetupTabs.openLauncher = false
|
||||
if (SetupTabs.openOverview) { tab = 0; SetupTabs.openOverview = false }
|
||||
val chipFocus = remember { List(tabs.size) { FocusRequester() } }
|
||||
var tabTurned by remember { mutableStateOf(false) }
|
||||
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true }
|
||||
@@ -204,12 +201,6 @@ internal fun SetupPanel(
|
||||
tab = STORAGE_TAB
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
kotlinx.coroutines.delay(2_000)
|
||||
a.onRefreshPhantomStatus()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(tab) {
|
||||
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
@@ -286,7 +277,7 @@ internal fun SetupPanel(
|
||||
},
|
||||
divider = divider && !showLimitDetails,
|
||||
) {
|
||||
if (limitBlocks) PrimaryButton(stringResource(R.string.setup_fix_it), compact = true, onClick = a.onShowPhantomGate)
|
||||
if (limitBlocks) PrimaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_fix_it), compact = true) { showLimitDetails = !showLimitDetails }
|
||||
else if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
|
||||
SecondaryButton(if (showLimitDetails) stringResource(R.string.common_hide) else stringResource(R.string.setup_details), compact = true) { showLimitDetails = !showLimitDetails }
|
||||
}
|
||||
@@ -299,7 +290,11 @@ internal fun SetupPanel(
|
||||
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(vertical = 4.dp),
|
||||
)
|
||||
Actions {
|
||||
if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
|
||||
if (limitBlocks) {
|
||||
PrimaryButton(stringResource(R.string.setup_dev_options), compact = true, onClick = onOpenDeveloperOptions)
|
||||
SecondaryButton(stringResource(R.string.setup_use_wireless), compact = true, enabled = !processLimitBusy) { setProcessLimit(false) }
|
||||
SecondaryButton(stringResource(R.string.setup_check_again), compact = true, onClick = a.onRefreshPhantomStatus)
|
||||
} else if (s.phantomProcessStatus == PhantomProcessStatus.DISABLED) {
|
||||
SecondaryButton(stringResource(R.string.setup_limit_turn_on), compact = true, enabled = !processLimitBusy) { setProcessLimit(true) }
|
||||
}
|
||||
}
|
||||
@@ -346,7 +341,6 @@ internal fun SetupPanel(
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.setup_runtime)) { runtimeCheck(false) }
|
||||
SteamIntegrationGroup(s.integration, s.integrationFocus, a.onIntegration, a.onIntegrationAppInfo, a.onIntegrationLocation)
|
||||
}
|
||||
1 -> {
|
||||
val controller = s.controller
|
||||
@@ -475,12 +469,6 @@ internal fun SetupPanel(
|
||||
4 -> {
|
||||
SettingsGroup(stringResource(R.string.setup_tab_diagnostics)) {
|
||||
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
|
||||
ToggleRow(
|
||||
host, "game-debug-logs", stringResource(R.string.setup_game_debug_logs),
|
||||
stringResource(if (s.gameDebugLogsNeedsRestart) R.string.setup_game_debug_logs_restart else R.string.setup_game_debug_logs_hint),
|
||||
s.gameDebugLogsEnabled,
|
||||
enabled = s.logsEnabled,
|
||||
) { a.onGameDebugLogs() }
|
||||
ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() }
|
||||
ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
|
||||
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
|
||||
@@ -518,7 +506,7 @@ internal fun SetupPanel(
|
||||
)
|
||||
if (!s.adbPaired) ActionRow(
|
||||
stringResource(R.string.setup_adb_pair), stringResource(R.string.setup_adb_pair_hint),
|
||||
stringResource(R.string.setup_adb_pair_button), onPairWirelessDebugging,
|
||||
stringResource(R.string.setup_adb_pair_button), { onRequestWirelessAdb(false) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,12 +205,7 @@ internal fun GameDetail(
|
||||
GameHero(
|
||||
title, item, installed, game,
|
||||
Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 210.dp).onGloballyPositioned { StoresMotion.heroAt = it.boundsInRoot() },
|
||||
corner = {
|
||||
if (!s.shortcutPicker) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (installed != null && installed.sidecar.store == Store.ITCH) ItchCheckButton(installed)
|
||||
RemoveButton(title, game, installed, a)
|
||||
}
|
||||
},
|
||||
corner = { if (!s.shortcutPicker) RemoveButton(title, game, installed, a) },
|
||||
scores = scores.takeIf { !stacked },
|
||||
) {
|
||||
HeroEyebrow(source, game, item, installed, download?.location ?: failed?.location)
|
||||
@@ -224,9 +219,6 @@ internal fun GameDetail(
|
||||
}
|
||||
}
|
||||
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
|
||||
if (!s.shortcutPicker) Rise(2) {
|
||||
GameResourcesRow(title.takeUnless { it == id }.orEmpty(), game, Modifier.padding(top = 6.dp))
|
||||
}
|
||||
if (tab != null) Rise(2) {
|
||||
Column(Modifier.fillMaxWidth().padding(top = 14.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
val labels = tabs.map { t ->
|
||||
@@ -362,7 +354,6 @@ internal fun GameActions(
|
||||
GameShortcutMenu(game, a)
|
||||
EditArtButton(game)
|
||||
}
|
||||
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
|
||||
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
|
||||
if (store == Store.XBOX && installed != null && id != null) {
|
||||
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
|
||||
@@ -535,7 +526,7 @@ private fun EditArtButton(g: Library.SteamGame) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, id: String, danger: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
private fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, id: String, danger: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import java.net.URLEncoder
|
||||
|
||||
internal data class GameResource(@StringRes val label: Int, val url: String, @StringRes val detail: Int? = null)
|
||||
|
||||
internal fun gameResources(title: String, game: Library.SteamGame?): List<GameResource> {
|
||||
if (title.isBlank()) return emptyList()
|
||||
val query = URLEncoder.encode(title.trim(), "UTF-8").replace("+", "%20")
|
||||
val steamId = game?.takeIf { Library.fromSteamClient(it) && it.appId > 0 }?.appId
|
||||
return buildList {
|
||||
add(GameResource(R.string.game_resource_pcgw, "https://www.pcgamingwiki.com/w/index.php?search=$query"))
|
||||
add(GameResource(R.string.game_resource_guides, "https://gamefaqs.gamespot.com/search?game=$query"))
|
||||
if (steamId != null) {
|
||||
add(GameResource(R.string.game_resource_protondb, "https://www.protondb.com/app/$steamId", R.string.game_resource_protondb_detail))
|
||||
add(GameResource(R.string.game_resource_steam_cloud, "https://store.steampowered.com/account/remotestorageapp/?appid=$steamId", R.string.game_resource_steam_cloud_detail))
|
||||
}
|
||||
add(GameResource(R.string.game_resource_search, "https://www.google.com/search?q=$query"))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
internal fun GameResourcesRow(title: String, game: Library.SteamGame?, modifier: Modifier = Modifier) {
|
||||
val links = remember(title, game) { gameResources(title, game) }
|
||||
if (links.isEmpty()) return
|
||||
FlowRow(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
links.forEach { ResourceLink(it) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ResourceLink(link: GameResource) {
|
||||
val ctx = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(source)
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
val label = stringResource(link.label)
|
||||
val description = listOfNotNull(label, link.detail?.let { stringResource(it) }, stringResource(R.string.game_resources_browser)).joinToString(". ")
|
||||
val open = { openUrl(ctx, link.url) }
|
||||
val tint = if (hot) pal.signal else pal.onSurfaceVariant
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp),
|
||||
modifier = Modifier.paneItem("resource:${link.label}").heightIn(min = 44.dp).clip(shape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.08f) else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal, restColor = Color.Transparent)
|
||||
.semantics { contentDescription = description }
|
||||
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = open)
|
||||
.controllerConfirm(onClick = open).padding(horizontal = 8.dp),
|
||||
) {
|
||||
Text(label, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = tint, maxLines = 1)
|
||||
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = tint.copy(alpha = 0.65f), modifier = Modifier.size(11.dp))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
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.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
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.automirrored.filled.Login
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.drawBehind
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.gfn.GfnGame
|
||||
import com.droiddeck.launcher.stores.gfn.GfnState
|
||||
import com.droiddeck.launcher.stores.gfn.GfnStoreAccount
|
||||
|
||||
/** The GeForce NOW tab's chip key; it sits after the store tabs and is not a [com.droiddeck.launcher.stores.Store]. */
|
||||
internal const val GEFORCE_NOW = "geforce-now"
|
||||
|
||||
internal val GfnGreen = Color(0xFF76B900)
|
||||
internal val GfnColours = SourceColours(Color(0xFF1C2A0A), Color(0xFFCDEB8B), GfnGreen)
|
||||
|
||||
internal fun gfnPalette(base: Palette): Palette = Palette(
|
||||
base.id, base.label, base.detail, base.background, base.surface, base.surfaceVariant, base.line, base.line2,
|
||||
base.onBackground, base.onSurfaceVariant, primary = GfnGreen, primary2 = Color(0xFF5A8F00), onPrimary = Color(0xFF0B0B0D), signal = GfnGreen,
|
||||
good = base.good, error = base.error,
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun GfnTheme(content: @Composable () -> Unit) {
|
||||
val base = LocalPalette.current
|
||||
val p = remember(base) { gfnPalette(base) }
|
||||
val scheme = MaterialTheme.colorScheme.copy(primary = p.primary, onPrimary = p.onPrimary)
|
||||
CompositionLocalProvider(LocalPalette provides p) { MaterialTheme(colorScheme = scheme, typography = MaterialTheme.typography, content = content) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun GfnPane(height: Dp) {
|
||||
val ctx = LocalContext.current
|
||||
LaunchedEffect(Unit) { GfnState.start(ctx) }
|
||||
when (val phase = GfnState.phase) {
|
||||
GfnState.Phase.Loading -> Box(Modifier.fillMaxWidth().padding(top = 16.dp)) {
|
||||
androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
|
||||
}
|
||||
is GfnState.Phase.Failed -> Column(verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) {
|
||||
Note(phase.message)
|
||||
PrimaryButton(stringResource(R.string.gfn_try_again), main = true) { GfnState.start(ctx, force = true) }
|
||||
}
|
||||
is GfnState.Phase.SignedOut, is GfnState.Phase.Code -> Box(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(top = 4.dp, bottom = 16.dp)) {
|
||||
GfnSignInCard(phase, height)
|
||||
}
|
||||
is GfnState.Phase.SignedIn -> GfnStorefront(phase.user)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnSignInCard(phase: GfnState.Phase, height: Dp) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val narrow = LocalNarrowPane.current
|
||||
val shape = RoundedCornerShape(20.dp)
|
||||
Box(
|
||||
Modifier.fillMaxWidth().heightIn(min = height.coerceAtLeast(0.dp)).clip(shape)
|
||||
.background(Brush.linearGradient(listOf(GfnColours.fill, colors.background))).border(1.dp, pal.line, shape)
|
||||
.drawBehind {
|
||||
drawRect(Brush.radialGradient(listOf(GfnGreen.copy(alpha = 0.28f), Color.Transparent), center = Offset(size.width * 0.16f, size.height * 0.9f), radius = size.height * 0.8f))
|
||||
},
|
||||
) {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.align(Alignment.BottomStart).padding(start = if (narrow) 20.dp else 40.dp, bottom = if (narrow) 20.dp else 36.dp, end = 20.dp, top = 20.dp),
|
||||
) {
|
||||
Rise(2) {
|
||||
Text(
|
||||
stringResource(R.string.gfn_name), fontSize = if (narrow) 30.sp else 42.sp, lineHeight = if (narrow) 34.sp else 46.sp,
|
||||
fontWeight = FontWeight.Black, color = colors.onBackground,
|
||||
)
|
||||
}
|
||||
Text(stringResource(R.string.gfn_pitch), fontSize = 15.sp, color = colors.onBackground)
|
||||
Text(stringResource(R.string.gfn_unofficial), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
when (phase) {
|
||||
is GfnState.Phase.Code -> {
|
||||
Text(stringResource(R.string.gfn_code_hint, phase.url), fontSize = 14.sp, color = colors.onBackground)
|
||||
Text(phase.userCode, fontSize = 34.sp, fontWeight = FontWeight.Black, letterSpacing = 4.sp, color = GfnGreen)
|
||||
Actions {
|
||||
PrimaryButton(stringResource(R.string.gfn_open_page), main = true) { openUrl(ctx, phase.url) }
|
||||
SecondaryButton(stringResource(R.string.common_cancel)) { GfnState.cancelSignIn() }
|
||||
}
|
||||
Text(stringResource(R.string.gfn_code_waiting), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
else -> {
|
||||
(phase as? GfnState.Phase.SignedOut)?.error?.let { Text(it, fontSize = 13.sp, color = colors.error) }
|
||||
Rise(3) {
|
||||
PrimaryButton(stringResource(R.string.stores_signin), main = true, large = true, icon = Icons.AutoMirrored.Filled.Login) { GfnState.signIn(ctx) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val MODE_STORE = 0
|
||||
private const val MODE_LIBRARY = 1
|
||||
private const val MODE_ACCOUNTS = 2
|
||||
|
||||
@Composable
|
||||
private fun GfnStorefront(user: String) {
|
||||
val ctx = LocalContext.current
|
||||
var mode by rememberSaveable { mutableIntStateOf(MODE_STORE) }
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
val grid = rememberLazyGridState()
|
||||
LaunchedEffect(mode) {
|
||||
when (mode) {
|
||||
MODE_LIBRARY -> GfnState.loadLibrary(ctx)
|
||||
MODE_ACCOUNTS -> GfnState.loadAccounts(ctx)
|
||||
}
|
||||
grid.scrollToItem(0)
|
||||
}
|
||||
LaunchedEffect(Unit) { GfnState.loadLibrary(ctx) }
|
||||
LaunchedEffect(mode, query) { if (mode == MODE_STORE) GfnState.showStore(ctx, query) }
|
||||
val nearEnd by remember {
|
||||
derivedStateOf {
|
||||
val last = grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
|
||||
last >= grid.layoutInfo.totalItemsCount - 10
|
||||
}
|
||||
}
|
||||
LaunchedEffect(nearEnd, GfnState.storeGames.size, mode) {
|
||||
if (mode == MODE_STORE && nearEnd && GfnState.storeGames.isNotEmpty()) GfnState.loadStore(ctx, query, reset = false)
|
||||
}
|
||||
val words = query.trim().lowercase().split(' ').filter { it.isNotEmpty() }
|
||||
val library = GfnState.library
|
||||
val libraryShown = remember(library, query) { library.orEmpty().filter { game -> words.all { game.search.contains(it) } } }
|
||||
val full: androidx.compose.foundation.lazy.grid.LazyGridItemSpanScope.() -> GridItemSpan = { GridItemSpan(maxLineSpan) }
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Adaptive(CardWidth), state = grid, modifier = Modifier.fillMaxSize().focusGroup(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
|
||||
) {
|
||||
item(key = "profile", span = full) { Rise(1) { GfnProfile(user, library?.size, onRefresh = {
|
||||
when (mode) {
|
||||
MODE_STORE -> GfnState.loadStore(ctx, query, reset = true)
|
||||
MODE_LIBRARY -> GfnState.loadLibrary(ctx, force = true)
|
||||
else -> GfnState.loadAccounts(ctx)
|
||||
}
|
||||
}) } }
|
||||
item(key = "modes", span = full) {
|
||||
Rise(2) {
|
||||
val pills: @Composable () -> Unit = {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
GfnModePill(stringResource(R.string.gfn_mode_store), mode == MODE_STORE, "store") { mode = MODE_STORE; query = "" }
|
||||
GfnModePill(stringResource(R.string.gfn_mode_library), mode == MODE_LIBRARY, "library") { mode = MODE_LIBRARY; query = "" }
|
||||
GfnModePill(stringResource(R.string.gfn_mode_accounts), mode == MODE_ACCOUNTS, "accounts") { mode = MODE_ACCOUNTS; query = "" }
|
||||
}
|
||||
}
|
||||
if (mode == MODE_ACCOUNTS) Column(Modifier.fillMaxWidth()) {
|
||||
Box(Modifier.heightIn(min = 52.dp).padding(vertical = 4.dp), contentAlignment = Alignment.CenterStart) { pills() }
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(LocalPalette.current.line))
|
||||
} else ModeHeader(
|
||||
stringResource(R.string.gfn_name), query, { query = it },
|
||||
placeholder = if (mode == MODE_STORE) stringResource(R.string.gfn_search_store, GfnState.storeTotal)
|
||||
else stringResource(R.string.gfn_search_library, library?.size ?: 0),
|
||||
lead = pills,
|
||||
) {}
|
||||
}
|
||||
}
|
||||
when (mode) {
|
||||
MODE_STORE -> {
|
||||
GfnState.storeError?.let { line -> item(key = "error", span = full) { Note(line) } }
|
||||
val games = GfnState.storeGames
|
||||
items(games, key = { "gfn:${it.id}" }, contentType = { "game" }) { game -> GfnCard(game, first = game.id == games.first().id, showOwned = true) }
|
||||
if (GfnState.storeLoading) item(key = "loading", span = full) {
|
||||
if (games.isEmpty()) Note(stringResource(R.string.gfn_loading_store))
|
||||
else androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
|
||||
} else if (games.isEmpty() && GfnState.storeError == null) item(key = "empty", span = full) { GfnEmpty(stringResource(R.string.stores_nothing_matches)) }
|
||||
}
|
||||
MODE_LIBRARY -> {
|
||||
GfnState.libraryError?.let { line -> item(key = "error", span = full) { Note(line) } }
|
||||
when {
|
||||
library == null && GfnState.libraryError == null -> item(key = "loading", span = full) { Note(stringResource(R.string.gfn_loading_library)) }
|
||||
library?.isEmpty() == true -> item(key = "empty", span = full) { Note(stringResource(R.string.gfn_library_empty)) }
|
||||
libraryShown.isEmpty() && library != null -> item(key = "nothing", span = full) { GfnEmpty(stringResource(R.string.stores_nothing_matches)) }
|
||||
else -> items(libraryShown, key = { "gfn:${it.id}" }, contentType = { "game" }) { game ->
|
||||
GfnCard(game, first = game.id == libraryShown.first().id, showOwned = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
item(key = "note", span = full) {
|
||||
Text(stringResource(R.string.gfn_accounts_note), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 2.dp))
|
||||
}
|
||||
GfnState.accountsMessage?.let { line -> item(key = "message", span = full) { Note(line) } }
|
||||
val accounts = GfnState.accounts
|
||||
if (accounts == null) item(key = "loading", span = full) { androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp)) }
|
||||
else items(accounts, key = { "account:${it.provider}" }, span = { full() }) { account -> GfnAccountRow(account) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnEmpty(text: String) {
|
||||
Box(Modifier.padding(vertical = 32.dp).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
Text(text, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnProfile(user: String, owned: Int?, onRefresh: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(16.dp)
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 4.dp).clip(shape).background(colors.surface).border(1.dp, pal.line, shape)
|
||||
.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(36.dp).clip(CircleShape).background(GfnGreen)) {
|
||||
Text(user.take(1).uppercase().ifEmpty { "G" }, fontSize = 16.sp, fontWeight = FontWeight.Black, color = Color.Black)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(user, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (owned != null) stringResource(R.string.gfn_profile_line, owned) else stringResource(R.string.gfn_name),
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Actions {
|
||||
SecondaryButton(stringResource(R.string.stores_refresh), compact = true) { onRefresh() }
|
||||
ConfirmButton(stringResource(R.string.stores_signout_go), stringResource(R.string.gfn_signout_confirm), compact = true) { GfnState.signOut(ctx) }
|
||||
}
|
||||
}
|
||||
Text(stringResource(R.string.gfn_unofficial), fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 2)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnModePill(label: String, on: Boolean, key: String, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val shape = RoundedCornerShape(99.dp)
|
||||
Text(
|
||||
label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1,
|
||||
color = if (on) colors.onPrimary else if (hot) colors.onBackground else colors.onSurfaceVariant,
|
||||
modifier = Modifier.paneItem("gfnmode:$key").clip(shape)
|
||||
.background(if (on) pal.signal else Color.Transparent)
|
||||
.glideBorder(hot, shape, pal.signal, if (on) Color.Transparent else pal.line)
|
||||
.hoverable(src).clickable(role = Role.Tab, interactionSource = src, indication = LocalIndication.current, onClick = onClick)
|
||||
.controllerConfirm(onClick = onClick)
|
||||
.padding(horizontal = 14.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnCard(game: GfnGame, first: Boolean, showOwned: Boolean) {
|
||||
val ctx = LocalContext.current
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val pressed by src.collectIsPressedAsState()
|
||||
val scale by animateFloatAsState(if (pressed) 0.985f else 1f, Motion.sp(0.5f, Spring.StiffnessMedium), label = "gfnCardScale")
|
||||
val play = { GfnState.play(ctx, game) }
|
||||
Column(
|
||||
Modifier.fillMaxWidth().paneItem("card:gfn:${game.id}").then(if (first) Modifier.firstTile() else Modifier)
|
||||
.graphicsLayer { scaleX = scale; scaleY = scale }
|
||||
.clip(RoundedCornerShape(10.dp)).glideBorder(hot, RoundedCornerShape(10.dp), pal.signal, pal.line)
|
||||
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = play)
|
||||
.controllerConfirm(onClick = play),
|
||||
) {
|
||||
CardFace(game.title, game.imageUrl.ifEmpty { null }, null, null, hot) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
if (showOwned && game.inLibrary) Icon(Icons.Filled.Check, null, tint = GfnGreen, modifier = Modifier.size(11.dp))
|
||||
Text(game.store, fontSize = 9.sp, fontWeight = FontWeight.SemiBold, color = Color.White.copy(alpha = 0.75f), maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GfnAccountRow(account: GfnStoreAccount) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shape = RoundedCornerShape(14.dp)
|
||||
val busy = GfnState.accountsBusy
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(shape).background(colors.surface).border(1.dp, pal.line, shape).padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(36.dp).clip(Shape12).background(if (account.connected) GfnColours.fill else colors.surfaceVariant)) {
|
||||
Text(account.label.take(1).uppercase(), fontSize = 15.sp, fontWeight = FontWeight.Black, color = if (account.connected) GfnColours.ink else colors.onSurfaceVariant)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(account.label, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
when {
|
||||
account.status == "expired" -> stringResource(R.string.gfn_status_expired)
|
||||
account.status == "sync_error" -> stringResource(R.string.gfn_status_sync_error)
|
||||
account.connected && account.displayName.isNotEmpty() -> stringResource(R.string.gfn_status_connected_as, account.displayName)
|
||||
account.connected -> stringResource(R.string.gfn_status_connected)
|
||||
else -> stringResource(R.string.gfn_status_not_connected)
|
||||
},
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Box {
|
||||
when (GfnState.actionFor(account)) {
|
||||
"link" -> PrimaryButton(stringResource(if (account.connected) R.string.gfn_reconnect else R.string.gfn_connect), enabled = !busy, compact = true) { GfnState.link(ctx, account) }
|
||||
"sync" -> SecondaryButton(stringResource(R.string.gfn_sync), enabled = !busy, compact = true) { GfnState.sync(ctx, account) }
|
||||
"unlink" -> ConfirmButton(stringResource(R.string.gfn_disconnect), stringResource(R.string.gfn_disconnect_confirm), compact = true) { GfnState.unlink(ctx, account) }
|
||||
else -> if (account.provider == "STEAM" && !account.connected)
|
||||
Text(stringResource(R.string.gfn_steam_link), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.itch.ItchUpdate
|
||||
import com.droiddeck.launcher.stores.itch.ItchUpdates
|
||||
|
||||
@Composable
|
||||
internal fun ItchCheckButton(installed: InstalledStoreGame) {
|
||||
val ctx = LocalContext.current
|
||||
IconAction(Icons.Filled.Refresh, stringResource(R.string.store_check_updates), "game:check-updates", enabled = ItchUpdates.checkingKey == null) {
|
||||
ItchUpdates.checkGame(ctx, installed)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ItchUpdateButton(installed: InstalledStoreGame, enabled: Boolean) {
|
||||
val ctx = LocalContext.current
|
||||
val update = ItchUpdates.available[installed.key] ?: return
|
||||
var asking by remember { mutableStateOf(false) }
|
||||
SecondaryButton(stringResource(R.string.common_update), enabled = enabled) {
|
||||
if (update.replaced) asking = true else ItchUpdates.start(ctx, installed, update)
|
||||
}
|
||||
if (asking) ReplacedDialog(installed, update) { asking = false }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ReplacedDialog(installed: InstalledStoreGame, update: ItchUpdate, onDismiss: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
AppDialog(shown, close, "itchUpdate", wide = false, maxWidth = 460.dp) {
|
||||
DialogTitleRow(installed.sidecar.title, close)
|
||||
Text(
|
||||
stringResource(R.string.stores_itch_update_replaced, update.filename.ifBlank { update.uploadId }),
|
||||
fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
PrimaryButton(stringResource(R.string.common_update)) {
|
||||
close()
|
||||
ItchUpdates.start(ctx, installed, update)
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.common_cancel)) { close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,9 +89,6 @@ import com.droiddeck.launcher.stores.StoresState
|
||||
import com.droiddeck.launcher.stores.arrangeStoreTabs
|
||||
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollection
|
||||
import com.droiddeck.launcher.stores.itch.ItchCollections
|
||||
import com.droiddeck.launcher.stores.itch.ItchUpdates
|
||||
import com.droiddeck.launcher.stores.retainOrder
|
||||
import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter
|
||||
import com.droiddeck.launcher.stores.sortGames
|
||||
@@ -130,14 +127,6 @@ internal fun libraryEntries(
|
||||
return out.distinctBy { it.key }
|
||||
}
|
||||
|
||||
internal fun collectionEntries(all: List<LibraryEntry>, items: List<CatalogItem>): List<LibraryEntry> {
|
||||
val keys = items.map { it.key }.toSet()
|
||||
val itch = all.filter { it.source == Store.ITCH.id }
|
||||
val have = itch.mapNotNull { it.storeKey }.toSet()
|
||||
return itch.filter { it.storeKey in keys } +
|
||||
items.filter { it.key !in have }.map { LibraryEntry(GameRef.key(it), Store.ITCH.id, it.title, null, it, false) }
|
||||
}
|
||||
|
||||
internal fun installedFirst(entries: List<LibraryEntry>): List<LibraryEntry> = entries.partition { it.installed }.let { (on, off) -> on + off }
|
||||
|
||||
internal const val LIBRARY_ALL = "all"
|
||||
@@ -180,33 +169,19 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
val all = remember(s.steamGames, cloudRows, owned, installedStore) { libraryEntries(s.steamGames + cloudRows, owned, installedStore) }
|
||||
LaunchedEffect(Unit) { XboxLibraryFilter.load(ctx) }
|
||||
var showUninstalled by remember(LibraryView.ownedRequest) { mutableStateOf(SessionPrefs.libraryShowUninstalled(ctx)) }
|
||||
var collectionShows by remember { mutableStateOf<Pair<String, Boolean>?>(null) }
|
||||
val setShowUninstalled = { show: Boolean ->
|
||||
val picked = ItchCollections.selected.takeIf { LibraryView.source == Store.ITCH.id }
|
||||
if (picked != null) collectionShows = picked to show
|
||||
else {
|
||||
showUninstalled = show
|
||||
SessionPrefs.setLibraryShowUninstalled(ctx, show)
|
||||
}
|
||||
showUninstalled = show
|
||||
SessionPrefs.setLibraryShowUninstalled(ctx, show)
|
||||
}
|
||||
val itchSignedIn = owned.containsKey(Store.ITCH)
|
||||
val listed = librarySources(all, SessionPrefs.storesTabOrder(ctx))
|
||||
val sources = if (itchSignedIn && Store.ITCH.id !in listed) listed + Store.ITCH.id else listed
|
||||
val sources = librarySources(all, SessionPrefs.storesTabOrder(ctx))
|
||||
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
|
||||
val q = LibraryView.query.trim().lowercase()
|
||||
val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL
|
||||
LaunchedEffect(source, itchSignedIn) { if (source == Store.ITCH.id && itchSignedIn) {
|
||||
ItchCollections.load(ctx)
|
||||
ItchUpdates.check(ctx)
|
||||
} }
|
||||
val collection = if (source == Store.ITCH.id) ItchCollections.chosen() else null
|
||||
val pool = if (collection == null) all else collectionEntries(all, ItchCollections.gamesOf(collection.id).orEmpty())
|
||||
val matching = pool.filter {
|
||||
val matching = all.filter {
|
||||
(source == LIBRARY_ALL || it.source == source) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it)
|
||||
}
|
||||
val listUninstalled = if (collection == null) showUninstalled else collectionShows?.takeIf { it.first == collection.id }?.second ?: true
|
||||
val candidates = if (listUninstalled) matching else matching.filter { it.installed }
|
||||
val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed }
|
||||
val candidates = if (showUninstalled) matching else matching.filter { it.installed }
|
||||
val hiddenUninstalled = if (showUninstalled) 0 else matching.count { !it.installed }
|
||||
val sort = s.storesSort
|
||||
val sizeSort = sort == "sizeAsc" || sort == "sizeDesc"
|
||||
val installedAt = StoresState.installed.associate { it.key to it.sidecar.installedAt }
|
||||
@@ -289,7 +264,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
kotlinx.coroutines.delay(Motion.ms(240).toLong())
|
||||
focusWithinFrames({ ff.last?.startsWith("card:") == true }) { if (ff.firstTileAttached > 0) ff.firstTile else FocusRequester.Default }
|
||||
}
|
||||
if (all.isEmpty() && open == null && !itchSignedIn) {
|
||||
if (all.isEmpty() && open == null) {
|
||||
LibraryEmpty(s, a, modifier)
|
||||
return
|
||||
}
|
||||
@@ -297,7 +272,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
val detailScroll = rememberScrollState()
|
||||
var cycled by remember { mutableIntStateOf(0) }
|
||||
var gridFocused by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(source, sort, listUninstalled) { grid.scrollToItem(0) }
|
||||
LaunchedEffect(source, sort, showUninstalled) { grid.scrollToItem(0) }
|
||||
LaunchedEffect(cycled) {
|
||||
if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
|
||||
focusWithinFrames({ gridFocused }) {
|
||||
@@ -308,12 +283,12 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
|
||||
open, detailScroll,
|
||||
gridScrolled = { grid.firstVisibleItemIndex > 0 || grid.firstVisibleItemScrollOffset > 0 },
|
||||
onDetailFocus = { detailFocused = it },
|
||||
modifier = modifier.padding(horizontal = if (narrow) 14.dp else 22.dp).padding(top = if (narrow) 10.dp else 14.dp),
|
||||
modifier = modifier.padding(horizontal = if (narrow) 14.dp else 22.dp, vertical = if (narrow) 10.dp else 14.dp),
|
||||
wrap = { key, content -> StoreTheme(GameRef.parse(key).let { r -> r.store ?: r.game(s.steamGames)?.source?.let { Store.byId(it) } }) { content() } },
|
||||
grid = {
|
||||
LibraryGrid(
|
||||
s, a, grid, visible, split, visible.size, sources, source, sizesPending, syncing,
|
||||
showUninstalled = listUninstalled.takeIf { !s.shortcutPicker },onShowUninstalled = setShowUninstalled,
|
||||
showUninstalled = showUninstalled.takeIf { stores }, onShowUninstalled = setShowUninstalled,
|
||||
hiddenUninstalled = hiddenUninstalled,
|
||||
onSource = { LibraryView.source = it },
|
||||
onCycle = { step ->
|
||||
@@ -408,7 +383,7 @@ private fun LibraryGrid(
|
||||
contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp),
|
||||
) {
|
||||
item(key = "header", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = source == Store.ITCH.id) }
|
||||
Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled) }
|
||||
}
|
||||
item(key = "filters", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Rise(1) { LibraryFilters(sources, source, onSource) }
|
||||
@@ -455,7 +430,7 @@ private fun LazyGridScope.libraryGrid(entries: List<LibraryEntry>, empty: Int, t
|
||||
@Composable
|
||||
private fun LibraryHeader(
|
||||
s: FrontEndState, a: FrontEndActions, total: Int, searchCleared: Boolean, xbox: Boolean,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit, collections: Boolean,
|
||||
showUninstalled: Boolean?, onShowUninstalled: (Boolean) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val narrow = LocalNarrowPane.current
|
||||
@@ -472,7 +447,6 @@ private fun LibraryHeader(
|
||||
},
|
||||
) {
|
||||
if (showUninstalled != null || xbox) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox)
|
||||
if (collections) CollectionsButton()
|
||||
SortButton(s, a)
|
||||
ViewButton(s, a)
|
||||
GameFileFolderActions(s, a)
|
||||
@@ -586,7 +560,6 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) {
|
||||
download != null -> Text("${download.percent}%", fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
e.item != null && StoresState.isUnfinished(e.item) -> Text(stringResource(R.string.stores_resume), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
if (e.installed && e.storeKey?.let { it in ItchUpdates.available } == true) Text(stringResource(R.string.common_update), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
|
||||
if (size != null && size > 0) Text(formatBytes(size), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
|
||||
if (!e.installed) Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp))
|
||||
}
|
||||
@@ -643,7 +616,7 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) {
|
||||
private fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
@@ -660,7 +633,7 @@ internal fun HeaderIconButton(description: String, icon: androidx.compose.ui.gra
|
||||
|
||||
/** Choosing Library in the rail lands on the first game, as Play Steam does on the Steam page. */
|
||||
@Composable
|
||||
internal fun Modifier.paneEntry(): Modifier {
|
||||
private fun Modifier.paneEntry(): Modifier {
|
||||
val ff = LocalFrontFocus.current ?: return this
|
||||
androidx.compose.runtime.DisposableEffect(ff) {
|
||||
ff.primaryAttached++
|
||||
@@ -727,39 +700,6 @@ private fun LibraryFilterButton(showUninstalled: Boolean?, onShowUninstalled: (B
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CollectionsButton() {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val title = stringResource(R.string.itch_collections)
|
||||
val all = stringResource(R.string.stores_tab_all)
|
||||
var at by remember { mutableStateOf<Rect?>(null) }
|
||||
Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) {
|
||||
HeaderIconButton(title + " · " + (ItchCollections.chosen()?.title ?: all), CollectionsIcon, "itch-collections") {
|
||||
val from = at ?: return@HeaderIconButton
|
||||
val choices = listOf<ItchCollection?>(null) + ItchCollections.list
|
||||
Steps.ask(StepAsk(
|
||||
anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = choices.size,
|
||||
handle = { Icon(CollectionsIcon, null, tint = pal.signal, modifier = Modifier.size(18.dp)) },
|
||||
) {
|
||||
StepTitle(title)
|
||||
StepList {
|
||||
choices.forEachIndexed { i, c ->
|
||||
val picked = c?.id == ItchCollections.selected
|
||||
StepChoice(
|
||||
c?.let { it.title + " (" + it.count + ")" } ?: all, selected = picked, enabled = open,
|
||||
modifier = Modifier.fillMaxWidth().stepItem(i).then(if (picked) Modifier.focusRequester(first) else Modifier),
|
||||
) {
|
||||
ItchCollections.select(ctx, c?.id)
|
||||
Steps.fold()
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SortButton(s: FrontEndState, a: FrontEndActions) {
|
||||
val pal = LocalPalette.current
|
||||
|
||||
@@ -60,6 +60,7 @@ class ModeSettings(
|
||||
val hdr: Boolean,
|
||||
val hdrReason: String?,
|
||||
val gpuDrivers: String? = null,
|
||||
val performanceMode: Boolean = false,
|
||||
val upscaler: Int = 0,
|
||||
val upscaleSharpness: Int = 75,
|
||||
val touchMode: String,
|
||||
@@ -95,7 +96,11 @@ class ModeSettings(
|
||||
val bootMovieCustomName: String? = null,
|
||||
val bootMovieImporting: Boolean = false,
|
||||
val bootMovieProgress: Int = -1,
|
||||
val integration: com.droiddeck.launcher.core.SteamIntegration.State? = null,
|
||||
val wifiDiscovery: Boolean? = null,
|
||||
val wifiDiscoveryPermission: Boolean = false,
|
||||
val wifiDiscoveryLocation: Boolean = false,
|
||||
val wifiDiscoveryAsked: Boolean = false,
|
||||
val wifiDiscoveryBlocked: Boolean = false,
|
||||
val deckyInstalled: String? = null,
|
||||
val deckyLatestRelease: DeckyManager.Release? = null,
|
||||
val deckyBranch: Int = DeckyManager.BRANCH_STABLE,
|
||||
@@ -111,6 +116,7 @@ class ModeSettingsActions(
|
||||
val onResolution: (String) -> Unit,
|
||||
val onHdr: (Boolean) -> Unit,
|
||||
val onGpuDrivers: () -> Unit = {},
|
||||
val onPerformanceMode: (Boolean) -> Unit = {},
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
val onTouch: (String) -> Unit,
|
||||
@@ -142,9 +148,8 @@ class ModeSettingsActions(
|
||||
val onBootMovieSound: (Boolean) -> Unit = {},
|
||||
val onImportBootMovie: () -> Unit = {},
|
||||
val onBootMovieChanged: () -> Unit = {},
|
||||
val onIntegration: (com.droiddeck.launcher.core.SteamIntegration.Feature) -> Unit = {},
|
||||
val onIntegrationAppInfo: () -> Unit = {},
|
||||
val onIntegrationLocation: () -> Unit = {},
|
||||
val onWifiDiscovery: (Boolean) -> Unit = {},
|
||||
val onWifiDiscoverySettings: () -> Unit = {},
|
||||
val onDeckyInstall: (DeckyManager.Release) -> Unit = {},
|
||||
val onDeckyCheck: () -> Unit = {},
|
||||
val onDeckyBranch: (Int) -> Unit = {},
|
||||
@@ -203,6 +208,7 @@ class SheetExtras(
|
||||
fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) {
|
||||
val steam = s.mode == SessionService.MODE_STEAM
|
||||
val host = rememberMenuHost()
|
||||
var explainWifiDiscovery by remember { mutableStateOf(false) }
|
||||
if (tab == SheetTab.DISPLAY) {
|
||||
val context = LocalContext.current
|
||||
val portraitWindow = SessionPrefs.portrait(context)
|
||||
@@ -242,6 +248,10 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
format = { "$it%" }, onChange = a.onUpscaleSharpness,
|
||||
)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.display_frame_rate)) {
|
||||
ToggleRow(host, "performance", stringResource(R.string.mode_performance), stringResource(R.string.mode_performance_hint),
|
||||
s.performanceMode, onChange = a.onPerformanceMode)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.mode_hdr)) {
|
||||
ToggleRow(
|
||||
host, "hdr", stringResource(R.string.mode_hdr10),
|
||||
@@ -502,9 +512,39 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
)
|
||||
}
|
||||
if (s.bootMovie != null) BootMovieGroup(s, a, host)
|
||||
if (s.integration != null) SteamIntegrationGroup(s.integration,
|
||||
onFeature = a.onIntegration, onAppInfo = a.onIntegrationAppInfo, onLocation = a.onIntegrationLocation)
|
||||
if (s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
|
||||
val hint = when {
|
||||
s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off)
|
||||
!s.wifiDiscoveryPermission && s.wifiDiscoveryAsked -> stringResource(R.string.mode_wifi_permission_denied)
|
||||
else -> stringResource(R.string.mode_wifi_discovery_hint)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.mode_wifi_discovery), hint) {
|
||||
Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
|
||||
horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp)) {
|
||||
if (s.wifiDiscoveryBlocked || (s.wifiDiscovery && !s.wifiDiscoveryLocation)) {
|
||||
SecondaryButton(stringResource(R.string.mode_wifi_open_settings), onClick = a.onWifiDiscoverySettings)
|
||||
}
|
||||
ToggleSwitch(s.wifiDiscovery, label = stringResource(R.string.mode_wifi_discovery)) { on ->
|
||||
host.open = null
|
||||
if (on) explainWifiDiscovery = true else a.onWifiDiscovery(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (explainWifiDiscovery) AlertDialog(
|
||||
onDismissRequest = { explainWifiDiscovery = false },
|
||||
title = { Text(stringResource(R.string.mode_wifi_explain_title)) },
|
||||
text = { Text(stringResource(R.string.mode_wifi_explain_text)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { explainWifiDiscovery = false; a.onWifiDiscovery(true) }, modifier = Modifier.focusGlide(CircleShape)) {
|
||||
Text(stringResource(if (s.wifiDiscoveryBlocked) R.string.mode_wifi_open_settings else R.string.mode_wifi_continue))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { explainWifiDiscovery = false }, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.input.pointer.util.VelocityTracker
|
||||
import androidx.compose.ui.input.pointer.util.addPointerInputChange
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlin.math.abs
|
||||
|
||||
internal object PageSwipe {
|
||||
var locks by mutableIntStateOf(0)
|
||||
var direction by mutableIntStateOf(0)
|
||||
}
|
||||
|
||||
// Runs on the Final pass so carousels, sliders, scrollers and widgets that consumed the drag keep it.
|
||||
@Composable
|
||||
internal fun Modifier.pageSwipe(enabled: () -> Boolean, onSwipe: (Int) -> Unit): Modifier {
|
||||
val enabledNow by rememberUpdatedState(enabled)
|
||||
val onSwipeNow by rememberUpdatedState(onSwipe)
|
||||
return pointerInput(Unit) {
|
||||
val distance = 72.dp.toPx()
|
||||
val flingDistance = 32.dp.toPx()
|
||||
val flingVelocity = 900.dp.toPx()
|
||||
val slop = viewConfiguration.touchSlop
|
||||
awaitEachGesture {
|
||||
val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Final)
|
||||
if (!enabledNow() || PageSwipe.locks > 0) return@awaitEachGesture
|
||||
val tracker = VelocityTracker()
|
||||
tracker.addPointerInputChange(down)
|
||||
var total = Offset.Zero
|
||||
var mine = false
|
||||
while (true) {
|
||||
val event = awaitPointerEvent(PointerEventPass.Final)
|
||||
if (event.changes.size > 1) return@awaitEachGesture
|
||||
val change = event.changes.firstOrNull { it.id == down.id } ?: return@awaitEachGesture
|
||||
if (!change.pressed) break
|
||||
if (!mine && change.isConsumed) return@awaitEachGesture
|
||||
total += change.position - change.previousPosition
|
||||
tracker.addPointerInputChange(change)
|
||||
if (!mine && abs(total.x) > slop && abs(total.x) > abs(total.y) * 2f) mine = true
|
||||
if (mine) change.consume()
|
||||
}
|
||||
if (!mine || PageSwipe.locks > 0) return@awaitEachGesture
|
||||
val vx = tracker.calculateVelocity().x
|
||||
val horizontal = abs(total.x) > abs(total.y) * 1.5f
|
||||
val far = abs(total.x) > distance
|
||||
val flung = abs(total.x) > flingDistance && abs(vx) > flingVelocity && (vx > 0) == (total.x > 0)
|
||||
if (horizontal && (far || flung)) onSwipeNow(if (total.x < 0) 1 else -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,6 @@ import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage
|
||||
@Composable
|
||||
fun PhantomProcessGatePage(
|
||||
status: PhantomProcessStatus,
|
||||
applyingSavedPairing: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onFixWithWirelessDebugging: () -> Unit,
|
||||
@@ -78,7 +77,7 @@ fun PhantomProcessGatePage(
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val wide = maxWidth >= 620.dp
|
||||
val fix: @Composable ColumnScope.() -> Unit = {
|
||||
FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging,
|
||||
FixGroup(hasToggle, stage, environment, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging,
|
||||
onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) })
|
||||
}
|
||||
val side: @Composable ColumnScope.() -> Unit = {
|
||||
@@ -120,7 +119,6 @@ private fun FixGroup(
|
||||
stage: Stage,
|
||||
environment: GateEnvironment,
|
||||
compact: Boolean,
|
||||
applyingSavedPairing: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onFixWithWirelessDebugging: () -> Unit,
|
||||
onOpenNotificationSettings: () -> Unit,
|
||||
@@ -133,10 +131,6 @@ private fun FixGroup(
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
when {
|
||||
applyingSavedPairing -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
Body(stringResource(R.string.adbpair_applying))
|
||||
}
|
||||
pairing -> PairingProgress(stage, onCancel)
|
||||
hasToggle -> {
|
||||
Body(stringResource(R.string.gate_toggle_steps))
|
||||
|
||||
@@ -38,7 +38,6 @@ import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.material.icons.outlined.DesktopWindows
|
||||
import androidx.compose.material.icons.outlined.Layers
|
||||
import androidx.compose.material.icons.outlined.ScreenShare
|
||||
import androidx.compose.material.icons.outlined.Pause
|
||||
import androidx.compose.material.icons.outlined.PictureInPictureAlt
|
||||
import androidx.compose.material.icons.automirrored.outlined.ExitToApp
|
||||
import androidx.compose.material.icons.outlined.Settings
|
||||
@@ -216,8 +215,6 @@ class DrawerActions(
|
||||
val micEnabled: Boolean = false,
|
||||
val onMicEnabled: (Boolean) -> Unit = {},
|
||||
val backActionsInverted: Boolean,
|
||||
val backDoubleTapMs: Int = 500,
|
||||
val onBackDoubleTapMs: (Int) -> Unit = {},
|
||||
val padType: String? = null,
|
||||
val onPadType: (String) -> Unit = {},
|
||||
val touchMode: String,
|
||||
@@ -286,7 +283,6 @@ class DrawerActions(
|
||||
val pipSupported: Boolean = false,
|
||||
val pipAutoEnter: Boolean = false,
|
||||
val onPip: () -> Unit = {},
|
||||
val onPause: () -> Unit = {},
|
||||
val onPipAutoEnter: (Boolean) -> Unit = {},
|
||||
val unfoldedControls: Boolean? = null,
|
||||
val onUnfoldedControls: (Boolean) -> Unit = {},
|
||||
@@ -429,15 +425,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
}
|
||||
.padding(12.dp),
|
||||
) {
|
||||
val title = a.title ?: if (a.steam) stringResource(R.string.drawer_steam) else stringResource(R.string.drawer_desktop)
|
||||
if (narrow) Text(title, fontSize = 18.sp, fontWeight = FontWeight.Bold,
|
||||
color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 6.dp))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp),
|
||||
) {
|
||||
Spacer(Modifier.weight(1f))
|
||||
SteamActionPill(
|
||||
stringResource(R.string.stores_dl_pause), Icons.Outlined.Pause, focus.track(page, "pause"),
|
||||
) { host.open = null; a.onPause() }
|
||||
if (narrow) Spacer(Modifier.weight(1f)) else Text(title, fontSize = 18.sp, fontWeight = FontWeight.Bold,
|
||||
color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (a.pipSupported) SteamActionPill(
|
||||
stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt, focus.track(page, "pip"),
|
||||
) { host.open = null; a.onPip() }
|
||||
@@ -564,11 +562,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
ChoiceRow(host, "touch", stringResource(R.string.mode_touch), null,
|
||||
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)),
|
||||
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
|
||||
if (a.touchMode == SessionPrefs.TOUCH_GESTURES) {
|
||||
ActionRow(stringResource(R.string.gesture_settings), null,
|
||||
stringResource(R.string.ctrl_edit), a.onGestureSettings,
|
||||
modifier = focus.track(page, "gesture-settings"))
|
||||
}
|
||||
ActionRow(stringResource(R.string.gesture_settings), stringResource(R.string.gesture_settings_hint),
|
||||
stringResource(R.string.ctrl_edit), a.onGestureSettings,
|
||||
modifier = focus.track(page, "gesture-settings"))
|
||||
if (a.onScreenKeys != null) {
|
||||
SettingsRow(stringResource(R.string.screen_keys), null, stacked = narrow) {
|
||||
Row(
|
||||
@@ -611,9 +607,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.mode_back), null,
|
||||
listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)),
|
||||
a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted)
|
||||
if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null,
|
||||
SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) },
|
||||
a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs)
|
||||
if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls),
|
||||
stringResource(R.string.unfolded_controls_hint), a.unfoldedControls,
|
||||
chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls)
|
||||
|
||||
@@ -77,7 +77,6 @@ class PausedFrame(val image: ImageBitmap, val bounds: android.graphics.Rect)
|
||||
|
||||
private const val CARD_SCALE = 0.82f
|
||||
private const val FRAME_WAIT_MS = 600L
|
||||
private val PopEasing = CubicBezierEasing(0.3f, 1.5f, 0.4f, 1f)
|
||||
|
||||
private fun tone(saturation: Float, brightness: Float): ColorMatrix =
|
||||
ColorMatrix().apply {
|
||||
@@ -91,7 +90,6 @@ fun SessionPausedOverlay(
|
||||
engaged: Boolean,
|
||||
failures: Int,
|
||||
frame: PausedFrame?,
|
||||
animateIn: Boolean,
|
||||
title: String,
|
||||
onResume: () -> Unit,
|
||||
onFrameNeeded: () -> Unit,
|
||||
@@ -108,18 +106,6 @@ fun SessionPausedOverlay(
|
||||
LaunchedEffect(suspended, engaged) {
|
||||
when {
|
||||
suspended && !engaged -> {
|
||||
if (!shown && animateIn) {
|
||||
if (currentFrame == null) {
|
||||
onFrameNeeded()
|
||||
withTimeoutOrNull(FRAME_WAIT_MS) { snapshotFlow { currentFrame }.first { it != null } }
|
||||
}
|
||||
shown = true
|
||||
launch { press.animateTo(1f, Motion.sp(0.5f, Spring.StiffnessMedium)) }
|
||||
launch { ring.animateTo(0f, Motion.tw(200)) }
|
||||
launch { lift.animateTo(1f, Motion.tw(520)) }
|
||||
orb.animateTo(1f, Motion.tw(380, delay = if (orb.value < 0.5f) 260 else 0, easing = PopEasing))
|
||||
return@LaunchedEffect
|
||||
}
|
||||
if (!shown) {
|
||||
if (currentFrame == null) {
|
||||
onFrameNeeded()
|
||||
|
||||
@@ -422,7 +422,7 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = null, content: @Composable ColumnScope.() -> Unit) {
|
||||
fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable ColumnScope.() -> Unit) {
|
||||
val tight = compact || LocalCompactSettings.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
@@ -434,7 +434,6 @@ fun SettingsGroup(title: String, compact: Boolean = false, detail: String? = nul
|
||||
) {
|
||||
Text(title.uppercase(), fontSize = if (tight) 11.sp else 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant)
|
||||
Box(modifier = Modifier.weight(1f).height(1.dp).background(pal.line))
|
||||
if (detail != null) Text(detail, fontSize = if (tight) 11.sp else 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant)
|
||||
}
|
||||
Column(modifier = Modifier.fillMaxWidth().clip(GroupShape).background(colors.surface).border(1.dp, pal.line, GroupShape)) { content() }
|
||||
}
|
||||
|
||||
@@ -143,8 +143,6 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
||||
words = {
|
||||
val runtimeStatus: @Composable () -> Unit = {
|
||||
if (s.busy || !s.ready || (s.available != null && s.available != s.installed)) RuntimeChip(s)
|
||||
else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus))
|
||||
IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration)
|
||||
}
|
||||
if (narrow) Column(
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.onPlaced { words = it.boundsInParent() },
|
||||
|
||||
@@ -1,215 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.relocation.BringIntoViewRequester
|
||||
import androidx.compose.foundation.relocation.bringIntoViewRequester
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.AutoAwesome
|
||||
import androidx.compose.material.icons.outlined.Close
|
||||
import androidx.compose.material.icons.outlined.Home
|
||||
import androidx.compose.material.icons.outlined.KeyboardCommandKey
|
||||
import androidx.compose.material.icons.outlined.LightMode
|
||||
import androidx.compose.material.icons.outlined.Wifi
|
||||
import androidx.compose.material3.Icon
|
||||
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
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.SteamIntegration
|
||||
import com.droiddeck.launcher.core.SteamIntegration.Feature
|
||||
|
||||
private val BadgeShape = RoundedCornerShape(10.dp)
|
||||
|
||||
internal fun SteamIntegration.State.enabled(feature: Feature) = when (feature) {
|
||||
Feature.WIFI -> wifi && locationPermission && locationOn
|
||||
Feature.BRIGHTNESS -> brightness
|
||||
Feature.HOME -> home
|
||||
Feature.SHORTCUTS -> home && shortcuts
|
||||
}
|
||||
|
||||
internal fun SteamIntegration.State.enabledCount() = Feature.entries.count { enabled(it) }
|
||||
|
||||
@Composable
|
||||
internal fun SteamIntegrationGroup(
|
||||
state: SteamIntegration.State,
|
||||
focus: Feature? = null,
|
||||
onFeature: (Feature) -> Unit,
|
||||
onAppInfo: () -> Unit,
|
||||
onLocation: () -> Unit = {},
|
||||
) {
|
||||
SettingsGroup(
|
||||
stringResource(R.string.integration_title),
|
||||
detail = stringResource(R.string.integration_count, state.enabledCount(), Feature.entries.size),
|
||||
) {
|
||||
Feature.entries.forEachIndexed { i, feature ->
|
||||
IntegrationRow(state, feature, focus == feature, i < Feature.entries.lastIndex, onFeature, onAppInfo, onLocation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun IntegrationRow(
|
||||
state: SteamIntegration.State,
|
||||
feature: Feature,
|
||||
focused: Boolean,
|
||||
divider: Boolean,
|
||||
onFeature: (Feature) -> Unit,
|
||||
onAppInfo: () -> Unit,
|
||||
onLocation: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val on = state.enabled(feature)
|
||||
var flash by remember { mutableStateOf(false) }
|
||||
val reveal = remember { BringIntoViewRequester() }
|
||||
LaunchedEffect(focused) {
|
||||
if (focused) try { flash = true; reveal.bringIntoView(); kotlinx.coroutines.delay(1600) } finally { flash = false }
|
||||
}
|
||||
val bg by animateColorAsState(if (flash) pal.signal.copy(alpha = 0.12f) else Color.Transparent, Motion.tw(400), label = "integrationFlash")
|
||||
val wifiLocationOff = feature == Feature.WIFI && state.wifi && state.locationPermission && !state.locationOn
|
||||
val wifiDenied = feature == Feature.WIFI && !state.locationPermission && state.locationBlocked
|
||||
val needsHome = feature == Feature.SHORTCUTS && !state.home
|
||||
val restricted = feature == Feature.SHORTCUTS && !needsHome && !state.shortcuts && state.shortcutsRestricted
|
||||
val maybeRestricted = feature == Feature.SHORTCUTS && !needsHome && !state.shortcuts && !restricted && state.shortcutsTried &&
|
||||
android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU
|
||||
val hint = stringResource(when {
|
||||
wifiLocationOff -> R.string.integration_wifi_location_off
|
||||
wifiDenied -> R.string.integration_wifi_denied
|
||||
needsHome -> R.string.integration_shortcuts_needs_home
|
||||
restricted -> R.string.integration_shortcuts_restricted
|
||||
maybeRestricted -> R.string.integration_shortcuts_maybe_restricted
|
||||
feature == Feature.WIFI -> if (on) R.string.integration_wifi_on else R.string.integration_wifi_hint
|
||||
feature == Feature.BRIGHTNESS -> R.string.integration_brightness_hint
|
||||
feature == Feature.HOME -> R.string.integration_home_hint
|
||||
else -> R.string.integration_shortcuts_hint
|
||||
})
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = Modifier.fillMaxWidth().bringIntoViewRequester(reveal).background(bg).heightIn(min = 64.dp)
|
||||
.padding(horizontal = 14.dp, vertical = 10.dp)
|
||||
.testTag("integration-${feature.name.lowercase()}"),
|
||||
) {
|
||||
FeatureBadge(featureIcon(feature), on)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(featureTitle(feature)), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(hint, fontSize = 13.sp, color = if (wifiLocationOff || wifiDenied || restricted) AttentionAmber else colors.onSurfaceVariant,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
when {
|
||||
wifiLocationOff -> SecondaryButton(stringResource(R.string.integration_location), compact = true, onClick = onLocation)
|
||||
wifiDenied -> SecondaryButton(stringResource(R.string.integration_app_info), compact = true, onClick = onLocation)
|
||||
restricted || maybeRestricted -> SecondaryButton(stringResource(R.string.integration_app_info), compact = true, onClick = onAppInfo)
|
||||
}
|
||||
val checked = if (feature == Feature.WIFI) state.wifi && state.locationPermission else on
|
||||
ToggleSwitch(checked, enabled = !needsHome && !restricted, label = stringResource(featureTitle(feature)),
|
||||
modifier = Modifier.testTag("integration-action-${feature.name.lowercase()}")) { onFeature(feature) }
|
||||
}
|
||||
}
|
||||
if (divider) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FeatureBadge(icon: ImageVector, on: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val tint by animateColorAsState(if (on) pal.good else colors.onSurfaceVariant, Motion.tw(250), label = "badgeTint")
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(36.dp).clip(BadgeShape)
|
||||
.background(if (on) pal.good.copy(alpha = 0.14f) else colors.surfaceVariant)
|
||||
.border(1.dp, if (on) pal.good.copy(alpha = 0.3f) else pal.line2, BadgeShape),
|
||||
) { Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(19.dp)) }
|
||||
}
|
||||
|
||||
private fun featureIcon(feature: Feature) = when (feature) {
|
||||
Feature.WIFI -> Icons.Outlined.Wifi
|
||||
Feature.BRIGHTNESS -> Icons.Outlined.LightMode
|
||||
Feature.HOME -> Icons.Outlined.Home
|
||||
Feature.SHORTCUTS -> Icons.Outlined.KeyboardCommandKey
|
||||
}
|
||||
|
||||
private fun featureTitle(feature: Feature) = when (feature) {
|
||||
Feature.WIFI -> R.string.integration_wifi
|
||||
Feature.BRIGHTNESS -> R.string.integration_brightness
|
||||
Feature.HOME -> R.string.integration_home
|
||||
Feature.SHORTCUTS -> R.string.integration_shortcuts
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun IntegrationSuggestion(state: SteamIntegration.State, onOpen: () -> Unit, onLater: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val pill = RoundedCornerShape(99.dp)
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.clip(pill).background(colors.surfaceVariant.copy(alpha = 0.85f))
|
||||
.border(1.dp, pal.signal.copy(alpha = 0.3f), pill).testTag("integration-suggestion"),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.heightIn(min = 40.dp).clip(pill).glideBorder(hot, pill, pal.signal, Color.Transparent)
|
||||
.hoverable(src).clickable(role = Role.Button, interactionSource = src, indication = LocalIndication.current, onClick = onOpen)
|
||||
.controllerConfirm(onClick = onOpen)
|
||||
.padding(start = 12.dp, end = 10.dp, top = 6.dp, bottom = 6.dp),
|
||||
) {
|
||||
Icon(Icons.Outlined.AutoAwesome, contentDescription = null, tint = pal.signal, modifier = Modifier.size(16.dp))
|
||||
Text(stringResource(R.string.integration_title), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
|
||||
Text(stringResource(R.string.integration_count, state.enabledCount(), Feature.entries.size), fontSize = 12.sp,
|
||||
color = colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
val closeSrc = remember { MutableInteractionSource() }
|
||||
val closeHot = rememberHot(closeSrc)
|
||||
val later = stringResource(R.string.integration_later)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.padding(end = 4.dp).size(32.dp).clip(CircleShape)
|
||||
.background(if (closeHot) pal.signal.copy(alpha = 0.16f) else Color.Transparent)
|
||||
.glideBorder(closeHot, CircleShape, pal.signal, Color.Transparent)
|
||||
.hoverable(closeSrc).clickable(role = Role.Button, interactionSource = closeSrc, indication = LocalIndication.current, onClick = onLater)
|
||||
.controllerConfirm(onClick = onLater)
|
||||
.semantics { contentDescription = later },
|
||||
) { Icon(Icons.Outlined.Close, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.size(16.dp)) }
|
||||
}
|
||||
}
|
||||
@@ -157,7 +157,7 @@ private fun FlathubHero(s: FrontEndState, ring: Int) {
|
||||
StoreState.sections.values.flatten().mapNotNull { it.icon }.distinct().take(48).takeIf { it.size >= 8 }.orEmpty()
|
||||
}
|
||||
val busy = StoreState.busy == "setup"
|
||||
BoxWithConstraints(Modifier.fillMaxSize().padding(horizontal = if (narrow) 14.dp else 22.dp).padding(top = if (narrow) 10.dp else 14.dp)) {
|
||||
BoxWithConstraints(Modifier.fillMaxSize().padding(horizontal = if (narrow) 14.dp else 22.dp, vertical = if (narrow) 10.dp else 14.dp)) {
|
||||
val shape = RoundedCornerShape(20.dp)
|
||||
Box(Modifier.fillMaxWidth().height(maxHeight.coerceAtLeast(320.dp)).clip(shape).background(colors.background).border(1.dp, pal.line, shape)) {
|
||||
androidx.compose.animation.Crossfade(icons, animationSpec = Motion.tw(600), label = "flathubWall") { tiles ->
|
||||
@@ -316,7 +316,7 @@ internal fun Storefront(s: FrontEndState, a: FrontEndActions) {
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(horizontal = padH).padding(top = if (narrow) 10.dp else 14.dp)
|
||||
Modifier.fillMaxSize().padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp)
|
||||
.bumpers(
|
||||
onPrevious = { if (openApp == null) mode = modes[(modes.indexOf(mode) + modes.size - 1) % modes.size] },
|
||||
onNext = { if (openApp == null) mode = modes[(modes.indexOf(mode) + 1) % modes.size] },
|
||||
|
||||
@@ -197,7 +197,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
LaunchedEffect(StoresState.openDownloads) { if (StoresState.openDownloads) { chip = DOWNLOADS; StoresState.openDownloads = false } }
|
||||
val store = Store.byId(chip)
|
||||
LaunchedEffect(tabs.toList()) {
|
||||
if (chip != DOWNLOADS && Store.byId(chip) !in shownStores) chip = shownStores.firstOrNull()?.id ?: DOWNLOADS
|
||||
if (chip != DOWNLOADS && chip != GEFORCE_NOW && Store.byId(chip) !in shownStores) chip = shownStores.firstOrNull()?.id ?: DOWNLOADS
|
||||
}
|
||||
val pane = PaneKey(
|
||||
chip,
|
||||
@@ -250,8 +250,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
}
|
||||
val pal = LocalPalette.current
|
||||
fun cycleStore(step: Int) {
|
||||
val ids = tabs.filter { it.shown }.map { it.store.id }
|
||||
if (ids.isEmpty()) return
|
||||
val ids = tabs.filter { it.shown }.map { it.store.id } + GEFORCE_NOW
|
||||
val at = ids.indexOf(chip)
|
||||
pickChip(ids[if (at < 0) (if (step > 0) 0 else ids.size - 1) else (at + step + ids.size) % ids.size])
|
||||
}
|
||||
@@ -311,7 +310,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
val backLabel = stringResource(R.string.common_back)
|
||||
Box(modifier.onGloballyPositioned { hostAt = it.positionInRoot() }) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(horizontal = padH).padding(top = if (narrow) 10.dp else 14.dp)
|
||||
modifier = Modifier.fillMaxSize().padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp)
|
||||
.then(if (openGame != null && !arranging) Modifier else Modifier.bumpers(
|
||||
onPrevious = {
|
||||
val picked = Store.byId(focusedChip)
|
||||
@@ -324,11 +323,12 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
)),
|
||||
) {
|
||||
Box(Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
|
||||
StoreTheme(Store.byId(focusedChip ?: chip)) {
|
||||
StoreTheme(Store.byId(focusedChip ?: chip), gfn = (focusedChip ?: chip) == GEFORCE_NOW) {
|
||||
Rise(0) {
|
||||
StoreChips(
|
||||
chip, focusedChip, s.storeDownloadsActive, tabs, arranging,
|
||||
onStore = { st -> openModes(st) },
|
||||
onGfn = { if (chip != GEFORCE_NOW) pickChip(GEFORCE_NOW) else move("first") },
|
||||
onDownloads = { if (chip != DOWNLOADS) pickChip(DOWNLOADS) else move("first") },
|
||||
onFocusChip = { focusedChip = it },
|
||||
onArrangeDone = { arranging = false },
|
||||
@@ -364,13 +364,14 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
|
||||
CompositionLocalProvider(LocalFrontFocus provides if (outgoing) null else LocalFrontFocus.current) {
|
||||
val leavingNow = androidx.compose.runtime.rememberUpdatedState(outgoing)
|
||||
val st = Store.byId(k.chip)
|
||||
StoreTheme(st) {
|
||||
StoreTheme(st, gfn = k.chip == GEFORCE_NOW) {
|
||||
Column(
|
||||
Modifier.fillMaxSize()
|
||||
.focusProperties { enter = { if (leavingNow.value) androidx.compose.ui.focus.FocusRequester.Cancel else androidx.compose.ui.focus.FocusRequester.Default } }
|
||||
.focusGroup(),
|
||||
) {
|
||||
when {
|
||||
k.chip == GEFORCE_NOW -> GfnPane(viewportH - 20.dp)
|
||||
k.chip == DOWNLOADS -> Column(Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) { StoresDownloadsPane(s, a) }
|
||||
st == null -> {}
|
||||
!k.accountsLoaded -> Box(Modifier.fillMaxWidth().padding(top = 16.dp)) {
|
||||
@@ -588,17 +589,17 @@ private fun RowScope.ArrangeStoreChip(
|
||||
@Composable
|
||||
private fun StoreChips(
|
||||
selected: String, focused: String?, active: Int, tabs: List<StoreTab>, arranging: Boolean,
|
||||
onStore: (Store) -> Unit, onDownloads: () -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit,
|
||||
onStore: (Store) -> Unit, onGfn: () -> Unit, onDownloads: () -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit,
|
||||
onArrangeDone: () -> Unit, onMoveTab: (Store, Int) -> Unit, onToggleTab: (Store) -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val keys = tabs.filter { it.shown }.map { it.store.id } + DOWNLOADS
|
||||
val keys = tabs.filter { it.shown }.map { it.store.id } + GEFORCE_NOW + DOWNLOADS
|
||||
val bounds = remember { androidx.compose.runtime.mutableStateMapOf<String, Rect>() }
|
||||
val highlighted = focused ?: selected
|
||||
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode
|
||||
val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard && !arranging
|
||||
val tint = androidx.compose.animation.animateColorAsState(
|
||||
Store.byId(highlighted)?.let { sourceColours(it.id).dot } ?: pal.signal, Motion.tw(160), label = "chipTint",
|
||||
Store.byId(highlighted)?.let { sourceColours(it.id).dot } ?: if (highlighted == GEFORCE_NOW) GfnGreen else pal.signal, Motion.tw(160), label = "chipTint",
|
||||
)
|
||||
val gap = 8.dp
|
||||
val gapPx = with(androidx.compose.ui.platform.LocalDensity.current) { gap.toPx() }
|
||||
@@ -630,6 +631,17 @@ private fun StoreChips(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!arranging) key(GEFORCE_NOW) {
|
||||
val reveal = remember { BringIntoViewRequester() }
|
||||
LaunchedEffect(selected) { if (selected == GEFORCE_NOW) reveal.bringIntoView() }
|
||||
val signedIn = com.droiddeck.launcher.stores.gfn.GfnState.phase is com.droiddeck.launcher.stores.gfn.GfnState.Phase.SignedIn
|
||||
StoreChip(
|
||||
label = stringResource(R.string.gfn_name), on = selected == GEFORCE_NOW, under = fillShown && highlighted == GEFORCE_NOW, key = GEFORCE_NOW, mark = GfnGreen,
|
||||
modifier = Modifier.bringIntoViewRequester(reveal).onGloballyPositioned { bounds[GEFORCE_NOW] = it.boundsInParent() },
|
||||
lead = { Box(Modifier.size(12.dp).background(GfnGreen.copy(alpha = if (signedIn) 1f else 0.35f), CircleShape)) },
|
||||
description = stringResource(R.string.gfn_name), onFocused = onFocusChip,
|
||||
) { onGfn() }
|
||||
}
|
||||
}
|
||||
ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown && highlighted != DOWNLOADS)
|
||||
}
|
||||
@@ -1159,7 +1171,8 @@ internal fun FlathubTheme(content: @Composable () -> Unit) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun StoreTheme(store: Store?, content: @Composable () -> Unit) {
|
||||
internal fun StoreTheme(store: Store?, gfn: Boolean = false, content: @Composable () -> Unit) {
|
||||
if (gfn) return GfnTheme(content)
|
||||
val base = LocalPalette.current
|
||||
val p = remember(base, store) { storePalette(base, store) }
|
||||
val scheme = MaterialTheme.colorScheme.copy(primary = p.primary, onPrimary = p.onPrimary)
|
||||
|
||||
@@ -115,7 +115,7 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
|
||||
}
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
||||
val stacked = LocalNarrowPane.current || maxWidth < 600.dp
|
||||
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
|
||||
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
|
||||
if (stacked) {
|
||||
StatusPanel(s, u, ua, me)
|
||||
Box(Modifier.height(18.dp))
|
||||
|
||||
@@ -360,7 +360,6 @@ internal fun AdbTextField(
|
||||
onNext: (() -> Unit)? = null,
|
||||
onDone: (() -> Unit)? = null,
|
||||
focusOnShow: Boolean = false,
|
||||
showLabel: Boolean = true,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val focusAsked = remember { booleanArrayOf(false) }
|
||||
@@ -375,7 +374,7 @@ internal fun AdbTextField(
|
||||
val colors = MaterialTheme.colorScheme
|
||||
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
if (showLabel) Text(
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = FontWeight.Medium,
|
||||
|
||||
@@ -200,31 +200,18 @@ object AppUpdates {
|
||||
fun message(context: Context): String = context.getString(text, *args)
|
||||
}
|
||||
|
||||
fun follow(context: Context, catalog: Catalog?): Follow = follow(context, catalog, installed())
|
||||
|
||||
internal fun follow(context: Context, catalog: Catalog?, me: Installed): Follow {
|
||||
fun follow(context: Context, catalog: Catalog?): Follow {
|
||||
stored(context)?.let { return it }
|
||||
val guess = guessFollow(catalog, me)
|
||||
if (guess.certain) setFollow(context, guess.follow)
|
||||
return guess.follow
|
||||
}
|
||||
|
||||
internal class Guess(val follow: Follow, val certain: Boolean)
|
||||
|
||||
/**
|
||||
* Stable and Preview builds of one commit are the same APK. Preview history can include older Stable releases,
|
||||
* so an overlapping older-build guess keeps the Stable default for this run without persisting it.
|
||||
*/
|
||||
internal fun guessFollow(catalog: Catalog?, me: Installed): Guess {
|
||||
if (me.pr != 0) return Guess(Follow(Channel.TEST, me.pr), true)
|
||||
val stable = catalog?.stable
|
||||
if (stable != null && isRunning(stable, me)) return Guess(Follow(Channel.STABLE), true)
|
||||
val publishedPreview = catalog != null && me.updatable && (
|
||||
catalog.preview?.let { isRunning(it, me) } == true ||
|
||||
catalog.recentPreviews.any { matchesInstalledCommit(it.commit, me.commit) }
|
||||
)
|
||||
if (stable?.version?.let { compareVersions(me.version, it) < 0 } == true) return Guess(Follow(Channel.STABLE), !publishedPreview)
|
||||
return Guess(Follow(if (publishedPreview) Channel.NIGHTLY else Channel.STABLE), false)
|
||||
val me = installed()
|
||||
val inferred = when {
|
||||
me.pr != 0 -> Follow(Channel.TEST, me.pr)
|
||||
catalog == null -> return Follow(Channel.STABLE)
|
||||
catalog.stable != null && isRunning(catalog.stable, me) -> Follow(Channel.STABLE)
|
||||
me.updatable -> Follow(Channel.NIGHTLY)
|
||||
else -> Follow(Channel.STABLE)
|
||||
}
|
||||
setFollow(context, inferred)
|
||||
return inferred
|
||||
}
|
||||
|
||||
fun setFollow(context: Context, follow: Follow) {
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
package com.droiddeck.launcher.wayland
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.Process
|
||||
import android.view.Choreographer
|
||||
import android.view.Surface
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
|
||||
object CompositorHost {
|
||||
@@ -18,22 +14,8 @@ object CompositorHost {
|
||||
@Volatile
|
||||
private var vsyncRunning = false
|
||||
|
||||
@Volatile
|
||||
private var ownVsyncThread = true
|
||||
|
||||
// The screen tick gets its own thread so a busy main thread cannot delay the compositor's frames.
|
||||
private val vsyncThread: HandlerThread by lazy {
|
||||
HandlerThread("droiddeck-vsync", Process.THREAD_PRIORITY_DISPLAY).apply { start() }
|
||||
}
|
||||
private val vsyncHandler: Handler by lazy { Handler(vsyncThread.looper) }
|
||||
|
||||
@Volatile
|
||||
private var vsyncGeneration = 0
|
||||
|
||||
// Each resume gets a new callback; one left queued from an earlier resume, on either thread, stops itself.
|
||||
private fun vsyncCallback(generation: Int) = object : Choreographer.FrameCallback {
|
||||
private val vsync = object : Choreographer.FrameCallback {
|
||||
override fun doFrame(frameTimeNanos: Long) {
|
||||
if (generation != vsyncGeneration) return
|
||||
WaylandCompositor.nativeVsync(frameTimeNanos)
|
||||
if (vsyncRunning) Choreographer.getInstance().postFrameCallback(this)
|
||||
}
|
||||
@@ -52,8 +34,6 @@ object CompositorHost {
|
||||
refreshHz: Float,
|
||||
fpsLimit: Int,
|
||||
): Boolean {
|
||||
ownVsyncThread = SessionPrefs.vsyncThread(context)
|
||||
WaylandCompositor.nativeSetRenderOnCommit(SessionPrefs.renderOnCommit(context))
|
||||
pace(refreshHz, fpsLimit)
|
||||
if (!SessionState.running) WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight)
|
||||
if (started) {
|
||||
@@ -123,14 +103,8 @@ object CompositorHost {
|
||||
|
||||
private fun resumeVsync() {
|
||||
if (vsyncRunning) return
|
||||
val callback = vsyncCallback(++vsyncGeneration)
|
||||
vsyncRunning = true
|
||||
WaylandCompositor.nativeLog("screen", if (ownVsyncThread) "screen tick runs on its own display-priority thread" else "screen tick runs on the main thread")
|
||||
if (!ownVsyncThread) {
|
||||
Choreographer.getInstance().postFrameCallback(callback)
|
||||
return
|
||||
}
|
||||
vsyncHandler.post { Choreographer.getInstance().postFrameCallback(callback) }
|
||||
Choreographer.getInstance().postFrameCallback(vsync)
|
||||
}
|
||||
|
||||
private fun pauseVsync() {
|
||||
|
||||
@@ -284,8 +284,6 @@ public final class WaylandCompositor {
|
||||
|
||||
public static native void nativeSetFpsLimit(int fps);
|
||||
|
||||
public static native void nativeSetRenderOnCommit(boolean on);
|
||||
|
||||
public static native void nativeSetGpuTurbo(boolean on);
|
||||
|
||||
public static native int nativeRaisePriority(int tid, int nice);
|
||||
|
||||
@@ -2025,6 +2025,7 @@
|
||||
<string name="display_filter_live">يُطبَّق فوريًا. مشترك بين Steam وسطح المكتب.</string>
|
||||
<string name="display_filter_note">تُطبَّق FSR و GSR و NIS عند تكبير صورة الجلسة. ويعمل خيار «زيادة الحدة فقط» أيضًا دون تكبير.</string>
|
||||
<string name="display_sharpness">حدّة المرشِّح</string>
|
||||
<string name="display_frame_rate">معدّل الإطارات</string>
|
||||
<string name="display_look_filter">%1$s يضبط أسلوب التكبير على %2$s.</string>
|
||||
<string name="display_match_screen">مطابقة الشاشة (%1$d×%2$d)</string>
|
||||
<string name="display_follow_screen">اتباع الشاشة (يُغيَّر الحجم عند الطي أو الفتح)</string>
|
||||
@@ -3218,55 +3219,6 @@
|
||||
<string name="library_remove">إزالة من المكتبة</string>
|
||||
<string name="library_in">في المكتبة</string>
|
||||
<string name="xbox_filter_show">عرض</string>
|
||||
<string name="itch_collections">المجموعات</string>
|
||||
<string name="stores_itch_updates_found">التحديثات المتاحة: %1$d</string>
|
||||
<string name="stores_itch_update_replaced">استبدل المطوّر هذا الإصدار بـ %1$s. هل تريد التحديث إليه؟</string>
|
||||
<string name="xbox_filter_cloud">سحابية</string>
|
||||
<string name="stores_xbox_cloud_settings">إعدادات السحابة</string>
|
||||
<string name="apps_search_hint">البحث في التطبيقات</string>
|
||||
<string name="apps_no_match">لا توجد تطبيقات تطابق ”%1$s“.</string>
|
||||
<string name="apps_add_widget">إضافة أداة</string>
|
||||
<string name="apps_widgets_loading">جارٍ تحميل الأدوات…</string>
|
||||
<string name="apps_widgets_none">لا توجد تطبيقات على هذا الجهاز توفّر أدوات.</string>
|
||||
<string name="apps_widget_wider">أعرض</string>
|
||||
<string name="apps_widget_narrower">أضيق</string>
|
||||
<string name="apps_widget_taller">أطول</string>
|
||||
<string name="apps_widget_shorter">أقصر</string>
|
||||
<string name="apps_widget_move_earlier">نقل إلى الأمام</string>
|
||||
<string name="apps_widget_move_later">نقل إلى الخلف</string>
|
||||
<string name="apps_widget_configure">إعدادات الأداة</string>
|
||||
<string name="apps_widget_remove">إزالة الأداة</string>
|
||||
<string name="apps_add_to_folder">إضافة إلى مجلد</string>
|
||||
<string name="apps_new_folder">مجلد جديد</string>
|
||||
<string name="apps_remove_from_folder">إزالة من المجلد</string>
|
||||
<string name="apps_app_info">معلومات التطبيق</string>
|
||||
<string name="apps_uninstall">إلغاء التثبيت</string>
|
||||
<string name="apps_folder_rename">إعادة التسمية</string>
|
||||
<string name="apps_folder_ungroup">فك التجميع</string>
|
||||
<string name="apps_folder_default">مجلد</string>
|
||||
<string name="apps_folder_name">اسم المجلد</string>
|
||||
<string name="apps_filter">عرض</string>
|
||||
<string name="apps_filter_all">كل التطبيقات</string>
|
||||
<string name="apps_filter_games">الألعاب</string>
|
||||
<string name="apps_filter_downloaded">المنزّلة</string>
|
||||
<string name="apps_filter_system">النظام</string>
|
||||
<string name="apps_filter_hidden">المخفية</string>
|
||||
<string name="apps_hide">إخفاء</string>
|
||||
<string name="apps_unhide">إظهار في التطبيقات</string>
|
||||
<string name="apps_shortcut_remove">إزالة الاختصار</string>
|
||||
<string name="apps_pin_title">إضافة إلى التطبيقات</string>
|
||||
<string name="apps_pin_add">إضافة</string>
|
||||
<string name="apps_hidden_none">لا توجد تطبيقات مخفية.</string>
|
||||
<string name="apps_sort_name_asc">الاسم أ–ي</string>
|
||||
<string name="apps_sort_name_desc">الاسم ي–أ</string>
|
||||
<string name="apps_sort_installed">المثبّتة مؤخرًا</string>
|
||||
<string name="apps_sort_updated">المحدّثة مؤخرًا</string>
|
||||
<plurals name="apps_count">
|
||||
<item quantity="zero">%d تطبيق</item>
|
||||
<item quantity="one">تطبيق واحد</item>
|
||||
<item quantity="two">تطبيقان</item>
|
||||
<item quantity="few">%d تطبيقات</item>
|
||||
<item quantity="many">%d تطبيقًا</item>
|
||||
<item quantity="other">%d تطبيق</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
@@ -1994,6 +1994,7 @@
|
||||
<string name="display_filter_live">Se aplica al instante. Compartido por Steam y Escritorio.</string>
|
||||
<string name="display_filter_note">FSR, GSR y NIS se aplican al ampliar la imagen de la sesión. Solo nitidez también funciona sin ampliar.</string>
|
||||
<string name="display_sharpness">Nitidez del filtro</string>
|
||||
<string name="display_frame_rate">Velocidad de fotogramas</string>
|
||||
<string name="display_look_filter">%1$s Cambia el escalado a %2$s.</string>
|
||||
<string name="display_match_screen">Igual a la pantalla (%1$d×%2$d)</string>
|
||||
<string name="display_follow_screen">Seguir la pantalla (cambia de tamaño al plegar o desplegar)</string>
|
||||
@@ -3068,52 +3069,6 @@
|
||||
<string name="library_remove">Quitar de Biblioteca</string>
|
||||
<string name="library_in">En Biblioteca</string>
|
||||
<string name="xbox_filter_show">Mostrar</string>
|
||||
<string name="itch_collections">Colecciones</string>
|
||||
<string name="stores_itch_updates_found">Actualizaciones disponibles: %1$d</string>
|
||||
<string name="stores_itch_update_replaced">El desarrollador reemplazó esta versión por %1$s. ¿Actualizar a ella?</string>
|
||||
<string name="xbox_filter_cloud">Nube</string>
|
||||
<string name="stores_xbox_cloud_settings">Configuración de nube</string>
|
||||
<string name="apps_search_hint">Buscar apps</string>
|
||||
<string name="apps_no_match">Ninguna app coincide con «%1$s».</string>
|
||||
<string name="apps_add_widget">Agregar widget</string>
|
||||
<string name="apps_widgets_loading">Cargando widgets…</string>
|
||||
<string name="apps_widgets_none">Ninguna app de este dispositivo ofrece widgets.</string>
|
||||
<string name="apps_widget_wider">Más ancho</string>
|
||||
<string name="apps_widget_narrower">Más angosto</string>
|
||||
<string name="apps_widget_taller">Más alto</string>
|
||||
<string name="apps_widget_shorter">Más bajo</string>
|
||||
<string name="apps_widget_move_earlier">Mover antes</string>
|
||||
<string name="apps_widget_move_later">Mover después</string>
|
||||
<string name="apps_widget_configure">Configuración del widget</string>
|
||||
<string name="apps_widget_remove">Quitar widget</string>
|
||||
<string name="apps_add_to_folder">Agregar a carpeta</string>
|
||||
<string name="apps_new_folder">Carpeta nueva</string>
|
||||
<string name="apps_remove_from_folder">Quitar de la carpeta</string>
|
||||
<string name="apps_app_info">Información de la app</string>
|
||||
<string name="apps_uninstall">Desinstalar</string>
|
||||
<string name="apps_folder_rename">Cambiar nombre</string>
|
||||
<string name="apps_folder_ungroup">Desagrupar</string>
|
||||
<string name="apps_folder_default">Carpeta</string>
|
||||
<string name="apps_folder_name">Nombre de la carpeta</string>
|
||||
<string name="apps_filter">Mostrar</string>
|
||||
<string name="apps_filter_all">Todas las apps</string>
|
||||
<string name="apps_filter_games">Juegos</string>
|
||||
<string name="apps_filter_downloaded">Descargadas</string>
|
||||
<string name="apps_filter_system">Sistema</string>
|
||||
<string name="apps_filter_hidden">Ocultas</string>
|
||||
<string name="apps_hide">Ocultar</string>
|
||||
<string name="apps_unhide">Mostrar en apps</string>
|
||||
<string name="apps_shortcut_remove">Quitar acceso directo</string>
|
||||
<string name="apps_pin_title">Agregar a Apps</string>
|
||||
<string name="apps_pin_add">Agregar</string>
|
||||
<string name="apps_hidden_none">No hay apps ocultas.</string>
|
||||
<string name="apps_sort_name_asc">Nombre A–Z</string>
|
||||
<string name="apps_sort_name_desc">Nombre Z–A</string>
|
||||
<string name="apps_sort_installed">Instaladas recientemente</string>
|
||||
<string name="apps_sort_updated">Actualizadas recientemente</string>
|
||||
<plurals name="apps_count">
|
||||
<item quantity="one">%d app</item>
|
||||
<item quantity="many">%d apps</item>
|
||||
<item quantity="other">%d apps</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
@@ -1941,6 +1941,7 @@
|
||||
<string name="display_filter_live">Прилага се веднага. Общ за Steam и Desktop.</string>
|
||||
<string name="display_filter_note">FSR, GSR и NIS се прилагат при уголемяване на изображението на сесията. „Само изостряне“ работи и без уголемяване.</string>
|
||||
<string name="display_sharpness">Острота на филтъра</string>
|
||||
<string name="display_frame_rate">Честота на кадрите</string>
|
||||
<string name="display_look_filter">%1$s Задава мащабиране на %2$s.</string>
|
||||
<string name="display_match_screen">Напасване на екрана (%1$d×%2$d)</string>
|
||||
<string name="display_follow_screen">Следване на екрана (преоразмерява при сгъване или разгъване)</string>
|
||||
@@ -3082,51 +3083,6 @@
|
||||
<string name="library_remove">Премахни от Библиотека</string>
|
||||
<string name="library_in">В Библиотека</string>
|
||||
<string name="xbox_filter_show">Показване</string>
|
||||
<string name="itch_collections">Колекции</string>
|
||||
<string name="stores_itch_updates_found">Налични актуализации: %1$d</string>
|
||||
<string name="stores_itch_update_replaced">Разработчикът замени тази версия с %1$s. Да се актуализира ли до нея?</string>
|
||||
<string name="xbox_filter_cloud">Облак</string>
|
||||
<string name="stores_xbox_cloud_settings">Настройки на облака</string>
|
||||
<string name="apps_search_hint">Търсене на приложения</string>
|
||||
<string name="apps_no_match">Няма приложения, отговарящи на „%1$s“.</string>
|
||||
<string name="apps_add_widget">Добавяне на приспособление</string>
|
||||
<string name="apps_widgets_loading">Приспособленията се зареждат…</string>
|
||||
<string name="apps_widgets_none">Няма приложения с приспособления на това устройство.</string>
|
||||
<string name="apps_widget_wider">По-широко</string>
|
||||
<string name="apps_widget_narrower">По-тясно</string>
|
||||
<string name="apps_widget_taller">По-високо</string>
|
||||
<string name="apps_widget_shorter">По-ниско</string>
|
||||
<string name="apps_widget_move_earlier">Преместване по-рано</string>
|
||||
<string name="apps_widget_move_later">Преместване по-късно</string>
|
||||
<string name="apps_widget_configure">Настройки на приспособлението</string>
|
||||
<string name="apps_widget_remove">Премахване на приспособлението</string>
|
||||
<string name="apps_add_to_folder">Добавяне в папка</string>
|
||||
<string name="apps_new_folder">Нова папка</string>
|
||||
<string name="apps_remove_from_folder">Премахване от папката</string>
|
||||
<string name="apps_app_info">Информация за приложението</string>
|
||||
<string name="apps_uninstall">Деинсталиране</string>
|
||||
<string name="apps_folder_rename">Преименуване</string>
|
||||
<string name="apps_folder_ungroup">Разгрупиране</string>
|
||||
<string name="apps_folder_default">Папка</string>
|
||||
<string name="apps_folder_name">Име на папката</string>
|
||||
<string name="apps_filter">Показване</string>
|
||||
<string name="apps_filter_all">Всички приложения</string>
|
||||
<string name="apps_filter_games">Игри</string>
|
||||
<string name="apps_filter_downloaded">Изтеглени</string>
|
||||
<string name="apps_filter_system">Системни</string>
|
||||
<string name="apps_filter_hidden">Скрити</string>
|
||||
<string name="apps_hide">Скриване</string>
|
||||
<string name="apps_unhide">Показване в приложенията</string>
|
||||
<string name="apps_shortcut_remove">Премахване на прекия път</string>
|
||||
<string name="apps_pin_title">Добавяне към приложенията</string>
|
||||
<string name="apps_pin_add">Добавяне</string>
|
||||
<string name="apps_hidden_none">Няма скрити приложения.</string>
|
||||
<string name="apps_sort_name_asc">Име А–Я</string>
|
||||
<string name="apps_sort_name_desc">Име Я–А</string>
|
||||
<string name="apps_sort_installed">Наскоро инсталирани</string>
|
||||
<string name="apps_sort_updated">Наскоро актуализирани</string>
|
||||
<plurals name="apps_count">
|
||||
<item quantity="one">%d приложение</item>
|
||||
<item quantity="other">%d приложения</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
@@ -1983,6 +1983,7 @@
|
||||
<string name="display_filter_live">Použije se okamžitě. Sdíleno Steamem a Plochou.</string>
|
||||
<string name="display_filter_note">FSR, GSR a NIS se použijí při zvětšování obrazu relace. Jen zaostření funguje i bez zvětšení.</string>
|
||||
<string name="display_sharpness">Ostrost filtru</string>
|
||||
<string name="display_frame_rate">Snímková frekvence</string>
|
||||
<string name="display_look_filter">%1$s Nastaví škálování na %2$s.</string>
|
||||
<string name="display_match_screen">Podle obrazovky (%1$d×%2$d)</string>
|
||||
<string name="display_follow_screen">Sledovat obrazovku (změní velikost při složení nebo rozložení)</string>
|
||||
@@ -3150,53 +3151,6 @@
|
||||
<string name="library_remove">Odebrat z knihovny</string>
|
||||
<string name="library_in">V knihovně</string>
|
||||
<string name="xbox_filter_show">Zobrazit</string>
|
||||
<string name="itch_collections">Kolekce</string>
|
||||
<string name="stores_itch_updates_found">Dostupné aktualizace: %1$d</string>
|
||||
<string name="stores_itch_update_replaced">Vývojář nahradil tuto verzi souborem %1$s. Aktualizovat na ni?</string>
|
||||
<string name="xbox_filter_cloud">Cloud</string>
|
||||
<string name="stores_xbox_cloud_settings">Nastavení cloudu</string>
|
||||
<string name="apps_search_hint">Hledat aplikace</string>
|
||||
<string name="apps_no_match">Výrazu „%1$s“ neodpovídá žádná aplikace.</string>
|
||||
<string name="apps_add_widget">Přidat widget</string>
|
||||
<string name="apps_widgets_loading">Načítání widgetů…</string>
|
||||
<string name="apps_widgets_none">Žádná aplikace v zařízení nenabízí widgety.</string>
|
||||
<string name="apps_widget_wider">Širší</string>
|
||||
<string name="apps_widget_narrower">Užší</string>
|
||||
<string name="apps_widget_taller">Vyšší</string>
|
||||
<string name="apps_widget_shorter">Nižší</string>
|
||||
<string name="apps_widget_move_earlier">Posunout dříve</string>
|
||||
<string name="apps_widget_move_later">Posunout později</string>
|
||||
<string name="apps_widget_configure">Nastavení widgetu</string>
|
||||
<string name="apps_widget_remove">Odebrat widget</string>
|
||||
<string name="apps_add_to_folder">Přidat do složky</string>
|
||||
<string name="apps_new_folder">Nová složka</string>
|
||||
<string name="apps_remove_from_folder">Odebrat ze složky</string>
|
||||
<string name="apps_app_info">Informace o aplikaci</string>
|
||||
<string name="apps_uninstall">Odinstalovat</string>
|
||||
<string name="apps_folder_rename">Přejmenovat</string>
|
||||
<string name="apps_folder_ungroup">Zrušit složku</string>
|
||||
<string name="apps_folder_default">Složka</string>
|
||||
<string name="apps_folder_name">Název složky</string>
|
||||
<string name="apps_filter">Zobrazit</string>
|
||||
<string name="apps_filter_all">Všechny aplikace</string>
|
||||
<string name="apps_filter_games">Hry</string>
|
||||
<string name="apps_filter_downloaded">Stažené</string>
|
||||
<string name="apps_filter_system">Systémové</string>
|
||||
<string name="apps_filter_hidden">Skryté</string>
|
||||
<string name="apps_hide">Skrýt</string>
|
||||
<string name="apps_unhide">Zobrazit v aplikacích</string>
|
||||
<string name="apps_shortcut_remove">Odebrat zkratku</string>
|
||||
<string name="apps_pin_title">Přidat do aplikací</string>
|
||||
<string name="apps_pin_add">Přidat</string>
|
||||
<string name="apps_hidden_none">Žádné skryté aplikace.</string>
|
||||
<string name="apps_sort_name_asc">Název A–Z</string>
|
||||
<string name="apps_sort_name_desc">Název Z–A</string>
|
||||
<string name="apps_sort_installed">Nedávno nainstalované</string>
|
||||
<string name="apps_sort_updated">Nedávno aktualizované</string>
|
||||
<plurals name="apps_count">
|
||||
<item quantity="one">%d aplikace</item>
|
||||
<item quantity="few">%d aplikace</item>
|
||||
<item quantity="many">%d aplikace</item>
|
||||
<item quantity="other">%d aplikací</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
@@ -1941,6 +1941,7 @@
|
||||
<string name="display_filter_live">Træder i kraft øjeblikkeligt. Deles af Steam og Desktop.</string>
|
||||
<string name="display_filter_note">FSR, GSR og NIS anvendes ved forstørrelse af sessionsbilledet. Kun skærpning virker også uden forstørrelse.</string>
|
||||
<string name="display_sharpness">Filterskarphed</string>
|
||||
<string name="display_frame_rate">Billedfrekvens</string>
|
||||
<string name="display_look_filter">%1$s Indstiller skalering til %2$s.</string>
|
||||
<string name="display_match_screen">Match skærm (%1$d×%2$d)</string>
|
||||
<string name="display_follow_screen">Følg skærm (ændrer størrelse ved fold/udfold)</string>
|
||||
@@ -3082,51 +3083,6 @@
|
||||
<string name="library_remove">Fjern fra Bibliotek</string>
|
||||
<string name="library_in">I Bibliotek</string>
|
||||
<string name="xbox_filter_show">Vis</string>
|
||||
<string name="itch_collections">Samlinger</string>
|
||||
<string name="stores_itch_updates_found">Opdateringer tilgængelige: %1$d</string>
|
||||
<string name="stores_itch_update_replaced">Udvikleren har erstattet denne version med %1$s. Opdater til den?</string>
|
||||
<string name="xbox_filter_cloud">Sky</string>
|
||||
<string name="stores_xbox_cloud_settings">Skyindstillinger</string>
|
||||
<string name="apps_search_hint">Søg i apps</string>
|
||||
<string name="apps_no_match">Ingen apps matcher “%1$s”.</string>
|
||||
<string name="apps_add_widget">Tilføj widget</string>
|
||||
<string name="apps_widgets_loading">Indlæser widgets…</string>
|
||||
<string name="apps_widgets_none">Ingen apps på enheden tilbyder widgets.</string>
|
||||
<string name="apps_widget_wider">Bredere</string>
|
||||
<string name="apps_widget_narrower">Smallere</string>
|
||||
<string name="apps_widget_taller">Højere</string>
|
||||
<string name="apps_widget_shorter">Lavere</string>
|
||||
<string name="apps_widget_move_earlier">Flyt tidligere</string>
|
||||
<string name="apps_widget_move_later">Flyt senere</string>
|
||||
<string name="apps_widget_configure">Widgetindstillinger</string>
|
||||
<string name="apps_widget_remove">Fjern widget</string>
|
||||
<string name="apps_add_to_folder">Føj til mappe</string>
|
||||
<string name="apps_new_folder">Ny mappe</string>
|
||||
<string name="apps_remove_from_folder">Fjern fra mappe</string>
|
||||
<string name="apps_app_info">Appinfo</string>
|
||||
<string name="apps_uninstall">Afinstaller</string>
|
||||
<string name="apps_folder_rename">Omdøb</string>
|
||||
<string name="apps_folder_ungroup">Opløs</string>
|
||||
<string name="apps_folder_default">Mappe</string>
|
||||
<string name="apps_folder_name">Mappenavn</string>
|
||||
<string name="apps_filter">Vis</string>
|
||||
<string name="apps_filter_all">Alle apps</string>
|
||||
<string name="apps_filter_games">Spil</string>
|
||||
<string name="apps_filter_downloaded">Downloadet</string>
|
||||
<string name="apps_filter_system">System</string>
|
||||
<string name="apps_filter_hidden">Skjulte</string>
|
||||
<string name="apps_hide">Skjul</string>
|
||||
<string name="apps_unhide">Vis i apps</string>
|
||||
<string name="apps_shortcut_remove">Fjern genvej</string>
|
||||
<string name="apps_pin_title">Føj til Apps</string>
|
||||
<string name="apps_pin_add">Tilføj</string>
|
||||
<string name="apps_hidden_none">Ingen skjulte apps.</string>
|
||||
<string name="apps_sort_name_asc">Navn A–Å</string>
|
||||
<string name="apps_sort_name_desc">Navn Å–A</string>
|
||||
<string name="apps_sort_installed">Senest installeret</string>
|
||||
<string name="apps_sort_updated">Senest opdateret</string>
|
||||
<plurals name="apps_count">
|
||||
<item quantity="one">%d app</item>
|
||||
<item quantity="other">%d apps</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
Loaded 100 of 1011 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user